Why do only callable objects get a __name__?

Ian Kelly ian.g.kelly at gmail.com
Mon Nov 18 21:43:28 CET 2013

On Mon, Nov 18, 2013 at 1:13 PM, John Ladasky
<john_ladasky at sbcglobal.net> wrote:
> A few days ago, I asked about getting the original declared name of a function or method, and learned about the __name__ attribute.
> https://groups.google.com/forum/#!topic/comp.lang.python/bHvcuXgvdfA
> Of course, I have used __name__ for years in the common expression "if __name__ == "__main__") to determine whether a particular module is being run or merely imported.  But until recently, I never went deeper than that.
> I just created an object using collections.namedtuple, and was surprised to discover that it didn't have a __name__ -- even though something that behaves like __name__ is clearly accessible and printable.  Here's some minimal Python 3.3.2 code and output:
> =================================================
> from collections import namedtuple
> MyNamedTupleClass = namedtuple("ANamedTuple", ("foo", "bar"))
> nt = MyNamedTupleClass(1,2)
> print(nt)
> print(type(nt))
> # print(nt.__name__) # this would raise an AttributeError
> print(type(nt).__name__) # this is the desired output
> =================================================
> ANamedTuple(foo=1, bar=2)
> <class '__main__.ANamedTuple'>
> ANamedTuple
> =================================================
> As you can see, I snooped around in the object's type.  I found that the type, rather than the object itself, had the __name__ I was seeking.  I then read the Python docs concerning __name__ and found that this attribute is restricted to callable objects.
> This leads me to ask two questions:
> 1. WHY do only callable objects get a __name__?  A __name__ would seem to be a useful feature for other types.  Clearly, whoever implemented namedtuple thought it was useful to retain and display that information as a part of the string representation of the namedtuple (and I agree).

Classes and functions are frequently kept in module namespaces, where
they are known by a specific name.  The intent is that the __name__
attribute should match that name by which it is commonly referred.

Specific instances are not typically widely referred to by set names
in this way.  They are more commonly stored in variables that are used
to hold a wide variety of objects.

In the namedtuple example that you give, it seems that you would want
the names of all instances of the ANamedTuple class to be the same
"ANamedTuple", and I really don't see what the purpose of giving them
all the same name would be.

> 2. If I created a superclass of namedtuple which exposed type(namedtuple).__name__ in the namespace of the namedtuple itself, would I be doing anything harmful?

Probably not.  But why not just invent your own name attribute rather
than shadow the one that Python designates for classes and functions?

More information about the Python-list mailing list