I have a simple function, which I shall call myFunction
. It takes two parameters, performs some calculations on them, and returns the result.
I also have a class, MyClass
, which has a constructor that has a header like this:
__init__(self, bar, fun=myFunction):
When I try to run anything in this class, I get the following error:
MyClass
def __init__(self, bar, fun=myFunction):
NameError: name 'myFunction' is not defined
If I remove this class, I can use myFun in the Python Shell, so what's the deal?
The Python "NameError: function is not defined" occurs when we try to call a function that is not declared or before it is declared. To solve the error, make sure you haven't misspelled the function's name and call it after it has been declared.
When you define a new function with the same name as a previously defined function, the function name is now bound to the new function object, and the old function object is reclaimed by the garbage collector.
A NameError is raised when you try to use a variable or a function name that is not valid. In Python, code runs from top to bottom. This means that you cannot declare a variable after you try to use it in your code. Python would not know what you wanted the variable to do.
To specifically handle NameError in Python, you need to mention it in the except statement. In the following example code, if only the NameError is raised in the try block then an error message will be printed on the console.
You haven't shown the actual code so it's hard to be sure, but I bet myFunction
is defined after MyClass
. The default value expression is evaluated when the __init__
method is defined, so myFunction
must be defined at that point. Defining it later is too late.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With