简体   繁体   中英

How do I reload a module in the Python console?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM