Dynamic Scoping problem

  • Thread starter Daniel Lemos Itaborai
  • Start date
D

Daniel Lemos Itaborai

I would like to first apologize my question, I just picked up Python
for a spin 4 days ago(loving it so far). I am having some trouble with
this...

# myproblem.py

x = 'wrong'

def bluft(x) : x()

def foo():
x = 'right'
def bar():
global x
print x
bluft(bar)

# end myproblem.py


Is there a way to enforce scope resolution?


Thanks for the patience,
Daniel Lemos Itaborai
 
A

Andrew Koenig

I would like to first apologize my question, I just picked up Python
for a spin 4 days ago(loving it so far). I am having some trouble with
this...

# myproblem.py

x = 'wrong'

def bluft(x) : x()

def foo():
x = 'right'
def bar():
global x
print x
bluft(bar)

# end myproblem.py


Is there a way to enforce scope resolution?

When you write

def foo():
x = 'right'
...

you are defining a new variable, local to foo, named x. When you say
"global x" inside bar, you are saying that you do not want that variable;
you want the global one instead.

If you want to assign 'right' to the global x, do it this way:

def foo():
global x
x = 'right'
def bar():
print x
bluft(bar)

That said, I should point out that global variables are usually a bad idea.
 
V

Ville Vainio

Andrew> That said, I should point out that global variables are
Andrew> usually a bad idea.

But also let me point out that they are not as bad an idea as they are
in e.g. C, because they are only *module* global, and are a handy way
of implementing singletons.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top