0

In python is it possible to write a module which results in the following behavior:

from my_module import normal_stuff
# nothing happens

but

from my_module import normal_stuff, arcane_magic
# some code has been executed behind the scenes (i.g. redefining sys.excepthook)

I imagine that this could be done by parsing the importing script with the help of the inspect-module but maybe there is a "cleaner" way.

cknoll
  • 2,130
  • 4
  • 18
  • 34
  • 1
    See https://stackoverflow.com/questions/2447353/getattr-on-a-module for a possible solution; basically the module can replace its own entry in `sys.modules` with a class instance, which can have a `__getattribute__()` defined to do arbitrary things on access to a particular name. – jasonharper Aug 18 '17 at 18:56

1 Answers1

0

I would just put the following code under my imports:

from my_module import normal_stuff, arcane_magic

if 'arcane_magic' in globals():
    # do some magic stuff
    pass
kchomski
  • 2,872
  • 20
  • 31
  • nice idea in principle but I look for a solution which does not depend on code in the importing script. The "magic" should completely be contained in `my_module` – cknoll Aug 20 '17 at 15:02