Special attributes added to classes on creation

Steven D'Aprano steve at pearwood.info
Sun Jul 3 12:02:23 EDT 2016


I have some code which can preprocess (using a metaclass) or postprocess
(using a decorator) a class:

@process
class K:
    pass


class K(metaclass=process):
    pass


Both should give the same result, but I have found that the results are
slightly different because the dict passed to process as a metaclass is
different from the the class dict seen by the decorator. I can demonstrate
the difference in Python 3.6 by using this metaclass/decorator:

class process(type):
    def __new__(meta, *args):
        if len(args) == 1:
            # decorator usage
            cls = args[0]
            d = cls.__dict__
        elif len(args) == 3:
            # metaclass usage
            name, bases, d = args
            cls = super().__new__(meta, *args)
        print(sorted(d.keys()))
        return cls


If I then try it against two identical (apart from their names) classes, I
get these results:


py> @process
... class K:
...     x = 1
...
['__dict__', '__doc__', '__module__', '__weakref__', 'x']
py> class Q(metaclass=process):
...     x = 1
...
['__module__', '__qualname__', 'x']



Now if I check the newly created Q, I see the same keys K has:

py> sorted(Q.__dict__.keys())
['__dict__', '__doc__', '__module__', '__weakref__', 'x']


Is there any documentation for exactly what keys are added to classes when? 




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list