Ошибка python importerror cannot import name

How to Fix ImportError: cannot import name in Python

The ImportError: cannot import name error occurs in Python when the imported class is in a circular dependency or the imported class is unavailable or was not created.

To fix ImportError: cannot import name in Python, “resolve the circular dependencies, and defer imports.” To fix the circular dependencies, we can use the module in a function when we need it.

Breaking a circular dependency makes the code cleaner and more understandable and gives easy access to all methods requiring dependency.

Python implements at least three different ways to import modules. You can use the import statement, the from statement, or the built-in __import__ function.

Modules are performed during import, and new functions and classes won’t see in the module’s namespace until the def (or class) statement has been executed.

Python program to fix it

See the below snippet, which eliminates the circular dependencies.

import WhateverModule def WhateverFunction(arg): from some.dependency import DependentClass

Python can detect circular dependencies and prevent the infinite loop of imports. What happens is that an empty placeholder is created for the module.

Читайте также:  text-align

Once the circularly dependent modules are compiled, it updates the imported module.

Making logic clear is very important. This problem appears because the reference becomes a dead loop. Let’s take an example of circular dependencies.

Let’s define a y.py file with the following code.

from x import x1 def y1(): print('y1') x1() def y2(): print('y2') if __name__ == '__main__': y1()

This file uses the function imported from the x.py file.

Now, let’s define the x.py file.

from y import y2 def x1(): print('x1') y2()

Now, this file x.py is dependent on y.py. So that means the x.py file is dependent on y.py.

You can see the circular dependencies.

Finally, if you run the file y.py file, you can see the following code.

Traceback (most recent call last): File "/Users/krunal/Desktop/code/pyt/database/y.py", line 1, in from x import x1 File "/Users/krunal/Desktop/code/pyt/database/x.py", line 1, in from y import y2 File "/Users/krunal/Desktop/code/pyt/database/y.py", line 1, in from x import x1 ImportError: cannot import name 'x1' from partially initialized module 'x' (most likely due to a circular import) (/Users/krunal/Desktop/code/pyt/database/x.py)

And we get the following error.

ImportError: cannot import name ‘x1’ from partially initialized module ‘x’.

To fix the ImportError, modify the x.py file. For example, instead of importing the y module at the start of the x.py file, write at the end of the file.

def x1(): print('x1') y2() from y import y2

Now rerun, and you can see the following output.

We have solved this problem by using the import module or class or function where we needed it. If we use this approach, we can fix circular dependency.

Источник

Ошибка python importerror cannot import name

Last updated: Feb 18, 2023
Reading time · 6 min

banner

# ImportError: cannot import name X in Python [Solved]

The error «ImportError: cannot import name X» occurs for multiple reasons:

  1. Having circular imports between files.
  2. Misspelling the name of the function or class that is being imported or the name of the module you are importing from.
  3. Trying to import a function or class that isn’t available in the specified module, version of the module, or version of the Python interpreter (for standard libraries).
  4. Naming a file with the same name as a module you’re trying to import from, e.g. sys.py and then importing from the sys module.

The error often occurs when we have circular imports (importing members between the same files).

To solve the error, move the functions or classes to a third file and import them from a central location in other files.

importerror cannot import name

# Resolving circular import issues

Here is an example of having circular imports (importing members between the same files).

This file is called main.py and imports a function from another.py .

Copied!
from another import do_multiplication # 👈️ imports from another.py def do_addition(a, b): return a + b print(do_multiplication(5, 5))

And here is the code for another.py .

Copied!
from main import do_addition # 👈️ imports from main.py def do_multiplication(a, b): return a * b # ⛔️ ImportError: cannot import name 'do_multiplication' from partially initialized module 'another' (most likely due to a circular import) (/home/borislav/Desktop/bobbyhadz_python/another.py) print(do_addition(5, 5))

We are importing members between the two files, so they depend on one another.

This is very confusing for the Python interpreter and should be avoided.

Instead, you can move the functions to a third file, and import them from a central location in your other files, without having to deal with circular imports.

Here is the updated code for third.py .

Copied!
def do_addition(a, b): return a + b def do_multiplication(a, b): return a * b

And now we are able to import the two functions in any other file without having circular imports.

Copied!
from third import do_addition, do_multiplication print(do_addition(5, 5)) # 👉️ 10 print(do_multiplication(5, 5)) # 👉️ 25

The another.py file can also import the functions from third.py without any issues.

Now the interpreter won’t get confused when running our code because we don’t have imports between the same files.

For example, if you have files a.py and b.py , move the objects in a file called c.py and import the objects from c.py to avoid any circular imports.

# Try to import the entire module

If the error persists, try to import the entire module, instead of importing a specific member from the module.

Copied!
import math # ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp'] print(dir(math))

print all attributes of module

You can use the dir() function to print all of the attributes of the module and check if the member you are trying to import exists in the module.

You can also use your IDE to try to autocomplete when accessing specific members.

If autocomplete doesn’t automatically start, try pressing CTRL + Space on your keyboard.

If your IDE can’t help you with autocomplete, the member you are trying to access likely doesn’t exist in the module.

You can also try to autocomplete directly when importing the module.

For example, if you start typing from numpy import and press CTRL + Space to start autocomplete, your IDE should come up with suggestions of valid imports.

Copied!
from numy import press CTRL + Space>

# Make sure you don’t have spelling errors in import statements

Carefully check your spelling as the names of functions, classes and modules are case-sensitive.

If you misspell the name of the function or class you’re trying to import, the error occurs.

For example, the following import statement causes the error.

Copied!
# ImportError: cannot import name 'Array' from 'numpy' (/home/borislav/Desktop/bobbyhadz_python/venv/lib/python3.11/site-packages/numpy/__init__.py) from numpy import Array print(Array)

The error is caused because I tried to import Array (uppercase A ) from numpy and the function is actually named array (lowercase a ).

Copied!
from numpy import array # ✅ works print(array)

Correcting the spelling error resolves the issue.

# Trying to import a member from a file that doesn’t export it

You might be trying to import a function or class from a module that doesn’t export it.

For example, you might have installed a version of the module in which the specified function doesn’t exist because it has been moved or completely removed.

  1. The module you are trying to import from exists.
  2. However, the member you are trying to import from the module doesn’t exist.

# Trying to use a function that isn’t available in your version of Python

The same could be the case for your specific version of Python.

A standard module might not contain the function you are trying to import because it is added in a later version or has been removed.

You can try to google around to see if the package you are importing from contains the function or class you are trying to import.

You can check your Python version with the python —version command if importing built-in modules.

check python version

Or you can check your version of a specific package with the pip show package-name command if importing from third-party modules.

check package version

Make sure to replace numpy with the name of the package you are importing from.

# Shadowing a module with a local file with the same name

Make sure you haven’t named a file in your project with the same name as the module you are trying to import from, e.g. numpy.py .

local file shadows module

This would shadow the module you are trying to import from and is often a cause of the error.

Notice that there is a local file named numpy.py in the example.

When I try to import from the numpy module, the error is raised because Python only finds my local numpy file.

To resolve the error, rename your local file to not shadow the remote, third-party module.

When you have a local file with the same name as a global module you’re trying to import, the Python interpreter finds the local file first and exits.

For example, if you have a local file named example.py , you won’t be able to import from the example module because the Python interpreter will only be able to find your own example.py file when resolving the path.

# Restart the kernel in Jupyter Notebook

If the error persists and you use Jupyter Notebook, try restarting the kernel.

restart-kernel

# Conclusion

To solve the «ImportError: cannot import name X» error, make sure:

  1. You don’t have any circular imports between your files.
  2. You haven’t misspelled the name of the function or class that is being imported or the name of the module you are importing from.
  3. You aren’t trying to import a function or class that isn’t available in the specified module, version of the module, or version of the Python interpreter (for standard libraries).
  4. You haven’t named a file in your project with the same name as a module you are trying to import from, e.g. sys.py .

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью