Reputation: 4028
Im aware, I could simply write the code indented under if __name__ == '__main__
or put it in a function. However, that would add an unnecessary indentation level. I'm also aware this would be bad style and I should write a proper module. I was just wondering. An entry-point for use with setuptools
is, of course, even better and people should not be lazy and use these with virtualenv for testing. I'm asking this question for the purely academic knowledge of 'is there a command to finish importing a file early'.
One can return functions early to prevent the rest of the function code from executing. This has the benefit of saving an indentation level. Example:
def my_func(arg):
print arg
if arg == 'barrier':
return
print 'arg is not barrier'
# ...
# alot more nested stuff that
# will not be executed if arg='barrier'
Saves an indentation level, when compared to:
def my_func(arg):
print arg
if arg == 'barrier':
return
else:
print 'arg is not barrier'
# ...
# alot more nested stuff that
# is one indentation level deeper :-(
Is it possible to do something similar, when importing a module, so that the rest of the code is not imported? For example in the module file:
# !/usr/bin/python
# I'm a module and a script. My name is 'my_module.py'.
# I define a few functions for general use, and can be run standalone.
def my_func1(arg):
# ... some code stuff ...
pass
def my_func2(gra):
# ... some other useful stuff ...
pass
if __name__ != '__main__':
importreturn # Statement I'm looking for that stops importing
# `exit(0)` here would exit the interpreter.
print 'I am only printed when running standalone, not when I'm imported!'
# ... stuff only run when this file is executed by itself ...
So that I don't see "I am only printed when running standalone, not when I'm imported!", when I do:
import my_module.py
my_func2('foobar')
Upvotes: 2
Views: 936
Reputation: 41928
No, there's no statement for that in Python.
The closest thing to what you want is to raise an exception and doing your import inside a try/except block. The code after the raise statement won't be executed.
To really implement an statement like that you will need a custom import handler that does some pre-processing, and/or a custom compiler. It might be an interesting challenge if you want to learn about Python internals, but not something you should use in real applications.
Upvotes: 3
Reputation: 1239
You don't want to avoid the indentation, the indentation concisely makes it clear what you intend the code to do:
if __name__ == '__main__':
print "I am only printed when running standalone, not when I'm imported!"
else:
print "I am only printed when importing"
If you want you could wrap this in a function?
def main():
if __name__ == '__main__':
print "I am only printed when running standalone, not when I'm imported!"
return
print "I am only printed when importing"
main()
Upvotes: 2