Not sure if this is possible in Python, but I'd like to have an instance of a class as a module-level global variable that, when called, returns a default property.
The idea comes from this question that overrides __call__
to have a class mimic a function.
Quick (untested) example of the idea:
class _foo(object):
__slots__ = ("_foo",)
_init = False
def __init__(self):
if not _init:
self._foo = ["bar", "baz", "zog"]
def __call__(self, item=None):
if itme is not None:
return self._foo[item]
else:
return self._foo
def __getitem__(self, item):
return self._foo[item]
# Module level
FOO = _foo()
Assume the above code is in a module (foo.py). Using the interpreter, I cal get the callable form to work how I want, but not the non-callable form.
>>> import foo
# callable forms
>>> foo.FOO(0)
"bar"
>>> foo.FOO()
["bar", "baz", "zog"]
# attribute forms
>>> foo.FOO[2]
"zog"
# doesn't work
>>> foo.FOO
<foo._foo object at 0xdeadbeef>
# desired output
>>> foo.FOO
["bar", "baz", "zog"]
My thinking is that I need to define a default property somehow so that when calling the instance directly, I get the internal list/dict of my choosing. I could cheat and do this via overriding repr, but that kinda breaks Python's own API and I want to avoid that. Passing no value in square brackets (>>> foo.FOO[]
) yields a syntax error instead.
I'd like any potential solutions to be compatible with Python 2.4 at minimum and 2.7 at maximum. If this isn't possible, then I guess I'll just stick to using the callable format.