Mark Ginsburg
Mark Ginsburg

Reputation: 2269

How to declare a global variable in a module

In the main program I have

import medallia_utils
from collections import defaultdict
Opers   = defaultdict(int)

Later on in this program, I will be calling a function in medallia_utils called word_checker.

I want to manipulate the dictionary variable Opers in a function word_checker defined inside medallia_utils so I want to declare it as Global.

When I do this inside of medallia_utils:

def word_checker(name, comment):
    import re 
    from collections import defaultdict
    global Opers

The system says

NameError: global name 'Opers' is not defined

I also tried to define this variable globally in medallia_utils outside of the function word_checker by doing

global Opers

or

global __Opers__

but nothing working so far. I get the same error.

What is the syntax fix to get this to work?

Upvotes: 0

Views: 136

Answers (2)

Jayden
Jayden

Reputation: 107

you need to make the variable hold something after you declare it as global eg.

global name 
name = 'bob'

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600059

There is no "syntax fix" that can make this work. If you want to use a variable defined in another module, you need to import it.

Upvotes: 2

Related Questions