0

Why objects denoted by "k" and "p" are not globals?

my_global = 5


def func1(n=5):

    global my_global, k, p
    k = 10
    p = 15
    return my_global + n + k + p


all_gobals = globals()

print(k in all_gobals)

print(func1())

Output:

print(k in all_gobals )
NameError: name 'k' is not defined

globals() gives me:

{'__name__': '__main__', '__doc__': None, '__package__': None,    '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f1649b48c88>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/pawel/PycharmProjects/test/exerc.py', '__cached__': None, 'random': <module 'random' from '/usr/lib/python3.6/random.py'>, 'itertools': <module 'itertools' (built-in)>, 'string': <module 'string' from '/usr/lib/python3.6/string.py'>, 'a': 20, 'is_perfect_number': <function is_perfect_number at 0x7f1649b7ae18>, 'is_palindrome': <function is_palindrome at 0x7f16497e31e0>, 'ask_for_help': <function ask_for_help at 0x7f16486a5bf8>, 'method': <function method at   0x7f16486a5c80>, 'my_global': 5, 'func1': <function func1 at 0x7f16486a5d08>,     'all_gobals': {...}}

Why executing print(k) gives?:

NameError: name 'k' is not defined

The object 'k' was defined as global, why I cannot use it outisde of the function? I saw the following topic and it should wokrs: Use of "global" keyword in Python

1 Answers1

1

k isn't defined until the function is called. What would the value of k be before the call to func1?

Move the call to func1 above your attempt to use k so it's defined before you try to use it.

This is a great example of why (ab)using globals isn't a good idea. It would be much better to return the value from func1 directly, then use it at the call site. That way it's clear where the data is coming from, and you don't accidentally use data before its defined.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • Thanks, now it makes sense. I use 'global' in many ways becasue I'm learning the concept and I want to understand how it works. –  May 05 '18 at 12:38
  • @kviatek While that's good, I'd *strongly* recommend, once you starting writing real code, to never touch it until you're out of other options. It's entirely possible to write all code without ever using `global`, and most of the time code that doesn't use global will be easier to understand and maintain. – Carcigenicate May 05 '18 at 12:39
  • I'll take your advise. Thanks once more. –  May 05 '18 at 12:40