1

I know that the order of functions in a script doesn't matter. However, this sample code doesn't work:

main.py

_FUNCTIONS = (_foo, _bar) def myfunc(): for f in _FUNCTIONS: print(f()) def _foo(): return False def _bar(): return True myfunc() 

provides the following error

File "main.py", line 1, in <module> _FUNCTIONS = (_foo, _bar) NameError: name '_foo' is not defined 

However, if I don't use _FUNCTIONS and inject (_foo, _bar) into a code this will work:

def myfunc(): for f in (_foo, _bar): print(f()) def _foo(): return False def _bar(): return True myfunc() 

Why the first example doesn't work?

How can I extract the list of functions in a variable and put it on the top of the script?

3
  • 6
    "I know that the order of functions in a script doesn't matter."—Yeah it does. You can't store a reference to something before it is defined. Commented Jun 7, 2021 at 15:12
  • in the second code snipped, the function is executed after the variables are defined. Try running myfunc() directly after the definition of myfunc and it will fail like the first code snippet. Commented Jun 7, 2021 at 15:14
  • 1
    Think about the order of execution, not the order of the statements themselves. Python will make an initial pass through your file, executing each statement at the top level. The def statements will define a function, but not execute it. By the time you get to the myfunc() call, all the functions are defined. In your first example, you're using _foo and _bar before their defs have been seen. Commented Jun 7, 2021 at 15:19

1 Answer 1

2

You actually misunderstood it, When you are using _FUNCTIONS = (_foo, _bar) , python expects _foo and _bar as a variable nothing fancy here, and since you haven't defined any reference to it yet, it's undefined, thus throws error.

In the second case, you're doing the same thing inside a function, by that time, the function is already available in python's scope, thus no error.

And as @khelwood has mentioned in the comment, the order does matter

Sign up to request clarification or add additional context in comments.

1 Comment

You are right. I misunderstood that a constant is evaluated at the time of it's definition, not at the time when we actual use it (like in case of functions).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.