12

How does IPython handle local variables? I have this function that works in the Python shell but will not work in the IPython shell.

def change(key,value):
    global aname
    global alist
    alist.append(key)
    aname.extend(value)

I am using this inside a for loop and which is reading input in from a JSON and other .txt files and adding the keys and value to a list which is then used by another function to save to the database. If I do not do it this way it will be ugly and will use the indexes in my loop.

[change(key,value) for key,value in jsondata.itervalues()]

def storeindatabase():
    do_sothing to the list aname and store
    do_sothing to the alist and store
4
  • I am using this inside of a for loop and which is reading inputting in from a json and other txt files and adding the keys and value to a list which is then used by another function to save to the database. if am not doing it this way it will be ugly and ill the using indexes in my loop Commented Jun 4, 2013 at 18:38
  • 1
    Doesn't matter. If you're not using = to assign to the name in your function, global does nothing whatsoever. Commented Jun 4, 2013 at 18:47
  • The global statements are not required in the change function. aname and alist are not defined in change, so Python will automatically look for the variables outside the function. This will also work in IPython too, so if you found it didn't, then aname and alist were likely not defined anywhere - recalculate the cell that defined them, then try to call change again. Commented Nov 1, 2018 at 22:50
  • I think def storeindatabase() is not needed to illustrate. Can you please remove that if so? Commented Apr 21, 2019 at 16:35

2 Answers 2

6

Append and extend won't work unless the lists already exist the first time they're called. Declaring them upfront makes it work in notebook as well.

aname=[]
alist=[]
def change(key,value):
    global aname
    global alist
    alist.append(key)
    aname.extend(value)

change(3,[3])
print(alist)
[3]
print(aname)
[4]
Sign up to request clarification or add additional context in comments.

Comments

4

Beforeword: in the last couple of months this answer has been downvoted considerably. I apology if my words might seem a bit rough, but I insist globals are really harmful, as explained in the documentation linked below. If you consider downvoting further down this answer, please read the documentation and elaborate why you disagree with what's below. To quote an answer linked below: "The reason they are bad is that they allow functions to have hidden (non-obvious, surprising, hard-to-detect) side effects, leading to an increase in complexity, potentially leading to Spaghetti code."

  1. Using globals is very likely to mean wrong engineering. If you need a global, that means you need to redesign your code. That's even more true in python.
  2. when you do really want to use a global (maybe the only acceptable case: singleton, though in python, you'd only scope the singleton more globally than where you use it...), you need to declare your variable as global, and then attribute it a value.

For example:

global bar
bar = []
def foobar():
    bar.append('X')

RTFM:


about the IPython part, my example does work:

In [1]: global bar

In [2]: bar = []

In [3]: def foo():
   ...:     bar.append(3)
   ...:     

In [4]: foo()

In [5]: foo()

In [6]: foo()

In [7]: bar
Out[7]: [3, 3, 3]

and here is another example, that shows global is indeed working, and not the outer scoping:

In [2]: def foo():
   ...:     global bar
   ...:     bar = []
   ...:     

In [3]: def oof():
   ...:     bar.append('x')
   ...:     

In [4]: foo()

In [5]: oof()

In [6]: oof()

In [7]: oof()

In [8]: oof()

In [9]: bar
Out[9]: ['x', 'x', 'x', 'x']

anyway, globals are evil!

27 Comments

can u try ur own example in ipthon it will not work that is what i want to know and why thanks
iPython notebooks are often used for tinkering with new problems. There's nothing wrong with using global variables in this case. This isn't about writing polished code, but rather about why the specific case given by @user1940979 doesn't work.
I see nothing wrong with using global. I think you're being elitist. I do it all the time in my PHP code and a friend called Adrian told me it was fine.
I strongly disagree with your claim that its "almost never useful" This is specifically using globals in within an IPython shell. Its entirely reasonable, and extremely useful to use globals when doing exploration and rapid prototyping. I found your post wholly unhelpful (it doesnt even work) and pretty presumptuous.
@zmo, nobody is doing real programming in IPython. IPython is for research and prototyping.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.