In Python variable names point at values. x=y
tells Python that the variable name x
should point at the value that y
is currently pointing at.
When you change y
, then the variable name y
points at a new value, while the variable name x
still points at the old value.
You can not achieve what you want with plain variable names.
I like KennyTM's suggestion to define x
as a function since it makes explicit that the value of x
requires running some code (the lookup of the value of y).
However, if you want to maintain a uniform syntax (making all the constants accessible in the same way), then you could use a class with properties (attributes which call getter and setter functions):
Constants.py:
class BunchOConstants(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
@property
def x(self):
return self.y
@x.setter
def x(self,val):
self.y=val
const=BunchOConstants(y=10,z='foo')
Your script.py:
import Constants
const=Constants.const
print(const.y)
# 10
print(const.x)
# 10
Here you change the "constant" y:
const.y='bar'
And the "constant" x is changed too:
print(const.x)
# bar
You can change x
also,
const.x='foo'
and y
too gets changed:
print(const.y)
# foo