Python中能否提前调用未定义函数?如何定义函数原型解决报错?
1. Can you call a function before it's defined in Python?
In short: No, not if you’re calling it directly at the top level—Python interprets code line by line from top to bottom. If you try to call a function before its definition is processed, the interpreter has no idea what that name refers to, hence the NameError (or "Unresolved reference" in IDEs like PyCharm).
That said, there’s a loophole: if the function call is inside another function that doesn’t execute until after the target function is defined, it works perfectly. For example:
def run_later(): my_function() # This is safe because run_later() isn't called yet def my_function(): print("Do something...") run_later() # Now my_function exists, so this runs without errors
This works because when run_later() is invoked, the interpreter has already processed the my_function definition.
2. Fixing your "Unresolved reference 'my_function'" error
Your example code fails because you’re calling my_function() directly at the top level before defining it:
my_function() # Interpreter hits this first—no idea what my_function is! def my_function(): print("Do something...")
Python doesn’t have formal function prototypes (like C/C++) where you declare a function’s signature upfront. Here’s how to fix this:
Option 1: Reorder your code (most Pythonic solution)
Simply move the function definition above the call. This aligns with Python’s top-to-bottom execution flow and is the cleanest approach:
def my_function(): print("Do something...") my_function() # Now the interpreter knows exactly what my_function is
Option 2: Forward references (for edge cases like mutual recursion)
If you can’t reorder code (e.g., two functions that call each other), you can define one function first even if it references the other—just make sure both are defined before either is called. For example:
def func_a(): print("A") func_b() # func_b isn't defined yet, but that's okay for now def func_b(): print("B") func_a() func_a() # Now both functions exist, so this runs (though it'll recurse infinitely!)
This works because by the time func_a() is called, func_b has been fully defined.
Important note about IDE warnings
If your IDE (like PyCharm) shows "Unresolved reference" even after fixing the order, it might be a false positive. Try reloading the project or checking your IDE’s Python interpreter settings to ensure it’s pointing to the correct environment.
内容的提问来源于stack exchange,提问作者Arman Laalfam

