Python decorator for class - python

I try do this:
import unittest
def decorator(cls):
class Decorator(cls):
def __init__(self, *args, **kwargs):
super(Decorator, self).__init__(*args, **kwargs)
return Decorator
#decorator
class myClass(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(myClass, self).__init__(*args, **kwargs)
self.test = 'test'
def test_test(self):
pass
myClass().run()
But I get recursion in MyClass.__init__. Are there any ways to avoid this?

You cannot use super(myClass, self) within a decorated class in this way.
myClass is looked up as a global, and the global myClass is rebound to Decorator, so you are telling Python to look in the class MRO for __init__ starting from Decorator which is myClass, which calls super(myClass, self).__init__(), looking up myClass as a global, which is bound to Decorator, etc.
The easiest work-around is to not use super() here:
#decorator
class myClass(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
self.test = 'test'
This is one of the reasons why in Python 3 the argument-less version of super() was introduced, giving methods a __class__ cell instead.
You could jump through some (very tricky) hoops to re-compile the myClass.__init__() method to give it a myClass closure bound to the original undecorated class object instead, but for a unittest, I would not bother.

Related

How to use super() in this complex multiple inheritance situation?

I'm writing a library that provides subclasses of each of two existing base classes with extra functionality.
Rather than explain the arrangement in words, here's a diagram:
And minimal code:
class Base0:
pass
class Base1(Base0):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.foo = something()
class Base2(Base0):
pass
class Mixin:
def __init__(self, bar):
self.bar = bar
# More code
class Child1(Base1, Mixin):
def __init__(self, *args, **kwargs):
Base1.__init__(self, *args, **kwargs)
Mixin.__init__(self, some_function_of(self.foo))
class Child2(Base2, Mixin):
def __init__(self, *args, **kwargs):
Base2.__init__(self, *args, **kwargs)
Mixin.__init__(self, something_else())
The Base classes are outside my control. I wrote the Mixin and Child classes. Users of my library will subclass the Child classes, so it's very important that the inheritance be sane and correct.
What I'd like to do is use super().__init__ in the Child classes rather than explicitly invoking the Base and Mixin initializers. The reason this is nontrivial is that in Child1, the value passed to the Mixin initializer can't be determined until after the Base1 initializer has run.
What is the simplest/sanest way to set this up?

python: error when running __new__? not invoking __init__

I was reading Python documentation regarding inheritance and use of __new__ and __init__
https://docs.python.org/3/reference/datamodel.html#basic-customization
I am trying to create a class 'config' which will be a generic class with all basic methods common to all my projects
from abc import ABCMeta, abstractmethod
class MyConfig(metaclass=ABCMeta):
def __new__(cls, *args, **kwargs):
print("Config new")
return cls
def __init__(self):
print("Config init")
Then, when I create a new project I'll import that generic config class and create an specific configuration class for that project
# from config import MyConfig
class MyConfiguration(MyConfig):
def __init__(self, *args, **kwargs):
super(MyConfiguration, self).__init__(*args, **kwargs)
print("Configuration init")
When I instantiate my configuration I would spec to both __new__ and __init__ methods to run, but only runs __new__
c = MyConfiguration()
This is the output:
Config new
Documentation says:
If __new__() is invoked during object construction and it returns an instance or subclass of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to the object constructor.
If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.
As only output comes from __new__ method, that means that I am doing something wrong because the __init__ method is not being invoked.
any help would be welcome.
__init__() will only be invoked if your __new__() returns something that it can be validly invoked on - namely, an instance of the class.
In your example, you're returning the class itself.
This is one way you can do it:
To create an instance of your class, and return it instead of returning the class itself:
from abc import ABCMeta, abstractmethod
class MyConfig(metaclass=ABCMeta):
def __new__(cls, *args, **kwargs):
instance = super(MyConfig, cls).__new__(cls, *args, **kwargs)
print("Config new")
return instance
def __init__(self, *args, **kwargs):
print("Config init")
class MyConfiguration(MyConfig):
def __init__(self, *args, **kwargs):
super(MyConfiguration, self).__init__(*args, **kwargs)
print("Configuration init")
if __name__ == '__main__':
c = MyConfiguration()
Output:
Config new
Config init
Configuration init

Injecting function call after __init__ with decorator

I'm trying to find the best way to create a class decorator that does the following:
Injects a few functions into the decorated class
Forces a call to one of these functions AFTER the decorated class' __init__ is called
Currently, I'm just saving off a reference to the 'original' __init__ method and replacing it with my __init__ that calls the original and my additional function. It looks similar to this:
orig_init = cls.__init__
def new_init(self, *args, **kwargs):
"""
'Extend' wrapped class' __init__ so we can attach to all signals
automatically
"""
orig_init(self, *args, **kwargs)
self._debugSignals()
cls.__init__ = new_init
Is there a better way to 'augment' the original __init__ or inject my call somewhere else? All I really need is for my self._debugSignals() to be called sometime after the object is created. I also want it happen automatically, which is why I thought after __init__ was a good place.
Extra misc. decorator notes
It might be worth mentioning some background on this decorator. You can find the full code here. The point of the decorator is to automatically attach to any PyQt signals and print when they are emitted. The decorator works fine when I decorate my own subclasses of QtCore.QObject, however I've been recently trying to automatically decorate all QObject children.
I'd like to have a 'debug' mode in the application where I can automatically print ALL signals just to make sure things are doing what I expect. I'm sure this will result in TONS of debug, but I'd still like to see what's happening.
The problem is my current version of the decorator is causing a segfault when replacing QtCore.QObject.__init__. I've tried to debug this, but the code is all SIP generated, which I don't have much experience with.
So, I was wondering if there was a safer, more pythonic way to inject a function call AFTER the __init__ and hopefully avoid the segfault.
Based on this post and this answer, an alternative way to do this is through a custom metaclass. This would work as follows (tested in Python 2.7):
# define a new metaclass which overrides the "__call__" function
class NewInitCaller(type):
def __call__(cls, *args, **kwargs):
"""Called when you call MyNewClass() """
obj = type.__call__(cls, *args, **kwargs)
obj.new_init()
return obj
# then create a new class with the __metaclass__ set as our custom metaclass
class MyNewClass(object):
__metaclass__ = NewInitCaller
def __init__(self):
print "Init class"
def new_init(self):
print "New init!!"
# when you create an instance
a = MyNewClass()
>>> Init class
>>> New init!!
The basic idea is that:
when you call MyNewClass() it searches for the metaclass, finds that you have defined NewInitCaller
The metaclass __call__ function is called.
This function creates the MyNewClass instance using type,
The instance runs its own __init__ (printing "Init class").
The meta class then calls the new_init function of the instance.
Here is the solution for Python 3.x, based on this post's accepted answer. Also see PEP 3115 for reference, I think the rationale is an interesting read.
Changes in the example above are shown with comments; the only real change is the way the metaclass is defined, all other are trivial 2to3 modifications.
# define a new metaclass which overrides the "__call__" function
class NewInitCaller(type):
def __call__(cls, *args, **kwargs):
"""Called when you call MyNewClass() """
obj = type.__call__(cls, *args, **kwargs)
obj.new_init()
return obj
# then create a new class with the metaclass passed as an argument
class MyNewClass(object, metaclass=NewInitCaller): # added argument
# __metaclass__ = NewInitCaller this line is removed; would not have effect
def __init__(self):
print("Init class") # function, not command
def new_init(self):
print("New init!!") # function, not command
# when you create an instance
a = MyNewClass()
>>> Init class
>>> New init!!
Here's a generalized form of jake77's example which implements __post_init__ on a non-dataclass. This enables a subclass's configure() to be automatically invoked in correct sequence after the base & subclass __init__s have completed.
# define a new metaclass which overrides the "__call__" function
class PostInitCaller(type):
def __call__(cls, *args, **kwargs):
"""Called when you call BaseClass() """
print(f"{__class__.__name__}.__call__({args}, {kwargs})")
obj = type.__call__(cls, *args, **kwargs)
obj.__post_init__(*args, **kwargs)
return obj
# then create a new class with the metaclass passed as an argument
class BaseClass(object, metaclass=PostInitCaller):
def __init__(self, *args, **kwargs):
print(f"{__class__.__name__}.__init__({args}, {kwargs})")
super().__init__()
def __post_init__(self, *args, **kwargs):
print(f"{__class__.__name__}.__post_init__({args}, {kwargs})")
self.configure(*args, **kwargs)
def configure(self, *args, **kwargs):
print(f"{__class__.__name__}.configure({args}, {kwargs})")
class SubClass(BaseClass):
def __init__(self, *args, **kwargs):
print(f"{__class__.__name__}.__init__({args}, {kwargs})")
super().__init__(*args, **kwargs)
def configure(self, *args, **kwargs):
print(f"{__class__.__name__}.configure({args}, {kwargs})")
super().configure(*args, **kwargs)
# when you create an instance
a = SubClass('a', b='b')
running gives:
PostInitCaller.__call__(('a',), {'b': 'b'})
SubClass.__init__(('a',), {'b': 'b'})
BaseClass.__init__(('a',), {'b': 'b'})
BaseClass.__post_init__(('a',), {'b': 'b'})
SubClass.configure(('a',), {'b': 'b'})
BaseClass.configure(('a',), {'b': 'b'})
I know that the metaclass approach is the Pro way, but I've a more readable and easy proposal using #staticmethod:
class Invites(TimestampModel, db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
invitee_email = db.Column(db.String(128), nullable=False)
def __init__(self, invitee_email):
invitee_email = invitee_email
#staticmethod
def create_invitation(invitee_email):
"""
Create an invitation
saves it and fetches it because the id
is being generated in the DB
"""
invitation = Invites(invitee_email)
db.session.save(invitation)
db.session.commit()
return Invites.query.filter(
PartnerInvites.invitee_email == invitee_email
).one_or_none()
So I could use it this way:
invitation = Invites.create_invitation("jim#mail.com")
print(invitation.id, invitation.invitee_email)
>>>> 1 jim#mail.com

Pass keyword argument only to __new__() and never further it to __init__()?

Part 1
I have a setup where I have a set of classes that I want to mock, my idea was that in the cases where I want to do this I pass a mock keyword argument into the constructor and in __new__ intercept this and instead pass back a mocked version of that object.
It looks like this (Edited the keyword lookup after #mgilsons suggestion):
class RealObject(object):
def __new__(cls, *args, **kwargs):
if kwargs.pop('mock', None):
return MockRealObject()
return super(RealObect, cls).__new__(cls, *args, **kwargs)
def __init__(self, whatever = None):
'''
Constructor
'''
#stuff happens
I then call the constructor like this:
ro = RealObject(mock = bool)
The issue I have here is that I get the following error when bool is False:
TypeError: __init__() got an unexpected keyword argument 'mock'
This works if I add mock as a keyword argument to __init__ but what I am asking if this is possible to avoid. I even pop the mock from the kwargs dict.
This is also a question about the design. Is there a better way to do this? (of course!) I wanted to try doing it this way, without using a factory or a superclass or anything. But still, should I use another keyword maybe? __call__?
Part 2 based on jsbueno's answer
So I wanted to extract the metaclass and the __new__ function into a separate module. I did this:
class Mockable(object):
def __new__(cls, *args, **kwargs):
if kwargs.pop('mock', None):
mock_cls = eval('{0}{1}'.format('Mock',cls.__name__))
return super(mock_cls, mock_cls).__new__(mock_cls)
return super(cls, cls).__new__(cls,*args, **kwargs)
class MockableMetaclass(type):
def __call__(self, *args, **kwargs):
obj = self.__new__(self, *args, **kwargs)
if "mock" in kwargs:
del kwargs["mock"]
obj.__init__(*args, **kwargs)
return obj
And I have defined in a separate module the classes RealObject and MockRealObject.
I have two problems now:
If MockableMetaclass and Mockable are not in the same module as the RealObject class the eval will raise a NameError if I provide mock = True.
If mock = False the code will enter into an endless recursion that ends in an impressive RuntimeError: maximum recursion depth exceeded while calling a Python objec. I'm guessing this is due to RealObject's superclass no longer being object but instead Mockable.
How can I fix these problems? is my approach incorrect? Should I instead have Mockable as a decorator? I tried that but that didn't seem to work since __new__ of an instance is only read-only it seems.
This is a job for the metaclass! :-)
The code responsible to call both __new__ and __init__ when instantiating a Python new-style object lies in the __call__method for the class metaclass. (or the semantically equivalent to that).
In other words - when you do:
RealObject() - what is really called is the RealObject.__class__.__call__ method.
Since without declaring a explicit metaclass, the metaclass is type, it is type.__call__ which is called.
Most recipes around dealing with metaclasses deal with subclassing the __new__ method - automating actions when the class is created. But overriding __call__ we can take actions when the class is instantiated, instead.
In this case, all that is needed is to remove the "mock" keyword parameter, if any, before calling __init__:
class MetaMock(type):
def __call__(cls, *args, **kw):
obj = cls.__new__(cls, *args, **kw)
if "mock" in kw:
del kw["mock"]
obj.__init__(*args, **kw)
return obj
class RealObject(metaclass=MetaMock):
...
A subclass is pretty much essential, since __new__ always passes the arguments to the constructor call to the __init__ method. If you add a subclass via a class decorator as a mixin then you can intercept the mock argument in the subclass __init__:
def mock_with(mock_cls):
class MockMixin(object):
def __new__(cls, *args, **kwargs):
if kwargs.pop('mock'):
return mock_cls()
return super(MockMixin, cls).__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
kwargs.pop('mock')
super(MockMixin, self).__init__(*args, **kwargs)
def decorator(real_cls):
return type(real_cls.__name__, (MockMixin, real_cls), {})
return decorator
class MockRealObject(object):
pass
#mock_with(MockRealObject)
class RealObject(object):
def __init__(self, whatever=None):
pass
r = RealObject(mock=False)
assert isinstance(r, RealObject)
m = RealObject(mock=True)
assert isinstance(m, MockRealObject)
The alternative is for the subclass __new__ method to return RealObject(cls, *args, **kwargs); in that case, since the returned object isn't an instance of the subclass. However in that case the isinstance check will fail.

Python class decorator and maximum recursion depth exceeded

I try define class decorator. I have problem with __init__ method in decorated class. If __init__ method invokes super the RuntimeError maximum recursion depth exceeded is raised.
Code example:
def decorate(cls):
class NewClass(cls): pass
return NewClass
#decorate
class Foo(object):
def __init__(self, *args, **kwargs):
super(Foo, self).__init__(*args, **kwargs)
What am I doing wrong?
Thanks, Michał
Edit 1
Thanks to Mike Boers answer I realized that correct question is what should I do to achive that super(Foo, self) point to proper class.
I have also two limitation. I want invoke Foo.__init__ method and I can't change Foo class definition.
Edit 2
I have solved this problem. I modify decorator function body. I don't return new class. Instead of I wrap methods of orginal class.
You need to override NewClass.__init__ to prevent recursion, because NewClass.__init__ is Foo.__init__ and it keeps calling itself.
def decorate(cls):
class NewClass(cls):
def __init__(self):
pass
return NewClass
New idea:
How about not subclassing it? Maybe monkey patching is your friend?
def decorate(cls):
old_do_something = cls.do_something
def new_do_something(self):
print "decorated",
old_do_something(self)
cls.do_something = new_do_something
return cls
#decorate
class Foo(object):
def __init__(self, *args, **kwargs):
super(Foo, self).__init__(*args, **kwargs)
def do_something(self):
print "Foo"
f = Foo()
f.do_something()
Remember that a decorator is simply syntactic sugar for:
>>> Foo = decorate(Foo)
So in this case the name Foo actually refers to the NewClass class. Within the Foo.__init__ method you are in fact asking for the super __init__ of NewClass, which is Foo.__init__ (which is what is currently running).
Thus, your Foo.__init__ keeps receiving its own __init__ to call, and you end up in an infinite recursion.

Categories

Resources