0

As title. I want to move code segment if __name__ == '__main__': before all functions that it will call.(I found this more readable, for myself) To achieve this I need to call functions that will be defined later. Is this possible?

While this has been answered in the comment section. To provide more context: I read one line of code:

cur_mod = sys.modules[__name__]

which let me came to this question. (i.e. I thought it would be possible to call something defined later by import itself)

8
  • 4
    No. Put your: if __name__ == '__main__': below all the defined functions. Just call functions as necessary below this line. Commented Jun 8, 2022 at 11:24
  • Function definition and call are 2 separate things. You can define the function and then call it in the if __name__ block. Commented Jun 8, 2022 at 11:25
  • You could have the other functions in another file and import it before this segment. Commented Jun 8, 2022 at 11:25
  • 4
    You can't call something that hasn't been defined yet, and Python doesn't "hoist" function definitions like some other languages do. So: no. You can put your code into a def main at the top which you call at the bottom…? Commented Jun 8, 2022 at 11:25
  • 1
    @VimNing You could put all of the code executed below the if __name__ == __main__ call into yet another function, and put it at the very top of the file... Then just call that function and it will do the same thing Commented Jun 8, 2022 at 11:36

1 Answer 1

1

What you can do is to wrap the invocation into a function of its own.

So that

foo()

def foo():
    print "Hi!"

will break, but

def bar():
    foo()

def foo():
    print "Hi!"

bar()

will be working properly.

General rule in Python is not that function should be defined higher in the code but that it should be defined before its usage.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.