Search code examples
pythonpython-decorators

Decorating a function only when used in a module


I am sorry if the question title is vague, I could not think of a better one.

I have a bunch of functions inside a module which I wish behaved differently when called locally versus when called from other modules.

Here is a toy example moduleA.py

def func(arg1):
     pass
     do something

moduleB.py

import moduleA
func(arg1) 

In moduleB the call for func() needs to do

initSomething
func(arg1)
doSomethingElse

And when func() is called from moduleA, I still need the original behavior. While the problem screams at me for using decorators, I am not sure on writing a decorator for func() that will be triggered only when called from a module.


Solution

  • Sounds to like you want to give the function calls a certain context. That's what context managers are for. You could do sth like:

    from contextlib import contextmanager
    
    @contextmanager
    def func_context():
        # init_something
        yield
        # do_something_else
    
    with func_context():
        func(arg1)