3

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'):
    pass

When 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)?

1
  • 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"? Commented May 27, 2014 at 1:50

1 Answer 1

2

The behavior is documented, 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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.