1

consider this

# global variable
i_am_global = {}

def get_global():
    global i_am_global # declare 1
    if i_am_global is not None:
        return i_am_global
    global i_am_global # declare 2
    i_am_global = do_something()
    return i_am_global
def main():
    get_global()
if __name__ == "__main__":
    main()

in this scenario where do we need to put global ? at # declare 1 or at # declare 2? and why?

This is because I heard(so I am asking this question) that global causes memory overhead. Please correct my understanding

Thank you

daydreamer
  • 87,243
  • 191
  • 450
  • 722
  • 2
    "*global causes memory overhead*" - you heard incorrectly. The `global` statement in Python does not cause memory overhead. – Greg Hewgill Feb 28 '12 at 18:16
  • When you tried both places, what did you observe? When you tried it without the `global` statement, what did you observe? – S.Lott Feb 28 '12 at 18:18
  • It's needed at #2 but not at #1. Take a look at this question: http://stackoverflow.com/questions/9366212/correct-use-of-global-variables-in-python-3 – Dan Gerhardsson Feb 28 '12 at 18:18
  • That was the link I needed. thank you @DanGerhardsson – daydreamer Feb 28 '12 at 18:23

2 Answers2

1

If you only ever read the variable, then you don't have to use global, but personally I do for documentary reasons. I also use a naming convention for globals. I don't believe there is a memory overhead for the global keyword, but globals in themeselves are generally considered to be undesirable.

cdarke
  • 42,728
  • 8
  • 80
  • 84
0

All top level functions and classes are global variables too. So there is no problem with declare any objects global.

But you should understand that any variable, which name not preceeded by underscore serves as public interface of that module and items to import. Consider this code

#module mutual_imports.py
global_object = 2

def changeGlobalObject():
    global global_object
    global_object = "two"

lets check this module:

>>> from mutual_imports import global_object, changeGlobalObject
>>> global_object
2
>>> changeGlobalObject()
>>> global_object
2
>>> from mutual_imports import global_object
>>> global_object
'two'

So what do you think about item that can be different if you are impoprting it different times.

All mutable things are good to be mutable states of some objects, just because it's easier and clearer way to handle it.

Odomontois
  • 15,918
  • 2
  • 36
  • 71