3
\$\begingroup\$

I had an idea for a __first__ special method for a class. It would be run after __new__ and before __init__ the first time a specific object is instantiated but is not then run if you instantiate the object again. For example, if you run:

class Foo:
    def __first__():
        print('Inside __first__')
    def __init__(self):
        print('Inside __init__')
a = Foo()
b = Foo()

It would return:

Inside __first__
Inside __init__
Inside __init__

In order to try and create this particular syntax I decided to create a meta class so that you could simply add this syntax to a class of your choice. This was my final code for the meta class and it was the first time I have tried meta class syntax so I was interested in what you thought about my code:

class First(type):
    _first = True
    def __call__(cls, *args, **kwargs):
        if cls._first:
            cls._first = False
            cls._oldinit = cls.__init__
            def init(*args, **kwargs):
                cls.__first__()
                cls._oldinit(*args, **kwargs)
            cls.__init__ = init
            cls.__init__.__doc__ = cls._oldinit.__doc__
        else:
            cls.__init__ = cls._oldinit
        return super(First, cls).__call__(*args, **kwargs)
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Would be nice to see this in context rather than an abstract idea - why do you want to do this? Practice with metaclasses, a specific application, etc. ? Should first be a class method? Perhaps that's not appropriate but context would be useful here. \$\endgroup\$ Commented Feb 15, 2019 at 15:17
  • \$\begingroup\$ @Greedo It is basically just practice of metaclasses but I also thought that this idea could potentially be a useful special method. From the tests I have done I have not specified that __first__ is a class method but I suppose it could be \$\endgroup\$ Commented Feb 15, 2019 at 15:30
  • \$\begingroup\$ Have you looked at subclasses? If class D extends B, will B._first interfere with D? \$\endgroup\$ Commented Feb 15, 2019 at 21:07
  • \$\begingroup\$ @AustinHastings Thanks for the suggestion for a way to break it. From what I have seen in the testing I did just now everything works fine with subclasses in that if B has a __first__ it will be run on the first time of D being run if either B or D has First set as its metaclass and then everything else will be normal \$\endgroup\$ Commented Feb 15, 2019 at 21:12

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.