1

I have the following statement:

>>> sys.path.append(os.path.abspath(os.path.join(__file__, os.pardir, os.pardir)))

However, occasionally __file__ will not be defined in the namespace:

NameError: name '__file__' is not defined

What would be the best way to check for this? The first thing that came to mind was if '__file__' in globals().

David542
  • 104,438
  • 178
  • 489
  • 842
  • 5
    When is `__file__` not defined? Could you provide the arguments you passed to the python interpreter? The only case I can imagine is running in the REPL (which appears to be the case with the `>>>`). In that case, I suppose you could just try-catch and just use the cwd as your base path. – 101arrowz Feb 27 '20 at 18:47
  • 3
    It would help to have the context here, but this seems like [an X-Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me. Manipulating the pythonpath from within a python program is usually a sign of something not being set up properly... – kojiro Feb 27 '20 at 18:51
  • Does this answer your question? [How do I check if a variable exists?](https://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists) – G. Anderson Feb 27 '20 at 18:53
  • @101arrowz yes, this was a script copy-pasted into the command prompt. – David542 Feb 27 '20 at 19:01

1 Answers1

1

To answer your question directly, a fairly pythonic way to test if a name exists is to catch the exception:

from pathlib import Path

try:
    value = Path(__file__, '..', '..').resolve().absolute()
except NameError:
    value = os.getenv('TMPDIR', '/tmp/foo')
kojiro
  • 74,557
  • 19
  • 143
  • 201