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

askedMay 27, 2014 at 1:47
user3002473's user avatar
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"?CommentedMay 27, 2014 at 1:50

1 Answer1

2

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).

answeredMay 27, 2014 at 1:51
Blckknght's user avatar
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy 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.