conditional evaluation of source file in python
Say I have a file that's only used in pre-production code
I want to ensure it gets not run in production code- any calls out to it have to fail.
This snippet at the top of the file doesn't work - it breaks the Python grammar, which specifies that return
must take place in a function.
if not __debug__:
return None
What is the best solution here - the one that doesn't involve开发者_如何学运维 making a gigantic else, that is. :-)
if not __debug__:
raise RuntimeError('This module must not be run in production code.')
Maybe split the non-production code out into a module which is conditionally imported from the main code?
if __debug__:
import non_production
non_production.main()
Updated: Based on your comment, you might want to look a 3rd-party library pypreprocessor which lets you do C-style preprocessor directives in Python. They provide a debugging example which seems very close to what you're looking for (ignoring inline debug code without requiring indentation).
Copy/pasted from that url:
from pypreprocessor import pypreprocessor
pypreprocessor.parse()
#define debug
#ifdef debug
print('The source is in debug mode')
#else
print('The source is not in debug mode')
#endif
import sys
if not __debug__:
sys.exit()
Documentation for sys.exit
.
One way you can do this is to hide all of the stuff in that module in another module that is imported conditionally.
. ├── main.py ├── _test.py ├── test.py
main.py:
import test
print dir(test)
test.py:
if __debug__:
from _test import *
_test.py:
a = 1
b = 2
Edit:
Just realized your comment in another answer where you said "I am hoping to avoid creating two different files for what amounts to an #ifdef". As shown in another answer, there really isn't any way to do what you want without an if statement.
I've upvoted the answer by samplebias, as I think that answer (plus edit) describes the closest you're going to get without using an if statement.
精彩评论