#๐Ÿ”’ Is it possible to know if I'm being imported outside of __init__.py or __main__.py?

14 messages ยท Page 1 of 1 (latest)

glacial pecan
#

I want to know if my package is being executed via python -m package/ poetry run/etc or imported via import package.

I've read I can use the __name__ check, but it seems to only work from one of the main files of the package. I'd like to do the check in a different source file from a utils function.

Is it possible?

summer kettleBOT
#

@glacial pecan

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

karmic viper
#

it might be possible, but it's pretty unusual. Whatever problem you're trying to solve this way would likely be better solved some other way.

#

it seems to only work from one of the main files of the package.
What do you mean by this? __name__ works the same everywhere.

glacial pecan
#

I'm trying to load config info based on how the package was imported. I'm doing it from a utility file due to SOC reasons.

I just double checked and yes it doesn't work. If used in a different source file, it will just give the name of the file, since that source file is imported even if the main package was executed.

karmic viper
#

"just give the name of the source file" is what it always does if it's imported. And if it's not imported, it's __main__

#

anyway

#

what is SOC?

#

"Summer of Code"? "Sarbanes-Oxley Compliance"?

glacial pecan
#

It's the basic software development principle Separation of Concerns.

manic wolf
karmic viper
#

hm, well, I still don't understand what problem you're trying to solve.

summer kettleBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.