Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

imp.reload - NoneType object has no attribute 'name'

The following code:

def _IMPORT_(path)
    path = abspath(path)
    namespace = path[len(getcwd())+1:].replace('/', '_').strip('\\/;,. ')
    print(path)
    print(namespace)
    loader = importlib.machinery.SourceFileLoader(namespace, path+'.py')
    handle = loader.load_module(namespace)
    print(handle)
    importlib.reload(handle)
    return handle

Produces:

/home/torxed/git/test/unitest/unix
unitest_unix
<module 'unitest_unix' from '/home/torxed/git/test/unitest/unix.py'>

Traceback (most recent call last):
  File "network.py", line 17, in <module>
    handle = sock()
  File "network.py", line 9, in __init__
    sock = _IMPORT_('./unix')
  File "/home/torxed/git/test/unitest/helpers.py", line 13, in _IMPORT_
    imp.reload(handle)
  File "/usr/lib/python3.4/imp.py", line 315, in reload
    return importlib.reload(module)
  File "/usr/lib/python3.4/importlib/__init__.py", line 149, in reload
    methods.exec(module)
  File "<frozen importlib._bootstrap>", line 1134, in exec
AttributeError: 'NoneType' object has no attribute 'name'

This works perfectly in Python 3.3.5 where this sort of operation was introduced (there were some similar import-mechanics before this). However on Python 3.4.2 This apparently doesn't work.

What's changed since 3.3.5? Can't find any traces of it or the change is somewhere in the middle of the releases. There were a patch last year for this exact behavior where the environment variables wasn't passed down but that appears to be working here.

like image 844
Torxed Avatar asked Dec 03 '14 13:12

Torxed


1 Answers

I get the same error when I try to reload a file after switching folders.

For example:


Create a simple module:

In [10]: %%file temp.py
    ...: message = "Hello World!"
    ...: 
Writing temp.py

Load the module and print a message:

In [14]: import temp
    ...: print(temp.message)
Hello World!

Change the message:

In [17]: temp.message = 'Hello brave new world!'
    ...: print(temp.message)
Hello brave new world!

Reload the module to get back the original message:

In [18]: import imp
    ...: imp.reload(temp)
    ...: print(temp.message)
Hello World!

Everything good so far...


Now change paths:

In [20]: cd ..

Try to reload the module:

In [24]: imp.reload(temp)
Traceback (most recent call last):

  File "<ipython-input-24-7fa95de0f250>", line 1, in <module>
imp.reload(temp)

  File "/home/user/anaconda3/lib/python3.4/imp.py", line 315, in reload
return importlib.reload(module)

  File "/home/user/anaconda3/lib/python3.4/importlib/__init__.py", line 149, in reload
methods.exec(module)

  File "<frozen importlib._bootstrap>", line 1134, in exec

AttributeError: 'NoneType' object has no attribute 'name'

In my case, the solution was to switch back to the path where the imports were made originally.

like image 192
ostrokach Avatar answered Sep 27 '22 15:09

ostrokach