Proper way to reload a python module from the console

前端 未结 8 1948
迷失自我
迷失自我 2020-12-03 04:51

I\'m debugging from the python console and would like to reload a module every time I make a change so I don\'t have to exit the console and re-enter it. I\'m doing:

<
8条回答
  •  时光说笑
    2020-12-03 05:08

    Unfortunately you've got to use:

    >>> from project.model import user
    >>> reload(user)
    

    I don't know off the top of my head of something which will automatically reload modules at the interactive prompt… But I don't see any reason one shouldn't exist (in fact, it wouldn't be too hard to implement, either…)

    Now, you could do something like this:

    from types import ModuleType
    import sys
    _reload_builtin = reload
    def reload(thing):
        if isinstance(thing, ModuleType):
            _reload_builtin(thing)
        elif hasattr(thing, '__module__') and thing.__module__:
            module = sys.modules[thing.__module__]
            _reload_builtin(module)
        else:
            raise TypeError, "reload() argument must be a module or have an __module__"
    

提交回复
热议问题