gt6989b
gt6989b

Reputation: 4233

Testing for presence of IPython

I have the same code, which I occasionally run from the command line as python source.py and occasionally copy/paste it into interactive IPython. I would like to execute slightly different code in either way, and tried to embed differences into the following code block:

try:
    __IPYTHON__
    # do IPython-mode code
except NameError:
    # do script-mode code

I know that in Python this is a common technique, but it screws up automated flagging in PyCharm and I was hoping to find some more attractive way to test for the presence of IPython, perhaps by testing '__IPYTHON__' in ... or something similar. However, I saw that this symbol is neither in locals() nor in globals(). Is there any other place I can test for its presence, or any other more conventional test, not using exceptions directly?

I am using Python 2.7.11 and IPython 5.1.0. Thank you very much.

UPDATE Related but unhelpful: How do I check if a variable exists?

Upvotes: 3

Views: 647

Answers (2)

ivirshup
ivirshup

Reputation: 661

While the current accepted answer works in the __main__ namespace, it won't work in a package due to __builtins__ being a dict in other namespaces. This should work in any namespace in python3:

import builtins
getattr(builtins, "__IPYTHON__", False)

Upvotes: 4

hvwaldow
hvwaldow

Reputation: 1376

I think you are looking for

if hasattr(__builtins__, '__IPYTHON__'):
    print('IPython')
else:
    print('Nope')

Upvotes: 5

Related Questions