0

I'm using PyCharm with Python 3.7. In my Python console, how do I reload a module that I've changed? I created a file, "services.py" where I created a service class in

class ArticlesService:
    def process(self):

As I test this in the console, I can't seem to figure out how to reload it. This is the error I get

from mainpage.services import ArticlesService
importlib.reload(ArticlesService)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 140, in reload
    raise TypeError("reload() argument must be a module")
TypeError: reload() argument must be a module

How do I refer to my class to reload it? (Or better yet, how do I get the console to automatically reload everything I've changed?)

Dave
  • 15,639
  • 133
  • 442
  • 830
  • 1
    `importlib.reload()` takes a module(means a folder with `__init__.py` inside it). So `importlib.reload(mainpage)` should work. – ruddra Jan 11 '19 at 18:29
  • Althoguh "mainpage" is the name of my application, I get the error, "NameError: name 'mainpage' is not defined" when I try that. – Dave Jan 11 '19 at 19:59
  • Possible duplicate of [How do I unload (reload) a Python module?](https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module) – Scott Skiles Jan 11 '19 at 20:27
  • I'm using the answer from that page, but when I run "importlib.reload(mainpage)", I get the error as per my comment to @ruddra – Dave Jan 11 '19 at 20:35

1 Answers1

3

from mainpage.services import ArticlesService only imports the class into your namespace, so you have no reference to the module in the namespace. From the importlib.reload docs:

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before.

So make sure to import the module if you want to reload later:

import importlib
import mainpage
from mainpage.services import ArticlesService

...

importlib.reload(mainpage)

This should work as well:

import importlib
import mainpage.services
from mainpage.services import ArticlesService

...

importlib.reload(mainpage.services)
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Ah, it would appear I had forgotten to run "import mainpage". Doing that causes the reload command to work afterwards. It would be great if all that coudl get done automatically but oh well. I'll come back and accept in 3 hours as SO doesn't let me award right away. Thx! – Dave Jan 14 '19 at 16:32