59

How do I declare a global variable in a function in Python?

That is, so that it doesn't have to be declared before but can be used outside of the function.

6
  • 5
    Yes, it's possible. What have you tried, what didn't work? Commented Nov 29, 2012 at 14:23
  • 4
    global my_var, you're done. Commented Nov 29, 2012 at 14:24
  • 6
    Why is this closed? It is a real question! Commented Aug 17, 2018 at 23:10
  • 3
    I think this question should be re-opened because in its current form, it asks a specific Python-related question, and that question has a specific objective answer. Commented Oct 16, 2018 at 15:30
  • @AshwiniChaudhary getting pylint error about that Commented Sep 5, 2020 at 17:06

2 Answers 2

47

Yes, but why?

def a():
    globals()['something'] = 'bob'
Sign up to request clarification or add additional context in comments.

8 Comments

just do, global something, it will create a new global variable if it doesn't exist.
explicit rather than implicit... - this makes it more "obvious" as to it's a bad idea...
@F3AR3DLEGEND globals my_var does usable outside the function, i've tried that.
While correct, this isn't standard practice. in most cases its best to use global keyword.
it may not be standard practice but it saved me a codefactor headache
|
24
def function(arguments):
    global var_name
    var_name = value #must declare global prior to assigning value

This will work in any function, regardless of it is in the same program or not.

Here's another way to use it:

def function():
    num = #code assigning some value to num
    return num

NOTE: Using the return built-in will automatically stop the program (or the function), regardless of whether it is finished or not.

You can use this in a function like this:

if function()==5 #if num==5:
    #other code

This would allow you to use the variable outside of the function. Doesn't necessarily have to be declared global.

In addition, to use a variable from one function to another, you can do something like this:

import primes as p #my own example of a module I made
p.prevPrimes(10) #generates primes up to n
for i in p.primes_dict:
    if p.primes_dict[i]: #dictionary contains only boolean values
        print p.primes_dict[i]

This will allow you to use the variable in another function or program without having use a global variable or the return built-in.

2 Comments

it's not global is it? I think it's module-wide.
Ah yes, it is only module-wide. However, using the return function should fix that.

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.