
Metaclasses in Python - fogus
http://stackoverflow.com/a/6581949
======
darklajid
Previously: <https://news.ycombinator.com/item?id=2860031>

------
lang
I find metaclasses philosophically unsound. If one introduces metaclasses,
what about meta-metaclasses, meta-meta-metaclasses. In this regard Self's
prototypical oop seems more coherent - there are only objects. Even
object/class duality looks philosophically more attractive than
object/class/metaclass trio.

~~~
lloeki
_meta_ is all relative and means 'beyond'. A metaclass being a class, it can
itself have a metaclass, and so on, and they are all only objects, where the
author's following excerpt embodies:

    
    
        MyClass = MetaClass()
        MyObject = MyClass()
    

Those two code blocks are effectively equivalent:

    
    
        class Quux(type):
            #__metaclass__ = type is implicit
            pass
        
        class Qux(object):
            __metaclass__ = Quux
            pass
    

and:

    
    
        Quux = type('Quux', (type,), {})
        Qux = Quux('Qux', (object,), {})
    

the ___metaclass___ attribute merely puts in words what's the callable being
called when the keyword _class_ gets parsed and subsequently handled in the
current namespace.

This class/object unification is one of a bunch of unifications I find
extremely satisfying when thinking about how Python ticks.

------
prolepunk
Is it me or the first metaclass example doesn't work.

I'm using Python 2.7.2+ on Debian and I can't get __metaclass__ force upper
case attributes inside of a 'module'

------
grunar
tl;dr don't use metaclasses

~~~
pjscott
Slightly longer version: don't use metaclasses unless you really know what
you're doing.

~~~
DrHankPym
Slightly shorter longer version: classes are objects, see 'type()'

------
lang
If I'm not mistaken the authors of Smalltalk realized that metaclasses were a
mistake long before they appeared in Python. Yet they were added to Python
anyway.

------
emehrkay
Python is a very cool language. I wonder if using __metaclass__ in some
fashion would allow for javascript-like prototyping.

~~~
beza1e1
What prototyping stuff is missing in Python?

~~~
emehrkay
Well in JS you could do String.prototype.fnName = function(){}; to add fnName
as a method to all strings even if they are already instantiated, is that
possible with Python?

~~~
oinksoft
Of course.

<http://codepad.org/3fWweqje>

~~~
emehrkay
Can it be done for built-in types?

~~~
maaku
No, unfortunately. That's one thing both Ruby and JS have over Python.

~~~
storborg
Some Python programmers might argue that's one thing Python has over Ruby and
JS.

~~~
dorkitude
Yup (see my response)

------
eschulte
If you find yourself doing things like this in Python you should probably
switch to Ruby.

