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?)

4
  • 1
    importlib.reload() takes a module(means a folder with __init__.py inside it). So importlib.reload(mainpage) should work. Commented Jan 11, 2019 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. Commented Jan 11, 2019 at 19:59
  • Possible duplicate of How do I unload (reload) a Python module? Commented Jan 11, 2019 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 Commented Jan 11, 2019 at 20:35

1 Answer 1

4
+100

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.