cwapi3d / cwapi3dpython

Cadwork Python Interface
https://docs.cadwork.com/projects/cwapi3dpython
MIT License
21 stars 8 forks source link

API script importing from other files #201

Open sam-snodgrass opened 1 month ago

sam-snodgrass commented 1 month ago

Hello, currently encountering this behaviour when developing with one script that imports from another file.

example (folder) | |---example.py |---other_file.py

When running example in the APIs, changes made in other_file.py are not present unless the cadwork application is closed and reopened. Is this expected behaviour and if not, could this possibly be addressed in any capacity? i.e. having changes made in other files be present when the main script is run.

Thank you

Brunner246 commented 1 month ago

This is currently not possible. We will analyze if we can make this possible.

Alternatively, you could execute your Python code via IDLE Shell during development stage. If you do this, you would have to close and restart the shell as soon as you have made changes.

chenkasirer commented 1 month ago

Hi @sam-snodgrass,

You could get a "hot-reload" kind of behavior in your script using a small helper function which pops the library module from the modules dictionary, causing Python to re-load it next time it's imported.

import sys

def reload_module(module_name):
    to_remove = [m for m in sys.module.keys() if m.startswith(module_name)]
    for m in to_remove:
        del sys.modules[m]

Then call it at the top of your script (example.py), before importing the library:

reload_module("other_file")
from other_file import example_func

That way, you shouldn't have to restart cadwork to see changes in other_file.py reflected.

However, depending on your library code, this can cause some pretty nasty issues. Python will re-defining the types in the modules you reload. So if your library defines a class A, which is reloaded, any instances of A from before the reload still in memory will not be instances of the same class A after the reload. More concretely, checks like type(old_a) is A might unexpectedly return False and dictionary lookups like some_dict[type(a)] might raise KeyError.

I spent so much time tracking down such issues that honestly I probably would have saved time restarting cadwork ;))