I was messing around with python metaclasses and I came across something very intriguing that I didn't know existed or was valid:
class Meta(type): def __new__(metacls, name, bases, kwargs, extra_thing=None): if extra_thing is not None: print(extra_thing) return super().__new__(metacls, name, bases, kwargs) def __init__(metacls, name, bases, kwargs, *args, **kwargs_): super().__init__(metacls, name, bases, kwargs)class TestClass(metaclass=Meta, extra_thing='foo'): passWhen you run this, 'foo' is printed.
So apparently, classes can have extra keyword arguments if their metaclasses allow for it.
If a scenario in which this functionality may be useful is found, is it okay to take advantage of it? Or should it be left alone in favour of other methods (such as defining a class wide variable extra_thing)?
- What do you mean by "is it okay"? Do you mean "is it documented behavior that I can rely on" or "is it good design"?BrenBarn– BrenBarn2014-05-27 01:50:06 +00:00CommentedMay 27, 2014 at 1:50
1 Answer1
The behavior isdocumented, so it's probably safe to use, if perhaps confusing to other programmers reading your code. Here's what the docs say:
Any other keyword arguments that are specified in the class definition are passed through to all metaclass operations described below.
The "operations" it describes are__prepare__ and calling metaclass itself (which will usually call the__new__ and/or__init__ methods of the metaclass).
Comments
Explore related questions
See similar questions with these tags.