sgfw sgfw - 4 months ago 6
Python Question

In Python, can I use the value of a global variable in a method at the time of it's definition, but not change when that variable is changed?

It's difficult to describe the behavior that I need, so I'll give an example. When running the following code,

f()
prints
"eggs"
, but I would like a way to make
f()
print
"spam"
, which is the value of
x
at the time of
f
's declaration.

x = "spam"
def f():
print(x)
x = "eggs"
f()


This doesn't seem very pythonic, but I've given a lot of thought to the problem I'm facing, and have concluded that this solution is the most elegant. I can give more details about the exact example that requires this solution if that's necessary.

Answer

Then bind x to f as soon as f is defined:

x = "spam"
def f(x=x):
    print(x)

x = "eggs"
f()
# spam

Probably not a good idea though.