Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

importerror: cannot import name

# Python ImportError: cannot import name error 
# is cause by either:  
# 1: The import module/class is inaccessible (not installed or ot reacheable by current PYTHONPATH)
# 	 Fix : Install module with pip or easy install or correct PYTHONPATH

# 2: You have created a circular dependancy such as:

# in foo.py
...
import bar
...

# in bar.py
...
import foo
...

# How to Fix it
# 1 - refactor your code (not always straitforward ...)
# 2 - Of course you should definitely avoid circular dependencies, 
#     but sometimes as a quick fix you can use some kind of lazy loading to defer imports

# In a method or function

def function_using_foo():
	import foo
    # now u can use foo here
    foo.baz()
    ...
    
def function_returning_foo():
	import foo
    # Hint: You can cache foo for more efficiency ...
    return foo  

# now u can use foo everywhere this way
function_returning_foo().baz()
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #import
ADD COMMENT
Topic
Name
4+7 =