2

In many situations I find myself wishing that I could tell Python to ignore a source file from a certain line onward, until the end of the file. Just one example of many is when translating code from another language to Python, function by function: After I translated one function, I want to test it, with the rest of the untranslated code still in the same file, and I hope not to parse it.

In other languages, doing this is easy. Shell has exit 0 which basically causes everything after it to never be parsed. Perl has __END__. C or C++ do not have ignore-until-end-of-file specifically, but it's easy emulate it with a #if 0 at some point and finally #endif at the end of the file.

My question is how can I do this in Python? I tried looking everywhere, and can't seem to find a solution!

To make the question more concrete, consider the following code:

print(1)
exit(0)
@$@(% # this is not correct Python

This program fails. The exit(0) doesn't help because Python still parses everything after it. Not to mention that exit(0) is obviously not the right thing to do in an imported source file (my intention is to stop reading this source file - not to exit the whole program). My question is with what I can replace the "exit(0)" line that will make this program work (print "1" and that's it).

Nadav Har'El
  • 11,785
  • 1
  • 24
  • 45

2 Answers2

4

Enclose what you don't want parsed in triple quotes:

print(1)
"""
@$@(% # this is not correct Python
blah
dee
blah
blah
"""
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
  • Very good idea. It will indeed work for the use case where the code I want to ignore is in some other programming language, or pure junk. The only downside I see now is that It will not work for actual Python code which might itself use triple quotes somewhere. But as long as I know this is not the case, your solution indeed saves the day. Thanks! – Nadav Har'El Dec 01 '20 at 22:21
  • Yes, there are limitations for sure. – Fred Larson Dec 01 '20 at 22:26
0

You can raise an exception, assuming you have some condition that is met or not

Inside the imported file

print("hi")
my_condition = True
if my_condition:
    raise Exception
print("nope")

and then wrap the import in a try block

try:
    import your_module
except Exception:
    print("source not fully read")
Mark
  • 532
  • 1
  • 4
  • 9
  • 1
    This solution doesn't solve my main concern: that the code after the "raise Exception" needs to be valid Python as well. If it has any syntax errors (or not even real Python), the import will fail. – Nadav Har'El Dec 01 '20 at 22:37