Nerotix
Nerotix

Reputation: 375

Defining global inside a function

Is it possible to define a global variable inside a function? like this:

def posities():
    global blauw
    blauw = {"bl1":[0], "bl2":[0],"bl3":[0],"bl4":[0]}
    global geel
    geel = {"ge1":[0], "ge2":[0],"ge3":[0],"ge4":[0]}
    global groen
    groen = {"gr1":[0], "gr2":[0],"gr3":[0],"gr4":[0]}
    global rood
    rood = {"ro1":[0], "ro2":[0],"ro3":[0],"ro4":[0]}
    global ingenomenPos
    ingenomenPos = []

Or MUST I first declare to the variables outside of the function? Because when I define them inside the function and I try to acces them from another function, it doesn't recognise it. So I want to declare global variables without first declaring them outside the function.

So I try to acces those globals with this method:

def bezet():
    print (str(ingenomenPos))

which results in the error:

NameError: name 'ingenomenPos' is not defined

Upvotes: 2

Views: 80

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121196

Use global statements only in functions, nowhere else (it has no effect elsewhere). Yes, it'll work, no you don't need to create the global outside first.

This is easily tested in the interpreter:

>>> foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> def bar():
...     global foo
...     foo = 'baz'
...
>>> bar()
>>> foo
'baz'

The global statement tells the Python compiler that assigning to the name should set a global, not a local variable. Without the statement, all use of a variable in a function becomes local as soon as it is used to bind to.

Note that you have to call the function; just the global statement being present in the function is not enough to bind the name. Python doesn't have 'declarations', names only exist through binding actions. See Naming and binding.

If you still see the exception, then the assignment never was executed. Either you haven't called the function, or the name = value statement was never reached (because the function returned before that line or an exception was raised).

Upvotes: 5

Related Questions