1

Say I have a script.py that imports module.py,

In the module, __file__ returns path\module.py

Is there a variable or something I can use in the module that returns path\script.py or script.py?

at the moment I'm doing module.config(__file__) in script.py instead.

azro
  • 53,056
  • 7
  • 34
  • 70
jdoe
  • 79
  • 1
  • 7
  • You can likely use `inspect` but I don't like to rely on it – Peter Jan 06 '22 at 18:06
  • I don't see anything wrong with using a method and passing a variable you have, but what is the use case for having something know what other modules have imported it? – OneCricketeer Jan 06 '22 at 18:07
  • I actually think your approach is the best. A lower layer in a design (i.e. an imported module) ought to have no interaction with a higher layer than what the higher layer proactively does with it. If `module.py` needs a piece of information (such as the file name `"script.py"`), it is up to the user (`script.py`) to provide it – TallChuck Jan 06 '22 at 18:16
  • @SuperStormer ```import __main__``` and then ```logfile=open("{f}.log".format(f=__main__.__file__),"a")``` works great – jdoe Jan 06 '22 at 18:19
  • @OneCricketeer I'm making a simple logger that writes the log filename based on the name of the host file. – jdoe Jan 06 '22 at 18:24
  • The builtin logging module should be used for this, rather than using open method – OneCricketeer Jan 06 '22 at 19:01

0 Answers0