How to use context when overriding __new__ to return an initialized object

Viewed 30

I've implemented a factory class which returns an initialized class in the __new__ method

class MyFactory(object):
    def __new__(self, my_obj, *args, **kwargs):
        if my_obj == ...:
            return A(*args, **kwargs)
        else:
            return B(*args, **kwargs)

Both classes A and B extend a base class MyBase() which support context

class MyBase(object):
    def __enter__(self):
        ...

    def __exit__(self, exc_type, exc_val, exc_tb):
        ...

I'm trying to use this setup like this

with MyFactory(my_obj, ...) as something:
   something.do_something()

However an error is thrown obviously since python is expecting the __enter__, __exit__ pair to be present on the MyFactory class

What changes should I make to make the above usage possible?

EDIT:

I concede, this is actually the correct way to do it. My errors were due to not returning self in the __enter__ method :facepalm:

Heres the working code for those of you interested

1 Answers

Currently MyFactory only extends oject

class MyFactory(object):

I think your MyFactory object needs to extend MyBase using the following syntax:

class MyFactory(MyBase):
    ...

This should enable the superclass instantiation of the __exit__ and __enter__ methods without explicitly describing them again in the child classes.

It's a bit of a mashup, but since you're returning objects from the __new__ call then it's probably a fair one.

Related