Calling a function that lives in `a.py`, that gets the filename of `b.py`

I have two files a.py and b.py.

a.py is where my functions live, and b.py is where my function calls live.

From b.py, I need to call a function that lives in a.py, that gets the filename of b.py.

a.py

import os

# functions
def foo():
    filename = os.path.basename(os.path.realpath(__file__))
    """ and then some other stuff """

b.py

from a import *

# function calls
foo()

But obviously __file__ in a.py is:

a.py

Is there a way to make this work without doing this:

a.py

import os

# functions
def foo():
    """ some other stuff """

b.py

from a import *

filename = os.path.basename(os.path.realpath(__file__))

# function calls
foo()

Which is completely possible, just much less elegant.

>Solution :

If you only need the filename you can just import sys and use sys.argv[0]. If you want to use the filename and do some other things you can pass sys.argv[0] into foo.

If you really want to have all the functionality live in a.py you can try this.

Leave a Reply