I'm really unsure why this isn't working. Here is the important part of the code (it's from a leetcode challenge). The first line throws the NameError.
def totalFruit(self, tree: List[int]) -> int:
pass
If I try importing List
first I get an error No module named 'List'
. I'm using Python 3.7.3 from Anaconda.
The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.
You can fix this by doing global new at the start of the function in which you define it. This statement puts it in the global scope, meaning that it is defined at the module level. Therefore, you can access it anywhere in the program and you will not get that error.
The Python "NameError: name 'numpy' is not defined" occurs when we use the numpy module without importing it first. To solve the error, install the module and import it ( import numpy ) before using it. Open your terminal in your project's root directory and install the numpy module.
NameError is a kind of error in python that occurs when executing a function, variable, library or string without quotes that have been typed in the code without any previous Declaration. When the interpreter, upon execution, cannot identify the global or a local name, it throws a NameError.
To be able to annotate what types your list should accept, you need to use typing.List
from typing import List
So did you import List
?
Update
If you're using Python > 3.9, see @Adam.Er8's answer
Since Python 3.9, you can use built-in collection types (such as list
) as generic types, instead of importing the corresponding capitalized types from typing
.
This is thanks to PEP 585
So in Python 3.9 or newer, you could actually write:
def totalFruit(self, tree: list[int]) -> int: # Note list instead of List
pass
without having to import anything.
To be able to specify a list of str's in a type hint, you can use the typing
package, and from typing import List
(capitalized, not to be confused with the built-in list
)
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