-1

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.

mathbike
  • 92
  • 6
  • I think you should pass the filename to the `foo` function in `a.py`. – Keijack Dec 06 '22 at 01:33
  • Yes that makes sense, although for my purpose that requires an equivalent extra step to the extra step that I'm already using. `b.py` will always be a new file. edit - is there a reason this question got downvoted? – mathbike Dec 06 '22 at 01:37

1 Answers1

0

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.

KyIe LiebIer
  • 408
  • 2
  • 12