1

I want to reload() my module in the shell (or in the script) and i am getting an error. I change the content of my class defnClass which is in the file def_class.py and want to reload it, but get the exception:

NameError: name 'def_class' is not defined.

The file is in the directory where i have started the shell. Why am i getting this error?

PS: If i restart the shell everything works of course fine.

my code:

class defnClass:

d = 33.45

def __init__(self, a, b, c):
    self.a = a
    self.b = b
    self.c = c

def add(self):
    return self.a + self.b + self.c

def mult(self):
    return self.a * self.b * self.c

def sub(self):
    return self.a - self.b - self.c

def div(self, n):
    return 12 / n

I then change this code after having used it, to the following:

class defnClass:

d = 33.45

def __init__(self, a, b, c):
    self.a = a
    self.b = b
    self.c = c

def add(self):
    return self.a + self.b + self.c + self.div(3)

def mult(self):
    return self.a * self.b * self.c

def sub(self):
    return self.a - self.b - self.c

def div(self, n):
    return 12 / n

Then i try to import the new version in the shell after having saved it with reload(def_class) which results in the following:

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

I have started the python-shell from inside the directory where the def_class.py file is.

1 Answers1

2

If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.name) instead.

https://docs.python.org/2/library/functions.html#reload

Thats why you should use from module import class again instead of reload(module).

But I recommend you to use import module instead of from module import class, and call class in your code with module.class(), and don't use from module import *.

You can read about this in Mark Roddy answer - 'import module' or 'from module import'

Community
  • 1
  • 1
Alexey Astahov
  • 203
  • 1
  • 7
  • It doesn't work! I still have to exit from the shell and restart it in order to get accsess to the updated module. Maybe does this have to do with python version 2.7.6? –  Feb 05 '16 at 14:31
  • ok, i think this is something has to do with my emacs setup using **elpy**. I downloaded the python IDLE and it just works fine! But in emacs+elpy it just doesn't work –  Feb 06 '16 at 09:05