As a beginner Python programmer, you’ve probably encountered the frustrating “function is not defined” error before. This error occurs when you try to call a function that Python can’t find a definition for.
Don’t worry – with a bit of debugging and tweaking, you’ll have it fixed in no time! In this comprehensive guide, we’ll cover what causes this error, how to fix it, and best practices to avoid it.
Also read: Python ‘Global name not defined’ Error and How to Handle It
What Triggers the “Function is Not Defined” Error in Python
There are a few key reasons why Python raises a “function is not defined” error:
Calling a Function Before Defining It
Python reads code from top to bottom. So if you try to call a function before defining it, Python won’t know what that function name refers to:
print_greeting("John")
def print_greeting(name):
print("Hello " + name)
Output:
Traceback (most recent call last):
File "example.py", line 1, in <module>
print_greeting("John")
NameError: name 'print_greeting' is not defined
Misspelling a Function Name
Python is case-sensitive. If you have a typo when calling a function, Python will think you’re trying to call a function that doesn’t exist:
def print_greeting(name):
print("Hello " + name)
print_greting("John") # typo: greting instead of greeting
Output:
Traceback (most recent call last):
File "example.py", line 4, in <module>
print_greting("John") # typo: greting instead of greeting
NameError: name 'print_greting' is not defined
Forgetting to Import a Module
If you try to call a function defined in an external module without importing that module first, you’ll get this error:
print(random.randint(1, 6)) # didn't import random module
Output:
Traceback (most recent call last):
File "example.py", line 1, in <module>
print(random.randint(1, 6))
NameError: name 'random' is not defined
These are the most common triggers for this error. Next let’s go over some ways to fix it!
Also read: Exploring the Random Module: Generating Basic Random Numbers in Python
Fixing the “Function is Not Defined” Error in Python
Here are 4 effective ways to troubleshoot and fix this error:
1. Check Function Name Spelling
Double-check that you spelled the function name correctly everywhere you referenced it. Python sees print_greeting and print_greting as two different functions.
2. Define Functions Before Calling Them
Move your function definitions to above the places where you call them. Remember: Python processes scripts from top to bottom!
3. Import Any External Modules
If the undefined function lives in an external module, don’t forget to import that module first before calling the function.
4. Use an IDE with Linting
IDEs like PyCharm can analyze your code and catch issues like undefined variables and functions. This helps fix errors even before you run your code.
Let’s look at a full debugging example to reinforce these concepts.
Example: Debugging “Function is Not Defined”
Say we have a Python script that tries to call a function called get_weather_data()
that we forgot to define:
import requests
city = "Boston"
weather = get_weather_data(city)
print(weather)
When we run it, we get:
Traceback (most recent call last):
File "script.py", line 4, in <module>
weather = get_weather_data(city)
NameError: name 'get_weather_data' is not defined
We expected to fetch weather data for Boston, but got an error instead. Let’s fix this using the debugging techniques covered earlier:
1. Check the spelling of the function name
We spelled get_weather_data
correctly when trying to call it. So spelling isn’t the issue here.
2. Define the function before calling it
Aha! We called get_weather_data()
on line 4, but haven’t defined this function anywhere. Let’s fix that:
import requests
# Define function up here
def get_weather_data(city):
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}"
response = requests.get(url)
return response.json()
city = "Boston"
weather = get_weather_data(city)
print(weather)
Now this code will run (PS. you need an API key before it actually outputs the data)!
Defining get_weather_data()
before we call it on line 10 fixed the “function is not defined” error.
3. Import any external modules
The function and calling code live in the same script, so imports aren’t relevant in this example. But remember to import modules that define functions you want to call.
4. Use a linter
An IDE like PyCharm provides real-time linting out of the box. This analyzes code for potential errors as you type. The linter would have caught the undefined function right away!
And that’s it! The key is to logically break down the issue based on the most common triggers. 9 times out of 10, the fixes will be simple namespace issues in your code.
Best Practices For Avoiding “Function is Not Defined” Errors
Here are some tips to write Python code that avoids this pesky error:
- Import modules at the top – Get module imports out of the way first before any other code.
- Define functions before calling – Follow this standard coding practice in all your scripts.
- Use descriptive names – Calling a generic name like
get_data()
is harder to debug thanget_weather_data()
orget_user_data()
. - Validate function names – Double-check names of any new functions you call. Tab completion in most IDEs helps avoid typos with this.
- Take advantage of linting – Modern IDEs will catch many errors for you in real-time, including undefined variables and functions.
Sticking to these coding best practices will help you avoid those frustrating debugging sessions tracking down the source of undefined functions!
References: Name ‘function’ is not defined – Stack Overflow