I tried to post this to cython-dev twice and got one awaiting
moderator approval and one silent no-op. So, I'll try it here.
It would be nice to have conditional compilation
directives that make multiple inclusion idempotent.
The usual guards in the C/C++ world would be:
#ifndef FOO_H
#define FOO_H
...
#endif
In Cython, I have been doing
DEF FOO_1 = 1
DEF FOO_2 = 1
IF FOO_1 == FOO_2:
DEF FOO_2 = 2
...
That seems kind of ugly, though. Beyond aesthetics,
it is probably nice in other contexts besides include
idempotency to test for a name before using it.
So, I propose a tiny addition to add a new compile-
time builtin called DEFINED() that just evaluates
to a boolean based on whether its string argument
exists in the compile-time environment.
This allows the above construct to be written both
more simply and more clearly:
IF not DEFINED("FOO"):
DEF FOO = 1
...
Name choice follows the principle of least surprise
since the lowercase cpp name has similar functionality,
just like the other conditional compilation features.
Here is a very simple patch that implements this,
attached as well.
diff -ruw Cython-0.9.8.orig/Cython/Compiler/Scanning.py Cython-0.9.8/Cython/Compiler/Scanning.py
--- Cython-0.9.8.orig/Cython/Compiler/Scanning.py 2008-06-11 14:25:34.000000000 -0400
+++ Cython-0.9.8/Cython/Compiler/Scanning.py 2008-07-17 16:39:27.691882798 -0400
@@ -186,6 +186,9 @@
else:
raise
+ def defined(self, name):
+ return name in self.entries
+
def initial_compile_time_env():
benv = CompileTimeScope?()
names = ('UNAME_SYSNAME', 'UNAME_NODENAME', 'UNAME_RELEASE',
@@ -201,6 +204,7 @@
for name in names:
benv.declare(name, getattr(builtin, name))
denv = CompileTimeScope?(benv)
+ denv.declare('DEFINED', denv.defined)
return denv
#------------------------------------------------------------------