Skip to content

Repository files navigation

Python Hot Module Reload

python-hmr logo

Better debugging experience with HMR

Test statuspypilicense-mitEndpoint Badge

Automatic reload your project when files are modified.

No need to modify your source code. Works in any environment.

reload

Supported Syntax:

  • import X
  • from X import Y

Supported Types:

  • Module
  • Function
  • Class

Installation

pip install python-hmr

Quick Start

Caution

From v0.3.0, there is only one API, hmr.reload.

Import your dev packages as usual. And add 2 lines for automatically reloading.

importdevimporthmrdev=hmr.reload(dev)

If you have multiple modules to reload, you can do it like this.

fromdevimportrun1, run2importhmrrun1, run2=hmr.reload(run1, run2)

Now you are ready to go! Try to modify the run1 or run2 and see the magic happen.

Detailed Usage

Function/Class instance

When you try to add HMR for a function or class, remember to pass the name of the function or class instance without parenthesis.

fromdevimportRunnerimporthmrRunner=hmr.reload(Runner)
a=Runner()
b=Runner()

Important

Here, when both a and b will be updated after reloading. This may be helpful if you have an expansive state store within the class instance.

However, it's suggested to reinitialize the class instance after reloading.

@Decorated Function

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

importfunctoolsdefwork(f):
@functools.wraps(f)defargs(*arg, **kwargs):
returnf(*arg, **kwargs)
returnargs

Stateful application

If your application is stateful, you can exclude the state from being reloaded. For simplicity, you can group all your state variable into the same .py file like state.py and exclude that from being reloaded.

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

importdevimporthmrdev=hmr.reload(dev, exclude=["dev.state"])

In this way dev/state.py will not be reloaded, the state will persist.

This also apply when reloading a function or class.

fromdevimportrunimporthmrrun=hmr.reload(run, exclude=["dev.state"])

Acknowledgement

Inspired from the following package.

About

🔄 Hot module reload for python, automatically reload your code when files are modified. No need to modify source code.

Topics

Resources

Stars

34 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages