Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my python function not defined, when it exists in the same file?

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?

like image 336
user1123936 Avatar asked Jun 22 '12 23:06

user1123936


People also ask

Why is Python saying my function is not defined?

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.

What happens if you define two functions in a module that have the same name?

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.

Why is variable not defined Python?

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.

How do I fix name errors in Python?

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.


1 Answers

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.

like image 194
Ned Batchelder Avatar answered Nov 15 '22 09:11

Ned Batchelder