I'm in the midst of writing a Python Library API and I often run into the scenario where my users want multiple different names for the same functions and variables.
If I have a Python class with the function foo()
and I want to make an alias to it called bar()
, that's super easy:
class Dummy(object):
def __init__(self):
pass
def foo(self):
pass
bar = foo
Now I can do this with no problem:
d = Dummy()
d.foo()
d.bar()
What I'm wondering is what is the best way to do this with a class attribute that is a regular variable (e.g. a string) rather than a function? If I had this piece of code:
d = Dummy()
print d.x
print d.xValue
I want d.x
and d.xValue
to ALWAYS print the same thing. If d.x
changes, it should change d.xValue
also (and vice-versa).
I can think of a number of ways to do this, but none of them seem as smooth as I'd like:
- Write a custom annotation
- Use the
@property
annotation and mess with the setter - Override the
__setattr__
class functions
Which of these ways is best? Or is there another way? I can't help but feel that if it's so easy to make aliases for functions, it should be just as easy for arbitrary variables...
FYI: I'm using Python 2.7.x, not Python 3.0, so I need a Python 2.7.x compatible solution (though I would be interested if Python 3.0 does something to directly address this need).
Thanks!