Consider the following Python (runs in 2.x or 3.x):
class Outer(object):
pass
class Inner(object):
def __init__(self):
print("Inner.self", self)
o = Outer()
i = o.Inner()
I want to get my hands on o while inside Inner.__init__(). But:
- I don’t want
oto be an explicit parameter toInner. - I want
O.Innerando.Innerto be a class object, not something weird like a closure.
Can you suggest how I might achieve this?
Right now my best idea is to use thread local storage. In my use case, whenever I construct an o.Inner(), I’m already inside a method on o somewhere, and it wouldn’t be a big deal to add
threading.local()["my o object"] = o
to my code.
This gives you an idea of the level of depravity I’m willing to consider.
In Python 2.6, a class decorator that’s also a custom descriptor matches the specs you give:
This emits:
just to confirm that
as per your peculiar specs. Of course it needs to be a different class each time for reentrancy — even in a single-threaded world, the following:
should work cleanly, and stashing o1 vs o2 anywhere else than in the classes returned by
o1.Innervso2.Inner(e.g., in TLS) would mean horrible results for this use.But then you didn’t specify “
o.Innerhas to be exactly the same class object for every possibleothat’s an instance ofOuter“, so this code fully meets the specs you did give;-).