M
M
mkone1122021-12-26 05:15:50
Python
mkone112, 2021-12-26 05:15:50

How to override metaclass's __new__ signature to add default values?

class Meta(type):
    def __new__(mcs, name, bases, dct=None):
        if not dct:
            dct = {}
        return super().__new__(mcs, name, bases, dct)
    def __init__(self, name, bases, dct):
        pass

Meta('NewClassName', tuple())

issues
type.__new__() takes exactly 3 arguments (2 given)

Nothing better came to my mind:
class Meta(type):
    def __new__(mcs, name, bases, *args, **kwargs):
        if not args and not kwargs:
            args = (dict(),)
        return super().__new__(mcs, name, bases, *args)
    def __init__(self, name, bases, *args, **kwargs):
        pass

Meta('NewClassName', tuple())

Question: Can this be done more concisely?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mkone112, 2021-12-27
@mkone112

class Meta(type):
    @classmethod
    def __prepare__(metacls, name, bases):
        ...
    def __new__(mcs, name, bases, dct=None):
        if not dct:
            dct = {}
        return super().__new__(mcs, name, bases, dct)

Meta('NewClassName', tuple())

Although I solved the issue using __init_subclass__

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question