Search code examples
pythonmoduleprogram-entry-point

Check name of running script file in module


I have 2 app files with import same module:

#app1.py
import settings as s
another code

#app2.py
import settings as s
another code

I need in module check if running first or second app:

#settings.py
#pseudocode
if running app1.py:
   print ('app1')
elif:
   print ('app2')

I check module inspect but no idea.

Also I am open for all better solutions.

EDIT: I feel a bit foolish (I guess it is easy)

I try:

var = None
def foo(a):
    var = a

print (var)

but still None.


Solution

  • I'm not sure it is possible for an importee to know who imported it. Even if it was, it sounds like code smell to me.

    Instead, what you can do is delegate the decision of what actions are to be taken by app1 and app2, instead of having settings make that decision.

    For example:

    settings.py

    def foo(value):
        if value == 'app1': 
            # do something        
        else:
            # do something else
    

    app1.py

    from settings import foo    
    foo('app1')
    

    And so on.


    To assign within the function and have it reflect on a global variable. Example:

    A.py

    var = None
    
    def foo(a):
        global var
        var = a
    
    def print_var():
        print(var)
    

    test.py

    import A
    
    A.print_var()
    A.foo(123)
    A.print_var()
    

    Output:

    None
    123
    

    Note that globals aren't recommended in general as a programming practice, so use them as little as possible.