Karthik Bhat
Karthik Bhat

Reputation: 391

Any type of scope resolution operator in Python?

Is there any way to make the python interpreter choose the global variable specifically when there is also a local variable with the same name? (Like C++ has :: operator)

x=50

def fun():
    x=20
    print("The value of local x is",x)

    global x
    #How can I display the value of global x here?
    print("The value of global x is",x)

print("The value of global x is",x)
fun()

The second print statement inside the function block should display the value of global x.

File "/home/karthik/PycharmProjects/helloworld/scope.py", line 7

global x
^

SyntaxError: name 'x' is used prior to global declaration

Process finished with exit code 1

Upvotes: 3

Views: 2605

Answers (2)

Naeio
Naeio

Reputation: 1191

I don't know any way to do this (and I am not an expert). The two solutions that I can think of are to give another name to your local x (like xLoc), or to put your global x in argument, like this :

x=50

def fun(xGlob):
    x=20
    print("The value of local x is",x)

    print("The value of global x is",xGlob)

print("The value of global x is",x)
fun(x)

Is this answering your question ?

Upvotes: 0

Norrius
Norrius

Reputation: 7930

Python does not have a direct equivalent to the :: operator (typically that kind of thing is handled by the dot .). To access a variable from an outer scope, assign it to a different name as to not shadow it:

x = 50

def fun():
    x = 20
    print(x)  # 20

    print(x_)  # 50

print(x)  # 50
x_ = x
fun()

But of course Python would not be Python if there weren't a hack around this... What you describe is actually possible, but I do not recommend it:

x = 50

def fun():
    x = 20
    print(x)  # 20

    print(globals()['x'])  # 50

print(x)  # 50
fun()

Upvotes: 6

Related Questions