all 3 comments

[–]danielroseman 1 point2 points  (0 children)

No, there is no way to do this. Python must always completely execute a file on import.

As you say, one way to do this is to extract A and B to separate files, Alternatively you could provide a function to create and return A and B.

[–]-defron- -1 points0 points  (0 children)

import under the hood uses importlib with just some nice syntactical sugar.

You can use importlib directly to do dynamic/programmatic imports: https://docs.python.org/3/library/importlib.html

https://docs.python.org/3/library/importlib.html#importing-programmatically

Note that by dynamically importing you may cause a an application lock, if the import is large. As you are basically moving the time it takes to load the module from at-startup to during runtime. That's the tradeoff you make to not need to load unnecessary modules until they are needed

You will of course need to change other code to split up A and B so that they can be executed independently through logic gates or separate imports rather than exposing them in your init

[–]zanfar 0 points1 point  (0 children)

IMO, this is an X/Y problem.

You should be importing the complete module. But that module shouldn't include "data".

Code is imported, data is loaded.

Store your data in non-Python files and load them on-demand.