0

I have a here.py that gets the nearest folder name:

import os
def here():
    return os.path.basename(os.path.dirname(__file__))

I have app.py which imports here.py and calls it:

from this_app.somewhere import here
print(here.here())

Finally, this is my folder structure:

this_app
  ├ __init__.py
  ├ app.py
  └ somewhere
    ├ __init__.py
    └ here.py

So you can see when I run app.py it will print somewhere because it is executing code in here.py

I want to keep the code in here.py but make it print out the folder app.py is in. In otherwords, I want to print the folder of the file that imported the module instead of the folder where the module is located, even though I want the code that decides what to print to be in the module.

I hope that makes sense. Basically, how do I change here.py so that when I call app.py it prints this_app (that is, it prints the folder name of wherever app.py is located)?

(One last consideration: my actual use case is more complicated than this so it can't resort to the current working directory because I might start the app.py from a directory far away from any of this. It has to be relative to the file that imports the here module, namely app.py.)

1 Answer 1

1

The __file__ attribute is defined per-module. You need to pass the __file__ of the calling module to here

here.py

import os
def here(calling_path):
    return os.path.basename(os.path.dirname(calling_path))

And use it:

from this_app.somewhere import here
print(here.here(__file__))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.