Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError: name 'List' is not defined

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.

like image 458
Ariel Frischer Avatar asked Aug 15 '19 05:08

Ariel Frischer


People also ask

How do you solve NameError name is not defined?

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.

How do you correct a NameError in Python?

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.

How do I fix NameError name NP not defined?

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.

What is NameError in Python?

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.


3 Answers

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

like image 77
LaundroMat Avatar answered Oct 07 '22 05:10

LaundroMat


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.

like image 41
Adam.Er8 Avatar answered Oct 07 '22 07:10

Adam.Er8


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)

like image 11
Itamar Mushkin Avatar answered Oct 07 '22 06:10

Itamar Mushkin