Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading