Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use global variables in IPython

Tags:

python

ipython

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
like image 393
user1940979 Avatar asked Jun 04 '13 18:06

user1940979


People also ask

Can Python use global variables?

Global variables can be used by everyone, both inside of functions and outside.

How do you pass a global variable to a function in Python?

Use of “global†keyword to modify global variable inside a function. If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.

How do you declare a global variable?

You can declare global—that is, nonlocal—variables by declaring them outside of any function definition. It's usually best to put all global declarations near the beginning of the program, before the first function. A variable is recognized only from the point it is declared, to the end of the file.

What does globals () do in Python?

Python – globals() function globals() function in Python returns the dictionary of current global symbol table. Symbol table: Symbol table is a data structure which contains all necessary information about the program. These include variable names, methods, classes, etc.


2 Answers

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:

  • http://docs.python.org/release/2.4/ref/global.html
  • Do you use the "global" statement in Python?
  • https://stackoverflow.com/a/19158418/1290438
  • https://docs.quantifiedcode.com/python-anti-patterns/maintainability/using_the_global_statement.html
  • http://wiki.c2.com/?GlobalVariablesAreBad

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!

like image 183
zmo Avatar answered Oct 12 '22 23:10

zmo


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]
like image 45
behold Avatar answered Oct 13 '22 01:10

behold