Why do only callable objects get a __name__?

Steven D'Aprano steve at pearwood.info
Tue Nov 19 08:08:15 CET 2013


On Mon, 18 Nov 2013 22:36:34 -0800, John Ladasky wrote:

> I just had a look at the namedtuple source code.  Part of my conceptual
> problem stems from the fact that namedtuple() is what I think people
> call a "class factory" function, rather than a proper class constructor.
>  I'll read through this until I understand it.

That's right. Since it's a factory, you don't have advantage of the class 
syntax -- although that syntax is only syntactic sugar for something 
which actually ends up as a function call!

When you write:

class MyClass(ParentClass, OtherClass):
    a = 23
    def method(self, arg):
        code goes here

the interpreter converts that to a function call:


MyClass = type("MyClass", (ParentClass, OtherClass), ns)

where ns is a dict containing:

{'a': 23, 'method': function-object, ...}

and one or two other things automatically inserted for you. A factory 
function, being just a function, can't take advantage of any magic 
syntax. While you can put anything you like inside the function, the 
function can't see what's on the left hand side of the assignment to 
retrieve the name, so you have to manually provide it.


-- 
Steven



More information about the Python-list mailing list