6

so, here is my problem: I code in python, but I need to improve performance in some part of my code that are too slow. A good(and easy) solution seems to be using cython; I tried it and got good results. The issue is that I use assert statement in my python code. Before using cython, I could compile my python code with the -OO option, so that I can deliver a version not executing any assertion test, and still have the assert for debug. But the files that are compiled in cython seems to always execute the asserts. Is there some options that can be passed to cython compilation to remove(or not remove) the assertions?

robert
  • 33,242
  • 8
  • 53
  • 74
user521353
  • 61
  • 1
  • 2
  • dont' know...but what about make a simple programm to comment out all your python assertion in the file you want to use? – Ant Nov 26 '10 at 12:46
  • +1: I've found this problem myself. It's strange that something designed to make your code fast doesn't do the simplest optimisation of all. – Scott Griffiths Nov 26 '10 at 13:01

2 Answers2

10

Cython skips the assertions if you define the C preprocessor macro PYREX_WITHOUT_ASSERTIONS. So pass -DPYREX_WITHOUT_ASSERTIONS to the C compiler when compiling the generated C file. How to to this depends on your build process.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • Thank you for this fast answer. I'm using the Distutils method, so I'll have to check how to pass the macro to the compiler. – user521353 Nov 26 '10 at 14:50
  • 5
    CYTHON_WITHOUT_ASSERTIONS works just as well, though we do support PYREX_WITHOUT_ASSERTIONS for backwards compatibility. – robertwb Oct 06 '16 at 00:01
-1

Use pypreprocessor

Which can also be found on PYPI (Python Package Index) and be fetched using pip.

Here's the implementation:

from pypreprocessor import pypreprocessor

pypreprocessor.parse()

#define debug

#ifdef debug
...place assert to be removed here...
#endif

This essentially works the same as the standard C preprocessor conditional compilation does.

SideNote: This module is compatible with both python2x and python3k.

Disclaimer: I'm the author of pypreprocessor.

This will make the initial load take longer due to the added preprocessor stage but the outputted bytecode (.pyc) will be optimized.

Evan Plaice
  • 13,944
  • 6
  • 76
  • 94