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).

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?

Thanks as always for your insights.
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to