Python 3 Metaprogramming
Why Stack Overflow recommends it
Stack Overflow users link it when answering questions about metaclasses, decorators and dynamic class creation, often pointing to specific timestamps.
Recommended by 7 people across 8 different months, 2013 to 2019.
What it is
David Beazley's three-hour PyCon tutorial on metaprogramming in Python 3, covering decorators, class decorators, descriptors and metaclasses. It focuses on idioms and examples that only work in Python 3, and includes live-coded demos such as importing XML as Python classes.
What people said
Strong rec Sebastian Wozny · 2015-10 · Stack Overflow · on “Instantiating class object with varying **kwargs dictionary - python”
For further fine grained control I recommend the excellent talk of David Beazley on Python metaprogramming: [this video]
Strong rec Sebastian Wozny · 2015-11 · Stack Overflow · on “Subclassing in python of instantiated superclass”
Inheritance Inheritance is such a nice thing in python, and I don't think you have to resort to getattr hacks, if you want those, scroll down. You can force the class dictionary to refer to another object: class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height class ColoredRectangle(Rectangle): def __init__(self, rect, color): self.__dict__ = rect.__dict__ self.color = color rect = Rectangle(3, 5) crect = ColoredRectangle(rect, color="blue") print crect.width, crect.height, crect.color #3 5 blue These two will refer to the same Rectangle object: crect.width=10 print rect.width, rect.height #10 5 This
Strong rec alkasm · 2019-08 · Stack Overflow · on “Defining a custom type that works with `typing.get_type_hints()`”
Just for fun, if you haven't seen David Beazley's excellent Python 3 metaprogramming tutorial [this video] , you might want to check it out. It's very long, very detailed, and super entertaining.
Recommends gatto · 2013-04 · Stack Overflow · on “Django passing object to class”
You can make classes on the fly: def foo(column): class Foo(object): if column == 'a': bar = 'a' foo = 'c' else: bar = 'b' return Foo for x in 'ab': cls = foo(x) print cls.bar print cls.foo There are other ways to do this, look up info on metaclasses. Here [this video] is a really good lecture on the subject. In your case I'd do: def import_data(column, *args, **kw): # make custom ContactCSVModel class ContactCSVModel(CsvModel): # IF column == x first_name = CharField() last_name = CharField() company = CharField() mobile = CharField() group = DjangoModelField(Group) contact_owner = DjangoModelField(User) class Meta: delimiter = "," dbModel = Contact update = {'keys': ["mobile", "group"]} return
Recommends christophe31 · 2013-07 · Stack Overflow · on “Generating django models from xml”
Here a talk which contains a tutorial to import an xml file as class: [this video] If you run with py3k, (I think this particular demo of this awesome and funny demonstration is compatible with python 2.6 and upper), you'll get the idea on how to replace your models.py by a models.xml. You'll have to adapt it to your xml format by yourself. (you'll need to look at least from around 2h to 2h32m) This talk explain a fun way to do it, the speaker doesn't seem convinced that it's a great idea. If you want to generate api models from WSDL, I would suggest you to still make your tables models in hard code as your database isn't dynamic I suppose. Simply make methods/static methods to translate api mode
Recommends tennabey · 2015-05 · Stack Overflow · on “Python: Class instances are classes”
If you check the type of 1 you get type(1) == int . If you check the type of int you get type(int) == type . A class whose instances are classes is called a metaclass and in Python you create metaclasses by subclassing type . class ClassClass(type): pass Technically collections.namedtuple is a metaclass, but it's actually cheating [LINK] . There's a great PyCon talk by David Beazly about metaprogramming in Python [this video] . It's long, but very interesting. He starts talking about metaclasses around the 27 minute mark.
Recommends MrAlexBailey · 2015-06 · Stack Overflow · on “Why does a decorated class looses its docstrings?”
@FelipeAguirre For some great examples of this type of work, watch this [this video] . The first 30 minutes especially.
Recommends henrywallace · 2016-09 · Stack Overflow · on “How to create a decorator that can be used either with or without parameters?”
Several answers here already address your problem nicely. With respect to style, however, I prefer solving this decorator predicament using functools.partial , as suggested in David Beazley's Python Cookbook 3 : from functools import partial, wraps def decorator(func=None, foo='spam'): if func is None: return partial(decorator, foo=foo) @wraps(func) def wrapper(*args, **kwargs): # do something with `func` and `foo`, if you're so inclined pass return wrapper While yes, you can just do @decorator() def f(*args, **kwargs): pass without funky workarounds, I find it strange looking, and I like having the option of simply decorating with @decorator . As for the secondary mission objective, redirec
Cites Sebastian Wozny · 2015-11 · Stack Overflow · on “Why does a class have the attributes of its metaclass?”
The class object B is of type UpperMeta . This has the consequence that all classmethods of UpperMeta are available on the class B . The attribute is not on the class B , but gets proxied from B 's class( B is the class, not an instance of B ) >>> print dir(B) # General lack of echo() ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] It's here: >>> print dir(B.__class__) ['__abstractmethods__', '__base__', ..., 'echo', 'mro'] From the documentation [LINK] : The default behavi
Cites Chris · 2018-11 · Stack Overflow · on “Using the __call__ method of a metaclass instead of __new__?”
I thought a fleshed out Python 3 version of pyroscope's answer might be handy for someone to copy, paste and hack about with (probably me, when I find myself back at this page looking it up again in 6 months). It is taken from this article [LINK] : class Meta(type): @classmethod def __prepare__(mcs, name, bases, **kwargs): print(' Meta.__prepare__(mcs=%s, name=%r, bases=%s, **%s)' % ( mcs, name, bases, kwargs )) return {} def __new__(mcs, name, bases, attrs, **kwargs): print(' Meta.__new__(mcs=%s, name=%r, bases=%s, attrs=[%s], **%s)' % ( mcs, name, bases, ', '.join(attrs), kwargs )) return super().__new__(mcs, name, bases, attrs) def __init__(cls, name, bases, attrs, **kwargs): print(' Meta