Skip to main content

Hot module reload for python

Project description

python-hmr logo

Python Hot Module Reload

Test status codecov pypi license-mit

Automatic reload your project when files are modified.

No need to modify your source code.

reload

Supported Syntax:

  • import X
  • import X as Y
  • from X import Y
  • from X import Y as A

Supported Types:

  • Module
  • Function
  • Class

Installation

pip install python-hmr

Usage

Just import your developing package and replace it with Reloader.

Then you can use it exactly like how you use a module before.

import my_pkg

from hmr import Reloader
my_pkg = Reloader(my_pkg)

my_pkg.func()
# >>> "Hi from func"

Or you can manually reload it

my_pkg.reload()

To stop the reloading

my_pkg.stop()

Module/Submodule reload

import my_pkg.sub_module as sub

from hmr import Reloader
sub = Reloader(sub)

Function/Class reload

No difference to reloading module

from my_pkg import func, Class

from hmr import Reloader
func = Reloader(func)
Class = Reloader(Class)

If your have multiple class instance, they will all be updated. Both a and b will be updated.

a = Class()
b = Class()

@Decorated Function reload

Use functools.wraps to preserve signature of your function, or the function information will be replaced by the decorator itself.

State handling

If your application contains submodule that handle state, you can exclude it from reloading. You need to move it to a new .py file like state.py and everything from that file will not be reloaded.

Make sure you know what you are doing. This could lead to unexpected behavior and unreproducible bugs.

import my_pkg

from hmr import Reloader
my_pkg = Reloader(my_pkg, excluded=["my_pkg.state"])

This will exclude the my_pkg/state.py from reloading.

Even you only want to reload a submodule or a function, you still need to provide the excluded argument.

import my_pkg.sub_module as sub
from my_pkg import func

from hmr import Reloader
sub = Reloader(sub, excluded=["my_pkg.state"])
func = Reloader(func, excluded=["my_pkg.state"])

Implementation

Current implementation is relied on the importlib.reload, which is not very graceful when handling state. Direct reading of AST may be a better solution for hot module reload in python, but it's too complicated, I might try it in the future.

Acknowledgement

Inspired from the following package.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python-hmr-0.1.1.tar.gz (5.5 kB view hashes)

Uploaded Source

Built Distribution

python_hmr-0.1.1-py3-none-any.whl (5.8 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page