Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting Name Error when importing a class?

Tags:

python

I am just starting to learn Python, but I have already run into some errors. I have made a file called pythontest.py with the following contents:

class Fridge:
    """This class implements a fridge where ingredients can be added and removed individually
       or in groups"""
    def __init__(self, items={}):
        """Optionally pass in an initial dictionary of items"""
        if type(items) != type({}):
            raise TypeError("Fridge requires a dictionary but was given %s" % type(items))
        self.items = items
        return

I want to create a new instance of the class in the interactive terminal, so I run the following commands in my terminal: python3

>> import pythontest
>> f = Fridge()

I get this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Fridge' is not defined

The interactive console cannot find the class I made. The import worked successfully, though. There were no errors.

like image 206
Kelp Avatar asked Oct 07 '10 19:10

Kelp


People also ask

Why am I getting name errors in Python?

What Is a NameError in Python? In Python, the NameError occurs when you try to use a variable, function, or module that doesn't exist or wasn't used in a valid way. Some of the common mistakes that cause this error are: Using a variable or function name that is yet to be defined.

How do you remove 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.

How do you fix an import error in Python?

Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .

Can not import name Python?

The Python "ImportError: cannot import name" occurs when we have circular imports (importing members between the same files). To solve the error, move the objects to a third file and import them from a central location in other files, or nest one of the imports in a function.


1 Answers

No one seems to mention that you can do

from pythontest import Fridge

That way you can now call Fridge() directly in the namespace without importing using the wildcard

like image 192
Falmarri Avatar answered Nov 02 '22 02:11

Falmarri