Commit c4fa206b authored by William Stein's avatar William Stein

Initial version

parents
0.9.4.1
-------
Bug fixes:
- Fixed indentation problem in Pyrex.Distutils.build_ext.
[Oliver Grisel <ogrisel@nuxeo.com>]
0.9.4
-----
Improvements:
- All use of lvalue casts has been eliminated, for
compatibility with gcc4.
- PyMODINIT_FUNC now used to declare the module init function.
- Generated code should be compilable as either C or C++.
When compiling as C++, "extern C" is used where appropriate
to preserve linkage semantics. C++ functions still cannot
be called yet.
- An extension type can be made weak-referenceable by
giving it a C attribute of type object called __weakref__.
- Source files opened in universal newlines mode.
- Support for public extension type C attributes of type
long long and unsigned long long added (but not tested).
[Sam Rushing <sam@rushing.nightmare.com>]
- Distutils include directories now passed to Pyrex compiler.
[Konrad Hinsen <khinsen@cea.fr>]
- Integer constants with an "L" suffix are now allowed
and are converted to Python long integers.
[Rainer Deyke <rainerd@eldwood.com>]
- A broken .c file is no longer left behind if there are
compilation errors.
- Using the result of a Python indexing or attribute access
operation as a char * is no longer considered an error in
most cases, as the former behaviour proved to be more
annoying than helpful.
Bug fixes:
- Fixed problems with conversion from Python integers to
C unsigned longs. Now use PyInt_AsUnsignedLongMask and
PyInt_AsUnsignedLongLongMask instead of the PyLong_*
functions (which only work on Python longs).
[Wim Vree <wim@vree.be>]
- C unsigned ints now converted to/from Python longs intead
of Python ints to avoid overflow problems.
[Heiko Wundram <me+pyrex@modelnine.org>]
- Correct PyArg_ParseTuple format characters now used for
unsigned types. [Jeff Bowden <jlb@houseofdistraction.com>]
- Nonzero return value from a base class tp_traverse call
is handled.
- Taking sizeof an incomplete type caused a crash while
producing an error message. [Drew Perttula <dperttula@pdi.com>]
- If a module cimported itself, definitions of global variables
were generated twice. [Parzival Herzog <parzp@shaw.ca>]
- Distutils extension updated to handle changed signature of
swig_sources(). [David M. Cooke <cookedm@physics.mcmaster.ca>]
- Incorrect C code generated for a raw string containing a double
quote preceded by a backslash. [Thomas Drake <bistroy@mac.com>]
- Declaration of public C function with an exception value written
to generated .pxi file without the except clause.
[Robby Dermody <robbyd@u20.org>]
- __delitem__ method of an extension type with no __setitem__
did not get called. [Richard Boulton <richard@tartarus.org>]
- A spurious Py_INCREF was generated when a return statement
required a type test. [Jonathan Doda <jdoda@sympatico.ca>]
- Casting a value to a function pointer and then immediately
calling it generated a cast to a function instead of a cast
to a function pointer. [Simon Burton <simon@arrowtheory.com>]
- Py_TPFLAGS_HAVE_GC was not being set on an extension type that
inherited from an external extension type that used GC but did
not itself have any PyObject* attributes.
[Michael Hordijk <hoffbrinkle@hotmail.com>]
- A return statement inside a for statement leaked a reference
to the loop's iterator.
[Jürgen Kartnaller <j.kartnaller@robotech.at>]
- Full module name now appears in __module__ attribute of classes
and extension types, provided a correct dotted name is used
for the .pyx file. [Giovanni Bajo <rasky@develer.com>]
- Public extension type with no C attributes produced an
invalid .pxi file. [Simon Burton <simon@arrowtheory.com>]
- Using a dict constructor as the second operand of a boolean
expression crashed the Pyrex compiler.
[Stefan Behnel <behnel_ml@gkec.informatik.tu-darmstadt.de>]
- A C declaration list ending with a comma resulted in invalid
C code being generated. [Alex Coventry <alex_c@mit.edu>]
- A raw string containing two consecutive backslashes produced
incorrect C code. [Helmut Jarausch <jarausch@igpm.rwth-aachen.de>]
- An error is reported if you attempt to declare a special
method of an extension type using 'cdef' instead of 'def'.
[Sam Rushing <srushing@ironport.com>]
0.9.3
-----
Enhancements:
- Types defined with a ctypedef in a 'cdef extern from' block
are now referred to by the typedef name in generated C code,
so it is no longer necessary to match the type in the C
header file exactly.
- Conversion to/from unsigned long now done with
PyLong_AsUnsignedLong and PyLong_FromUnsignedLong.
[Dug Song <dugsong@monkey.org>]
- A struct, union or enum definition in a 'cdef extern from'
block may now be left empty (using 'pass'). This can be useful
if you need to declare a variable of that type, but don't need
to refer to any of its members.
- More flexible about ordering of qualifiers such as 'long' and
'unsigned'.
["John (J5) Palmieri" <johnp@redhat.com>]
Bug fixes:
- Non-interned string literals used in a Python class
definition did not work.
[Atsuo Ishimoto <ishimoto@gembook.org>]
[Andreas Kostyrka <andreas@kostyrka.org>]
- Return types of the buffer interface functions for extension
types have been corrected.
[Dug Song <dugsong@monkey.org>]
- Added 'static' to declarations of string literals.
[Phil Frost <indigo@bitglue.com>]
- Float literals are now copied directly to the C code as written,
to avoid problems with loss of precision.
[Mario Pernici <Mario.Pernici@mi.infn.it>]
- Inheriting from an extension type with C methods defined in
another Pyrex module did not work.
[Itamar Shtull-Trauring <itamar@itamarst.org>]
0.9.2.1
-------
Bug fixes:
- Corrected an import statement setup.py, and made it
check for a unix platform in a more reliable way.
0.9.2
-----
Enhancements:
- Names of Python global variables and attributes are now
interned, and PyObject_GetAttr/SetAttr are used instead
of PyObject_GetAttrString/SetAttrString. String literals
which resemble Python identifiers are also interned.
- String literals are now converted to Python objects only
once instead of every time they are used.
- NUL characters are now allowed in Python string literals.
- Added some missing error checking code to the beginning
of module init functions. It's unlikely the operations
involved would ever fail, but you never know.
Bug fixes:
- Corrected some problems introduced by moving the Plex
package.
0.9.1.1
-------
Bug fixes:
- Corrected a problem in the setup.py (pyrexc script incorrectly
named).
- Updated the distutils extension to match changes in the
Pyrex compiler calling interface.
- Doing 'make clean' in Demos/callback was removing a little too
much (that's why cheesefinder.c kept disappearing).
0.9.1
-----
Enhancements:
- A C method can now call an inherited C method by the usual
Python technique.
[Jiba <jiba@tuxfamily.org>]
- The __modname__ of a Python class is now set correctly.
[Paul Prescod <paul@prescod.net>]
- A MANIFEST.in file has been added to the distribution to
facilitate building rpms.
[contributed by Konrad Hinsen <hinsen@cnrs-orleans.fr>]
Bug fixes:
- Conditional code now generated to allow for the renaming of LONG_LONG
to PY_LONG_LONG that occurred between Python 2.2 and 2.3.
- Header files referenced in cimported modules were not being included.
[Tom Popovich <tompopovich@aol.com>]
- References to C functions and variables in a cimported module were
not being recognised if made from within a local scope.
[Tom Popovich <tompopovich@aol.com>]
- Spurious declarations in code generated for a "finally" block.
[Brandon Long <blong@fiction.net>]
- Attempting to return a value from a __contains__ method didn't work.
[Andreas Kostyrka <andreas@mtg.co.at>]
- Incorrect code generated for an extension type with C methods
inheriting from a base type with no C methods.
[Robin Becker <robin@reportlab.com>]
- Failure to report an error if a C method was defined in the
implementation part of an extension type that was not declared
in the corresponding definition part. Documentation also updated
to explain that this is necessary.
[Jiba <jiba@tuxfamily.org>]
- Made it an error to forward-declare an extension type with
a different base class specification from its subsequent
definition.
[Jiba <jiba@tuxfamily.org>]
- C attributes of an extension type were not being propagated
through more than one level of inheritance.
[Jiba <jiba@tuxfamily.org>]
- If a garbage collection occurred early enough in the __new__
method of an extension type with Python-valued C attributes,
a crash could occur in its tp_traverse function.
[reported by Jiba <jiba@tuxfamily.org>]
[fix suggested by Paul Prescod <paul@prescod.net>]
- An empty vtable struct is no longer generated for extension
types with no C methods.
[Robin Becker <robin@reportlab.com>]
- Memory was leaked in the sq_item function of an extension
type with a __getitem__ method.
[Atsuo Ishimoto <ishimoto@gembook.org>]
- Code generated to work around a bug in some versions of Python
2.2 which fails to initialise the tp_free slot correctly in
some circumstances.
[Matthias Baas <baas@ira.uka.de>]
- Compiler crash when defining an extension type with a base
class specified by a dotted name.
[Alain Pointdexter <alainpoint@yahoo.fr>]
- Referencing an extension type defined in a cimported module
at run time did not work correctly.
[Alain Pointdexter <alainpoint@yahoo.fr>]
- Incorrect object struct code generated for an extension type
whose base class was defined in a .pxd file.
[Alain Pointdexter <alainpoint@yahoo.fr>]
- Redeclaring a type that wasn't previously an extension type
as an extension type caused a compiler crash.
[Scott Robinson <scott@tranzoa.com>]
- Incorrect code was generated for return statements in a
special method with no return value.
[Gary Bishop <gb@cs.unc.edu>]
- Single-line def statement did not work.
[Francois Pinard <pinard@iro.umontreal.ca>]
Modifications:
- Only the last pathname component of the .pyx file is reported in
backtraces now.
[Bryan Weingarten <bryan.weingarten@pobox.com>]
- Documentation corrected to remove the erroneous statement that
extension classes can have a __del__ method.
[Bryan Weingarten <bryan.weingarten@pobox.com>]
- Note added to documentation explaining that it is not possible
for an extension type's __new__ method to explicitly call the
inherited __new__ method.
- The version of Plex included with Pyrex is now installed
as a subpackage of the Pyrex package, rather than as a
top-level package, so as not to interfere with any other
version of Plex the user may have installed.
0.9
---
New features:
- Extension types can have properties. See the new "Properties"
section in the "Extension Types" page.
- An extension type can inherit from a builtin type or another
extension type. See "Subclassing" in the "Extension Types" page.
- Extension types can have C methods, which can be overridden
in derived extension types. See "C Methods" in the "Extension Types"
page.
Enhancements:
- Conversion is now performed between C long longs and Python
long integers without chopping to the size of a C long.
Also the Python PY_LONG_LONG type is now used for long longs
for greater portability.
Bug fixes:
- Names were sometimes being generated that were insufficiently
unique in the presence of cimported declarations.
- Changed the way the included filename table is declared from
char *[] to char **, to stop MSVC from complaining about it
having an unknown size.
[Alexander A Naanou <alex_nanou@pochta.ru>]
- Second argument of assert statement was not being coerced
to a Python value.
[Francois Pinard http://www.iro.umontreal.ca/~pinard]
- Return statement without value wasn't accepted in some
extension type special methods when it should have been.
[Francois Pinard http://www.iro.umontreal.ca/~pinard]
- Attempting to call a non-function C value crashed the
compiler.
[John J Lee <jjl@pobox.com>]
- Functions declared as "except *" were not returning exceptions.
[John J Lee <jjl@pobox.com>]
- A syntax warning from Plex about assignment to None has
been eliminated.
[Gordon Williams <g_will@cyberus.ca>]
- Public function declaration with empty argument list was
producing (void) in .pxi file.
[Michael P. Dubner <dubnerm@mindless.com>]
- Incorrect error signalling code was being generated in the
__hash__ special method of an extension type.
0.8.1
-----
Bug fixes:
- Names of structs, unions and enums in external header
files were getting mangled when they shouldn't have been.
[Norman Shelley <Norman.Shelley@motorola.com>]
- Modified distutils extension so that it will stop before
compiling the C file if the Pyrex compiler reports errors.
[John J Lee <jjl@pobox.com>]
0.8
---
New features:
- INCOMPATIBLE CHANGE: The type object of an external extension
type is now imported at run time using the Python import
mechanism. To make this possible, an 'extern' extension type
declaration must DECLARE THE MODULE from which the extension
type originates. See the new version of the "Extension Types"
documentation for details.
This change was made to eliminate the need for Pyrex to be
told the C name of the type object, or for the Pyrex module
to be linked against the object code providing the type object.
You will have to update any existing external extension type
declarations that you are using. I'm sorry about that, but it
was too hard to support both the old and new ways.
- Compile-time importing: A Pyrex module can now import declarations
from another Pyrex module using the new 'cimport' statement. See
the new section on "Sharing Declarations Between Pyrex Modules" in
the documentation.
Minor improvements:
- An error is reported if you declare a struct, union or
extension type using 'cdef' in one place and 'ctypedef'
in another.
- Struct, union and extension types can only be forward-
declared using 'cdef', not 'ctypedef' (otherwise invalid
C code would be generated).
- The 'global' statement can be used at the module level to
declare that a name is a module-level name rather than a
builtin. This can be used to access module attributes such
as __name__ that would otherwise be assumed to be builtins.
[Pat Maupin <pmaupin@speakeasy.net>]
- The 'assert' statement now accepts a second argument.
[Francois Pinard <pinard@iro.umontreal.ca>]
Bug fixes:
- When using Python 2.3, "True" or "False" could sometimes
turn up in generated code instead of "1" or "0".
[Adam Hixson <chixson@ou.edu>]
- Function return value not always converted to or from a
Python object when it should have been.
- Certain kinds of error in a function call expression
could crash the compiler.
["Edward C. Jones" <edcjones@erols.com>]
- Fixed memory leak in functions with * or ** args.
[Alexander A Naanou <alex_nanou@pochtamt.ru>]
0.7.1
-----
Bug fixes:
- Calling a function declared as returning an extension
type could crash the compiler.
- A function call with type errors in the argument list
could crash the compiler.
- An 'else' clause on a for-from statement could crash
the compiler.
- Incorrect casting code was generated when a generic
object argument of a special method was declared as
being of an extension type.
[Phillip J. Eby <pje@telecommunity.com>]
- A blank line that couldn't be interpreted wholly as
a valid indentation sequence caused a syntax error.
In particular, a formfeed character on an otherwise
blank line wasn't accepted.
[Francois Pinard <pinard@iro.umontreal.ca>]
- Parallel assignments were incorrectly optimised.
- A bare tuple constructor with an extra comma at the
end of a line caused a syntax error.
0.7
---
New features:
- Attributes of extension types can be exposed to Python
code, either read/write or read-only.
- Different internal and external names can be specified
for C entities.
- None is a compile-time constant, and more efficient code
is generated to reference it.
- Command line options for specifying directories to
search for include files.
Enhancements:
- More efficient code is generated for access to Python
valued C attributes of extension types.
- Cosmetic code improvement: Less casting back and forth
between extension types and PyObject * when referencing
C members of the object struct.
- C arguments and variables declared as an extension type
can take the value None.
- Form feed characters are accepted as whitespace.
- Function names in tracebacks are qualified with
module name and class name.
Bug fixes:
- A sufficiently complex expression in a boolean context
could cause code to be generated twice for the same
subexpression.
- Incorrect casting code was generated when passing an
extension type to a function expecting a generic Python
object.
- Executable statements are now disallowed inside a
cdef class block (previously they silently caused
crazy C code to be generated).
- Tracebacks should now report the correct filename for
functions defined in files included with the 'include'
statement.
- The documentation incorrectly claimed that an extension
type can't have a __del__ method. In fact, it can, and
it behaves as expected.
0.6.1
-----
Bug fixes:
- Fixed broken distutils extension.
0.6
---
New features:
- Command line options for reporting version number,
requesting a listing file and specifying the name of
the generated C file.
- An 'include' statement allows inclusion of declarations
from other Pyrex source files.
- If there are any public declarations, a Pyrex include
file is generated (as well as a .h file) containing
declarations for them.
- Extension types can be declared public, so their C
attributes are visible to other Pyrex and C code.
- Try-except statements can now have an 'else' clause.
[Francois Pinard <pinard@iro.umontreal.ca>]
- Multiple simple statements can be placed on one line
separated by semicolons.
- A suite consisting of a simple statement list can now
be placed on the same line after the colon in most
cases.
[Francois Pinard <pinard@iro.umontreal.ca>]
- The automatic coercion of a C string to a C char has
been removed (it proved to be too error-prone).
Instead, there is a new form of literal for C
character constants: c'X'
- The __get__ special method (used by descriptor objects)
now allows for the possibility of the 2nd or 3rd
arguments being NULL. Also the __set__ method has been
split into two methods, __set__ and __delete__.
[Phillip J. Eby <pje@telecommunity.com>]
Bug fixes:
- Values unpacked into a non-Python destination variable
were not being converted before assignment.
[Gareth Watts <gareth@omnipotent.net>]
- Hex constants greater than 0x7fffffff caused compiler
to crash. [Gareth Watts <gareth@omnipotent.net>]
- Type slots are no longer statically initialised with
extern function pointers, to avoid problems with
some compilers. The hack in the distutils extension
to work around this by compiling as C++ has been
disabled. [Phillip J. Eby <pje@telecommunity.com>]
- Fixed several more instances of the error-reporting
routine being called with arguments in the wrong
order. Hoping I've *finally* got all of them now...
- Nested for-from loops used the same control variable.
[Sebastien de Menten <sdementen@hotmail.com>]
- Fixed some other error message related bugs.
[Francois Pinard <pinard@iro.umontreal.ca>]
- Assigning to slice didn't work.
[Francois Pinard <pinard@iro.umontreal.ca>]
- Temp variables were being declared as extension
types and then being assigned PyObject *'s. All
Python temp vars are now declared as PyObject *.
[Francois Pinard <pinard@iro.umontreal.ca>]
0.5
---
Bug fixes:
- Algorithm for allocating temp variables redesigned
to fix various errors concerning temp
variable re-use.
[Mark Rowe <bdash@gmx.net>]
- Memory leak occured sometimes when an implicit
type test was applied to the result of an
expression.
[christoph.wiedemann@daimlerchrysler.com]
- __set__ method of extension types had wrong
signature.
[Josh Littlefield <joshl@cisco.com>]
0.4.6
-----
Bug fixes:
- Indexing multi-dimensional C arrays didn't
work.
[Gary Dietachmayer <gary.dietachmayer@dsto.defence.gov.au>]
0.4.5
-----
New features:
- There is now a 'public' declaration for
making Pyrex-defined variables and functions
available to external C code. A .h file is
also generated if there are any public
declarations.
Enhancements:
- Defining __len__/__getitem__ methods in an
extension class fills sq_length/sq_item slots
as well as mp_length/mp_subscript.
[Matthias Baas <baas@ira.uka.de>]
- The Distutils extension now allows .c files
to be incorporated along with .pyx files.
[Modification to Distutils extension contributed
by Darrell Gallion <dgallion1@yahoo.com>.]
Bug fixes:
- Float literals without a decimal point
work again now.
[Mike Rovner <mike@bindkey.com>]
[Peter Lepage <gpl@mail.lns.cornell.edu>]
- Compiler crashed if exception value didn't
match function return type.
[Michael JasonSmith <mpj17@smtphost.canterbury.ac.nz>]
- The setup.py file should now install the
Lexicon.pickle file in the right place.
[Patch supplied by David M. Cooke
<cookedm@arbutus.physics.mcmaster.ca>]
- Compiler crashed when compiling a C function that
returned an extension type.
[David M. Cooke
<cookedm@arbutus.physics.mcmaster.ca>]
- Anonymous enum types did not have C code
suppressed inside an extern-from block.
[Matthew Mueller <donut@azstarnet.com>]
0.4.4
-----
Enhancements:
- Tracebacks now extend into Pyrex function
calls and show line numbers in the Pyrex
source file.
- Syntax for float literals made more lenient
(no longer requires digits both before and
after the point).
[Peter Lepage <gpl@mail.lns.cornell.edu>]
- Method calls can be made on string literals
(e.g. ",".join(x)).
[pedro_rodriguez@club-internet.fr]
Bug fixes:
- Incorrect refcount code generated when a
Python function needing argument type tests
had local Python variables.
[Matthias Baas <baas@ira.uka.de>]
- 'self' parameter of __getitem__ method of
extension type had wrong implicit type.
[Peter Lepage <gpl@mail.lns.cornell.edu>]
- Repaired breakage introduced by trying to
allow an empty parameter list to be written
as (void). No longer attempting to allow
this (too hard to parse correctly).
[Peter Lepage <gpl@mail.lns.cornell.edu>]
- Found bug in Plex 1.1.2 which was the *real*
cause of the two-newlines-in-a-row problem.
Removed the Opt(Eol)+Str("\n") hacks in
the scanner which were working around this
before.
[pedro_rodriguez@club-internet.fr]
- __call__ special method of extension types
had wrong signature.
[Peter Lepage <gpl@mail.lns.cornell.edu>]
0.4.3
-----
New language features:
- For-from loop for iterating over integer
ranges, using pure C loop where possible.
Enhancements:
- sizeof() can now be applied to types as
well as variables.
- Improved handling of forward-declared
extension types.
Bug fixes:
- Two newlines in a row in a triple quoted
string caused a parse error on some
platforms.
[Matthias Baas <baas@ira.uka.de>]
- Fixed problem with break and continue in
the else-clause of a loop.
0.4.2
-----
New language features:
- C functions can be declared as having an
exception return value, which is checked
whenever the function is called. If an
exception is detected inside a C function
for which no exception value is declared,
a warning message is printed and the
exception is cleared.
- Cascaded assignments (i.e. a = b = c
are now supported.
- Anonymous enum declarations are allowed,
for when you just want to declare constants.
- The C types "long long" and "long double"
are now understood. Also, "int" is optional
after "short" or "long".
Enhancements:
- A * argument in a function call can now be
any sequence, not just a tuple.
- A C char* or char[] will be turned into
a char by taking its first character if
used in a context where a char is required,
thus allowing a string literal to be used as
a char literal.
- C string * C int or vice versa is now
interpreted as Python string replication.
- Function arguments are checked for void or
incomplete type.
Bug fixes:
- Non-external extension types show up in the
module dict once more (this got broken in
0.4.1).
- A spurious decref has been removed from the
runtime support code for the "import" statement.
Hopefully this will prevent the crashes some
people have been experiencing when importing
builtin modules.
[Mathew Yeates <mathew@comma.jpl.nasa.gov>]
0.4.1
-----
New language features:
- "ctypedef struct/union/enum/class" statements
added, for use in extern-from blocks when a
header file uses a ctypedef to declare a
tagless struct, union or enum type.
- "pass" allowed in an extern-from block.
- "cdef extern from *" for when you don't want
to specify an include file name.
- Argument names may be omitted in function
signatures when they're not needed.
- New reserved word NULL for the null C pointer.
Compiler enhancements:
- Lexicon is now picked in binary format, so
startup should be much faster on slower
machines.
- If Pyrex decides to rebuild the lexicon and
then finds that it can't write a pickle file,
it now prints a warning and carries on
instead of crashing.
- Chat about hash codes and lexicon pickling
now turned off by default except when creating
a new lexicon (which ought never happen now
unless you change the scanner).
Bug fixes:
- Modified the runtime support code for "import"
statements, hopefully fixing problem with using
a Pyrex module in conjunction with py2exe.
- DL_EXPORT now used in both the prototype and
definition of the module init function.
- Exception state is now saved and restored around
calls to an extension type __dealloc__ method,
to avoid screwing up if the object is deallocated
while an exception is being propagated.
- Making an attribute reference to a method of
an extension type caused a compiler crash.
- Doc string in new-style class definition
caused a run-time error.
- Insufficient parentheses were put around C type
casts.
- Constructors for extension types are now read-only
C global variables instead of entries in the
module dict. This change was needed to prevent
Numeric from blowing up due to touching its
typeobject before import_numeric() could be called.
0.4
---
New features:
- "cdef extern from" statement allows inclusion
of C header files to be specified, solving
a number of problems including:
- Clashes between Pyrex and C declarations,
due to "const" and other reasons
- Windows-specific features required in
function declarations
- Helping deal with types such as "size_t"
- Helping deal with functions defined as
macros
- Access to internals of pre-existing extension
types is now possible by placing an extension
type declaration inside a "cdef extern from"
block.
Bug fixes:
- Error not reported properly when passing
wrong number of args to certain special
methods of extension types.
[Mitch Chapman <mitchchapman@earthlink.net>]
- Compile-time crash when defining an extension
type with a __hash__ method.
Minor enhancements:
- Hashing of the scanner source file made more
platform-independent, making spurious regeneration
of the pickle less likely.
0.3.4
-----
Bug fixes:
- Runtime crash when using * or ** args in
a method of an extension type fixed.
[Matthew Mueller <donut@azstarnet.com>]
- Compiler crash when using default argument
values in a method of a Python class.
[Mike Rovner <mike@bindkey.com>]
Enhancements:
- Type slots filled with functions from outside
the extension module are now initialised dynamically,
which should eliminate at least some of the
"initialiser is not constant" problems experienced
on Windows.
[Marek Baczek <imbaczek@poczta.fm>]
- On Windows, __declspec(dllexport) is now used for
the module init func declaration (or should be --
I haven't tested this).
[Marek Baczek <imbaczek@poczta.fm>]
- The compiler shouldn't attempt to rewrite the
Lexicon.pickle file unless the source has been
changed (hashing is used now instead of comparing
timestamps). So there should be no problem any more
with installing Pyrex read-only.
[fawcett@uwindsor.ca]
0.3.3
-----
Bug fixes:
* A void * can be assigned from any other
pointer type.
[piers@cs.su.oz.au]
* File names in error messages no longer
quoted (this was apparently confusing some
editors).
[donut@azstarnet.com]
* Reference to a struct member which is an
array is coerced to a pointer.
[donut@azstarnet.com]
* Default argument values did not work
in methods of an extension type.
[donut@azstarnet.com]
* Single or double quote characters in a
triple-quoted string didn't work.
[donut@azstarnet.com]
* Using *args in a function definition
sometimes caused a crash at runtime.
[donut@azstarnet.com]
* A hack is included which tries to make
functions in Python.h which use 'const'
accessible from Pyrex. But it doesn't
work on all platforms. Thinking about a
better solution.
New features:
* Comment containing Pyrex version number
and date/time at top of generated C file.
[baas@ira.uka.de]
0.3.2
-----
Bug fixes:
* The & operator works again.
[matthias.oberlaender@daimlerchrysler.com]
[baas@ira.uka.de]
* The & operator had incorrect precedence.
* "SystemError: 'finally' pops bad exception"
under some circumstances when raising an
exception. [baas@ira.uka.de]
* Calling a Python function sometimes leaked
a reference.
* Crash under some circumstances when casting
a Python object reference to a C pointer type.
[mpj17@cosc.canterbury.ac.nz]
* Crash when redeclaring a function.
[baas@ira.uka.de]
* Crash when using a string constant inside
a Python class definition.
[mike@bindkey.com]
* 2-element slice indexing expressions.
[mike@bindkey.com]
* Crash when encountering mixed tabs and
spaces.
[mike@bindkey.com]
New features:
* A wider variety of constant expressions is
now accepted for enum values, array
dimensions, etc.
[mike@bindkey.com]
0.3.1
-----
New features:
* More special methods for extension types:
__delitem__, __delslice__, __getattr__,
__setattr__, __delattr__
* Module-level variable of a Python object type
declared with 'cdef' is private to the module, and
held in a C variable instead of the module dict.
* External C functions with variable argument lists
can be declared and called.
* Pyrex-defined Python functions can have default
argument values and * and ** arguments, and can be
called with keyword arguments.
* Pointer-to-function types can be declared.
* Pyrex now supports a declaration syntax that
C doesn't! Example:
cdef (int (*)()) foo() # function returning a function ptr
* There is now a ctypedef statement.
* Extension types can now be forward-declared.
* All permutations of (non-Unicode) string literals
and escape codes should work now.
* Hex and octal integer literals.
* Imaginary number literals.
* Docstrings are now supported.
Bug fixes:
* Type tests are performed when using a Python object
in a context requiring a particular extension type.
* Module-level variable holding the type object
of an extension type had incorrect type.
0.3
---
New features:
* Extension types! Yay!
0.2.2
-----
Bug fixes:
* Fixed error message generation again after a previous
bug was accidentally re-indroduced.
* Removed the declaration of isspace() from the code
generated for print statement support (it's not needed
and was conflicting with the system-supplied one on
some platforms).
0.2
---
New features:
* Executable statements are now allowed at the
top level of a module.
* Python class definitions are now supported, with
the following limitations:
- Class definitions are only allowed at the top
level of a module, not inside a control structure
or function or another class definition.
- Assigning a Pyrex-defined Python function to a
class attribute outside of the class definition
will not create a method (because it's not an
interpreted Python function and therefore
won't trigger the bound-method creation magic).
- The __metaclass__ mechanism and the creation of
new-style classes is not (yet) supported.
* Casting between Python and non-Python types is
better supported.
Bug fixes:
* Fixed bug preventing for-loops from working.
0.1.1
-----
* I've discovered a flaw in my algorithm for releasing
temp variables. Fixing this properly will require some
extensive reworking; I've put in a hack in the meantime
which should work at the cost of using more temp variables
than are strictly necessary.
* Fixed bug preventing access to builtin names from
working. This should also have fixed the import
statement, but I haven't tested it.
* Fixed some errors in __Pyx_GetExcValue.
* Fixed bug causing boolean expressions to malfunction
sometimes.
The original Pyrex code as of 2006-04 is licensed under the following
license: "Copyright stuff: Pyrex is free of restrictions. You may use,
redistribute, modify and distribute modified versions."
------------------
Cython, which derives from Pyrex, is licensed under the Python
Software Foundation License. More precisely, all modifications
made to go from Pyrex to Cython are so licensed.
all:
python Setup.py build_ext --inplace
test: all
python run_primes.py 20
python run_numeric_demo.py
python run_spam.py
cd callback; $(MAKE) test
clean:
@echo Cleaning Demos
@rm -f *.c *.o *.so *~ core
@rm -rf build
@cd callback; $(MAKE) clean
@cd embed; $(MAKE) clean
PYHOME = $(HOME)/pkg/python/version
PYINCLUDE = \
-I$(PYHOME)/include/python2.2 \
-I$(PYHOME)/$(ARCH)/include/python2.2
%.c: %.pyx
../bin/pyrexc $<
%.o: %.c
gcc -c -fPIC $(PYINCLUDE) $<
%.so: %.o
gcc -shared $< -lm -o $@
all: primes.so spam.so numeric_demo.so
clean:
@echo Cleaning Demos
@rm -f *.c *.o *.so *~ core core.*
@cd callback; $(MAKE) clean
@cd embed; $(MAKE) clean
from distutils.core import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name = 'Demos',
ext_modules=[
Extension("primes", ["primes.pyx"]),
Extension("spam", ["spam.pyx"]),
Extension("numeric_demo", ["numeric_demo.pyx"]),
],
cmdclass = {'build_ext': build_ext}
)
all:
python Setup.py build_ext --inplace
test: all
python run_cheese.py
clean:
@echo Cleaning Demos/callback
@rm -f cheese.c *.o *.so *~ core
@rm -rf build
PYHOME = $(HOME)/pkg/python/version
PYINCLUDE = \
-I$(PYHOME)/include/python2.2 \
-I$(PYHOME)/$(ARCH)/include/python2.2
%.c: %.pyx
../../bin/pyrexc $<
%.o: %.c
gcc -c -fPIC $(PYINCLUDE) $<
%.so: %.o
gcc -shared $< -lm -o $@
all: cheese.so
clean:
@echo Cleaning Demos/callback
@rm -f *.c *.o *.so *~ core core.*
This example demonstrates how you can wrap a C API that has a callback interface, so that you can pass Python functions to it as callbacks. The files cheesefinder.h and cheesefinder.c represent the C library to be wrapped. The file cheese.pyx is the Pyrex module which wraps it. The file run_cheese.py demonstrates how to call the wrapper.
\ No newline at end of file
from distutils.core import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
name = 'callback',
ext_modules=[
Extension("cheese", ["cheese.pyx", "cheesefinder.c"]),
],
cmdclass = {'build_ext': build_ext}
)
#
# Pyrex wrapper for the cheesefinder API
#
cdef extern from "cheesefinder.h":
ctypedef void (*cheesefunc)(char *name, void *user_data)
void find_cheeses(cheesefunc user_func, void *user_data)
def find(f):
find_cheeses(callback, <void*>f)
cdef void callback(char *name, void *f):
(<object>f)(name)
/*
* An example of a C API that provides a callback mechanism.
*/
#include "cheesefinder.h"
static char *cheeses[] = {
"cheddar",
"camembert",
"that runny one",
0
};
void find_cheeses(cheesefunc user_func, void *user_data) {
char **p = cheeses;
while (*p) {
user_func(*p, user_data);
++p;
}
}
typedef void (*cheesefunc)(char *name, void *user_data);void find_cheeses(cheesefunc user_func, void *user_data);
\ No newline at end of file
import cheese
def report_cheese(name):
print "Found cheese:", name
cheese.find(report_cheese)
PYVERSION = 2.2
PYHOME = $(HOME)/pkg/python/$(PYVERSION)
PYARCH = $(PYHOME)/$(ARCH)
PYINCLUDE = \
-I$(PYHOME)/include/python$(PYVERSION) \
-I$(PYARCH)/include/python$(PYVERSION)
PYLIB = -L$(PYARCH)/lib/python$(PYVERSION)/config \
-lpython$(PYVERSION) \
-ldl -lpthread -lutil -lm
%.c: %.pyx
../../bin/pyrexc $<
%.o: %.c
gcc -c -fPIC $(PYINCLUDE) $<
#%.so: %.o
# gcc -shared $< -lm -o $@
all: main
main: main.o embedded.o
gcc main.o embedded.o $(PYLIB) -o main
clean:
@echo Cleaning Demos/embed
@rm -f *~ *.o *.so core core.* embedded.h embedded.c main
embedded.h: embedded.c
main.o: embedded.h
# Makefile for Microsoft C Compiler, building a DLL
PYVERSION = 2.2
PYHOME = \Python$(PYVERSION:.=)
PYINCLUDE = -I$(PYHOME)\include
PYLIB = /LIBPATH:$(PYHOME)\libs
CFLAGS = $(PYINCLUDE) /Ox /W3 /GX -nologo
.SUFFIXES: .exe .dll .obj .c .cpp .pyx
.pyx.c:
$(PYHOME)\Python.exe ../../pyrexc.py $<
all: main.exe
clean:
del /Q/F *.obj embedded.h embedded.c main.exe embedded.dll embedded.lib embedded.exp
# When linking the DLL we must explicitly list all of the exports
# There doesn't seem to be an easy way to get DL_EXPORT to have the correct definition
# to do the export for us without breaking the importing of symbols from the core
# python library.
embedded.dll: embedded.obj
link /nologo /DLL /INCREMENTAL:NO $(PYLIB) $** /IMPLIB:$*.lib /DEF:<< /OUT:$*.dll
EXPORTS initembedded
EXPORTS spam
<<
main.exe: main.obj embedded.lib
link /nologo $** $(PYLIB) /OUT:main.exe
embedded.h: embedded.c
main.obj: embedded.h
embedded.obj: embedded.c
$(CC) /MD $(CFLAGS) -c $**
embedded.lib: embedded.dll
# Makefile for Microsoft compiler statically linking PYVERSION = 2.2 PYHOME = \Python$(PYVERSION:.=) PYINCLUDE = -I$(PYHOME)\include PYLIB = /LIBPATH:$(PYHOME)\libs python22.lib CFLAGS = $(PYINCLUDE) /Ox /W3 /GX -nologo .SUFFIXES: .exe .dll .obj .c .cpp .pyx .pyx.c: $(PYHOME)\Python.exe ../../pyrexc.py $< all: main.exe clean: -del /Q/F *.obj embedded.h embedded.c main.exe main.exe: main.obj embedded.obj link /nologo $** $(PYLIB) /OUT:main.exe embedded.h: embedded.c main.obj: embedded.h
\ No newline at end of file
PYVERSION = 2.2
PYHOME = $(HOME)/pkg/python/$(PYVERSION)
PYARCH = $(PYHOME)/$(ARCH)
PYINCLUDE = \
-I$(PYHOME)/include/python$(PYVERSION) \
-I$(PYARCH)/include/python$(PYVERSION)
PYLIB = -L$(PYARCH)/lib/python$(PYVERSION)/config \
-lpython$(PYVERSION) \
-ldl -lpthread -lutil -lm
%.c: %.pyx
../../bin/pyrexc $<
%.o: %.c
gcc -c -fPIC $(PYINCLUDE) $<
#%.so: %.o
# gcc -shared $< -lm -o $@
all: main
main: main.o embedded.o
gcc main.o embedded.o $(PYLIB) -o main
clean:
@echo Cleaning Demos/embed
@rm -f *~ *.o *.so core core.* embedded.h embedded.c main
embedded.h: embedded.c
main.o: embedded.h
This example demonstrates how Pyrex-generated code can be called directly from a main program written in C. In this example, the module's initialisation function (called "initembedded", since the module is called "embedded") is called explicitly. This is necessary because the module is not being imported using the normal Python import mechanism. The Windows makefiles were contributed by Duncan Booth <Duncan.Booth@SuttonCourtenay.org.uk>.
\ No newline at end of file
cdef public void spam():
praise()
def praise():
print "Spam, glorious spam!"
#include "Python.h"
#include "embedded.h"
int main(int argc, char *argv) {
Py_Initialize();
initembedded();
spam();
Py_Finalize();
}
#
# This example demonstrates how to access the internals
# of a Numeric array object.
#
cdef extern from "Numeric/arrayobject.h":
struct PyArray_Descr:
int type_num, elsize
char type
ctypedef class Numeric.ArrayType [object PyArrayObject]:
cdef char *data
cdef int nd
cdef int *dimensions, *strides
cdef object base
cdef PyArray_Descr *descr
cdef int flags
def print_2d_array(ArrayType a):
print "Type:", chr(a.descr.type)
if chr(a.descr.type) <> "f":
raise TypeError("Float array required")
if a.nd <> 2:
raise ValueError("2 dimensional array required")
cdef int nrows, ncols
cdef float *elems, x
nrows = a.dimensions[0]
ncols = a.dimensions[1]
elems = <float *>a.data
hyphen = "-"
divider = ("+" + 10 * hyphen) * ncols + "+"
print divider
for row in range(nrows):
for col in range(ncols):
x = elems[row * ncols + col]
print "| %8f" % x,
print "|"
print divider
def primes(int kmax):
cdef int n, k, i
cdef int p[1000]
result = []
if kmax > 1000:
kmax = 1000
k = 0
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] <> 0:
i = i + 1
if i == k:
p[k] = n
k = k + 1
result.append(n)
n = n + 1
return result
def primes(kmax):
p = []
k = 0
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] <> 0:
i = i + 1
if i == k:
p.append(n)
k = k + 1
n = n + 1
return p
import Numeric
import numeric_demo
a = Numeric.array([[1.0, 3.5, 8.4], [2.3, 6.6, 4.1]], "f")
numeric_demo.print_2d_array(a)
import sys
from primes import primes
if len(sys.argv) >= 2:
n = int(sys.argv[1])
else:
n = 1000
print primes(n)
from spam import Spam
s = Spam()
print "Created:", s
s.set_amount(42)
print "Amount =", s.get_amount()
s.describe()
s = None
#
# Example of an extension type.
#
cdef class Spam:
cdef int amount
def __new__(self):
self.amount = 0
def __dealloc__(self):
print self.amount, "tons of spam is history."
def get_amount(self):
return self.amount
def set_amount(self, new_amount):
self.amount = new_amount
def describe(self):
print self.amount, "tons of spam!"
<!doctype html public "-//w3c//dtd html 4.0 transitional//en"><html><head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="GENERATOR" content="Mozilla/4.51 (Macintosh; I; PPC) [Netscape]"> <title>About Pyrex</title></head><body> <center><h1> <hr width="100%">Pyrex</h1></center> <center><i><font size=+1>A language for writing Python extension modules</font></i><hr width="100%"></center> <h2> What is Pyrex all about?</h2> Pyrex is a language specially designed for writing Python extension modules. It's designed to bridge the gap between the nice, high-level, easy-to-use world of Python and the messy, low-level world of C.<p>You may be wondering why anyone would want a special language for this. Python is really easy to extend using C or C++, isn't it? Why not just write your extension modules in one of those languages?<p>Well, if you've ever written an extension module for Python, you'll know that things are not as easy as all that. First of all, there is a fair bit of boilerplate code to write before you can even get off the ground. Then you're faced with the problem of converting between Python and C data types. For the basic types such as numbers and strings this is not too bad, but anything more elaborate and you're into picking Python objects apart using the Python/C API calls, which requires you to be meticulous about maintaining reference counts, checking for errors at every step and cleaning up properly if anything goes wrong. Any mistakes and you have a nasty crash that's very difficult to debug.<p>Various tools have been developed to ease some of the burdens of producing extension code, of which perhaps <a href="http://www.swig.org">SWIG</a> is the best known. SWIG takes a definition file consisting of a mixture of C code and specialised declarations, and produces an extension module. It writes all the boilerplate for you, and in many cases you can use it without knowing about the Python/C API. But you need to use API calls if any substantial restructuring of the data is required between Python and C.<p>What's more, SWIG gives you no help at all if you want to create a new built-in Python <i>type. </i>It will generate pure-Python classes which wrap (in a slightly unsafe manner) pointers to C data structures, but creation of true extension types is outside its scope.<p>Another notable attempt at making it easier to extend Python is <a href="http://pyinline.sourceforge.net/">PyInline</a> , inspired by a similar facility for Perl. PyInline lets you embed pieces of C code in the midst of a Python file, and automatically extracts them and compiles them into an extension. But it only converts the basic types automatically, and as with SWIG,&nbsp; it doesn't address the creation of new Python types.<p>Pyrex aims to go far beyond what any of these previous tools provides. Pyrex deals with the basic types just as easily as SWIG, but it also lets you write code to convert between arbitrary Python data structures and arbitrary C data structures, in a simple and natural way, without knowing<i>anything</i> about the Python/C API. That's right -- <i>nothing at all</i>! Nor do you have to worry about reference counting or error checking -- it's all taken care of automatically, behind the scenes, just as it is in interpreted Python code. And what's more, Pyrex lets you define new<i>built-in</i> Python types just as easily as you can define new classes in Python.<p>Sound too good to be true? Read on and find out how it's done.<h2> The Basics of Pyrex</h2> The fundamental nature of Pyrex can be summed up as follows: <b>Pyrex is Python with C data types</b>.<p><i>Pyrex is Python:</i> Almost any piece of Python code is also valid Pyrex code. (There are a few limitations, but this approximation will serve for now.) The Pyrex compiler will convert it into C code which makes equivalent calls to the Python/C API. In this respect, Pyrex is similar to the former Python2C project (to which I would supply a reference except that it no longer seems to exist).<p><i>...with C data types.</i> But Pyrex is much more than that, because parameters and variables can be declared to have C data types. Code which manipulates Python values and C values can be freely intermixed, with conversions occurring automatically wherever possible. Reference count maintenance and error checking of Python operations is also automatic, and the full power of Python's exception handling facilities, including the try-except and try-finally statements, is available to you -- even in the midst of manipulating C data.<p>Here's a small example showing some of what can be done. It's a routine for finding prime numbers. You tell it how many primes you want, and it returns them as a Python list.<blockquote><b><tt><font size=+1>primes.pyx</font></tt></b></blockquote> <blockquote><pre>&nbsp;1&nbsp; def primes(int kmax):&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef int n, k, i&nbsp;3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef int p[1000]&nbsp;4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; result = []&nbsp;5&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if kmax > 1000:&nbsp;6&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; kmax = 1000&nbsp;7&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; k = 0&nbsp;8&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; n = 2&nbsp;9&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while k &lt; kmax: 10&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; i = 0 11&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while i &lt; k and n % p[i] &lt;> 0: 12&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; i = i + 1 13&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if i == k: 14&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; p[k] = n 15&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; k = k + 1 16&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; result.append(n) 17&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; n = n + 1 18&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return result</pre></blockquote> You'll see that it starts out just like a normal Python function definition, except that the parameter <b>kmax</b> is declared to be of type <b>int</b> . This means that the object passed will be converted to a C integer (or a TypeError will be raised if it can't be).<p>Lines 2 and 3 use the <b>cdef</b> statement to define some local C variables. Line 4 creates a Python list which will be used to return the result. You'll notice that this is done exactly the same way it would be in Python. Because the variable <b>result</b> hasn't been given a type, it is assumed to hold a Python object.<p>Lines 7-9 set up for a loop which will test candidate numbers for primeness until the required number of primes has been found. Lines 11-12, which try dividing a candidate by all the primes found so far, are of particular interest. Because no Python objects are referred to, the loop is translated entirely into C code, and thus runs very fast.<p>When a prime is found, lines 14-15 add it to the p array for fast access by the testing loop, and line 16 adds it to the result list. Again, you'll notice that line 16 looks very much like a Python statement, and in fact it is, with the twist that the C parameter <b>n</b> is automatically converted to a Python object before being passed to the <b>append</b> method. Finally, at line 18, a normal Python <b>return</b> statement returns the result list.<p>Compiling primes.pyx with the Pyrex compiler produces an extension module which we can try out in the interactive interpreter as follows:<blockquote><pre>>>> import primes >>> primes.primes(10) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] >>></pre></blockquote> See, it works! And if you're curious about how much work Pyrex has saved you, take a look at the <a href="primes.c">C code generated for this module</a> .<h2> Language Details</h2> For more about the Pyrex language, see the <a href="overview.html">Language Overview</a> .<h2> Future Plans</h2> Pyrex is not finished. Substantial tasks remaining include:<ul><li> Support for certain Python language features which are planned but not yet implemented. See the <a href="overview.html#Limitations">Limitations</a> section of the <a href="overview.html">Language Overview</a> for a current list.</li></ul> <ul><li> C++ support. This could be a very big can of worms - careful thought required before going there.</li></ul> <ul><li> Reading C/C++ header files directly would be very nice, but there are some severe problems that I will have to find solutions for first, such as what to do about preprocessor macros. My current thinking is to use a separate tool to convert .h files into Pyrex declarations, possibly with some manual intervention.</li></ul> </body></html>
\ No newline at end of file
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Mozilla/4.51 (Macintosh; I; PPC) [Netscape]"><title>FAQ.html</title></head>
<body>
<center> <h1> <hr width="100%">Pyrex FAQ
<hr width="100%"></h1>
</center>
<h2> Contents</h2>
<ul>
<li> <b><a href="#CallCAPI">How do I call Python/C API routines?</a></b></li>
<li> <b><a href="#NullBytes">How do I convert a C string containing null
bytes to a Python string?</a></b></li>
<li> <b><a href="#NumericAccess">How do I access the data inside a Numeric
array object?</a></b></li>
<li><b><a href="#Rhubarb">Pyrex says my extension type object has no attribute
'rhubarb', but I know it does. What gives?</a></b></li><li><a style="font-weight: bold;" href="#Quack">Python says my extension type has no method called 'quack', but I know it does. What gives?</a><br>
</li>
</ul>
<hr width="100%"> <h2> <a name="CallCAPI"></a>How do I call Python/C API routines?</h2>
Declare them as C functions inside a <tt>cdef extern from</tt> block.
Use the type name <tt>object</tt> for any parameters and return types which
are Python object references. Don't use the word <tt>const</tt> anywhere.
Here is an example which defines and uses the <tt>PyString_FromStringAndSize</tt> routine:
<blockquote><tt>cdef extern from "Python.h":</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; object PyString_FromStringAndSize(char *, int)</tt> <p><tt>cdef char buf[42]</tt> <br>
<tt>my_string = PyString_FromStringAndSize(buf, 42)</tt></p>
</blockquote>
<h2> <a name="NullBytes"></a>How do I convert a C string containing null
bytes to a Python string?</h2>
Put in a declaration for the <tt>PyString_FromStringAndSize</tt> API routine
and use that<tt>.</tt> See <a href="#CallCAPI">How do I call Python/C API
routines?</a> <h2> <a name="NumericAccess"></a>How do I access the data inside a Numeric
array object?</h2>
Use a <tt>cdef extern from</tt> block to include the Numeric header file
and declare the array object as an external extension type. The following
code illustrates how to do this:
<blockquote><tt>cdef extern from "Numeric/arrayobject.h":</tt> <p><tt>&nbsp;&nbsp;&nbsp; struct PyArray_Descr:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int type_num, elsize</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; char type</tt> </p>
<p><tt>&nbsp;&nbsp;&nbsp; ctypedef class Numeric.ArrayType [object PyArrayObject]</tt><tt>:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef char *data</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef int nd</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef int *dimensions,
*strides</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef object base</tt>
<br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef PyArray_Descr *descr</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef int flags<br>
</tt></p>
</blockquote>
<p>For more information about external extension types, see the <a href="extension_types.html#ExternalExtTypes">"External Extension Types"</a>
section of the <a href="extension_types.html">"Extension Types"</a> documentation
page.<br>
<tt> </tt> </p>
<h2><a name="Rhubarb"></a>Pyrex says my extension type object has no attribute
'rhubarb', but I know it does. What gives?</h2>
You're probably trying to access it through a reference which Pyrex thinks
is a generic Python object. You need to tell Pyrex that it's a reference
to your extension type by means of a declaration,<br>
for example,<br>
<blockquote><tt>cdef class Vegetables:</tt><br>
<tt>&nbsp; &nbsp; cdef int rhubarb</tt><br>
<br>
<tt>...</tt><br>
<tt>cdef Vegetables veg</tt><br>
<tt>veg.rhubarb = 42</tt><br>
</blockquote>
Also see the <a href="extension_types.html#ExtTypeAttrs">"Attributes"</a>
section of the <a href="extension_types.html">"Extension
Types"</a> documentation page.<br>
<h2><a name="Quack"></a>Python says my extension type has no method called 'quack', but I know it does. What gives?</h2>
You may have declared the method using <span style="font-family: monospace;">cdef</span> instead of <span style="font-family: monospace;">def</span>. Only functions and methods declared with <span style="font-family: monospace;">def</span> are callable from Python code.<br>
---
</body></html>
\ No newline at end of file
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Mozilla/4.61 (Macintosh; I; PPC) [Netscape]"><title>Extension Types</title></head>
<body>
<h1> <hr width="100%">Extension Types
<hr width="100%"></h1>
<h2> Contents</h2>
<ul>
<li> <a href="#Introduction">Introduction</a></li>
<li> <a href="#ExtTypeAttrs">Attributes</a></li>
<li> <a href="#NotNone">Extension types and None</a></li>
<li> <a href="special_methods.html">Special methods</a></li>
<li> <a href="#Properties">Properties</a> <font style="color: rgb(0, 153, 0);" color="#ed181e">(NEW in
0.9)</font></li>
<li><a href="#SubclassingExtTypes">Subclassing</a></li>
<li> <a href="#CMethods">C Methods</a> <font style="color: rgb(0, 153, 0);" color="#ff0000">(NEW in 0.9)</font><br>
<a href="#ForwardDeclaringExtTypes">Forward-declaring extension types</a></li><li><a href="#WeakRefs">Making extension types weak-referenceable</a> <span style="color: rgb(255, 0, 0);">(NEW in 0.9.4)</span><br>
</li>
<li> <a href="#PublicAndExtern">Public and external extension types</a><font color="#2f8b20"><br>
</font></li>
<ul>
<li> <a href="#ExternalExtTypes">External extension types</a></li>
<li> <a href="#ImplicitImport">Implicit importing</a><font color="#2f8b20"><br>
</font></li>
<li> <a href="#TypeVsConstructor">Type names vs. constructor names</a></li>
<li> <a href="#PublicExtensionTypes">Public extension types</a></li>
<li> <a href="#NameSpecClause">Name specification clause</a></li>
</ul>
</ul>
<h2> <a name="Introduction"></a>Introduction</h2>
As well as creating normal user-defined classes with the Python <b>class</b>
statement, Pyrex also lets you create new built-in Python types, known as
<i>extension types</i>. You define an extension type using the <b>cdef class</b> statement. Here's an example:
<blockquote><tt>cdef class Shrubbery:</tt> <p><tt>&nbsp;&nbsp;&nbsp; cdef int width, height</tt> </p>
<p><tt>&nbsp;&nbsp;&nbsp; def __init__(self, w, h):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.width = w</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.height = h</tt> </p>
<p><tt>&nbsp;&nbsp;&nbsp; def describe(self):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print "This shrubbery is",
self.width, \</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
"by", self.height, "cubits."</tt></p>
</blockquote>
As you can see, a Pyrex extension type definition looks a lot like a Python
class definition. Within it, you use the <b>def</b> statement to define
methods that can be called from Python code. You can even define many of
the special methods such as <tt>__init__</tt> as you would in Python.
<p>The main difference is that you can use the <b>cdef</b> statement to define
attributes. The attributes may be Python objects (either generic or of a particular
extension type), or they may be of any C data type. So you can use extension
types to wrap arbitrary C data structures and provide a Python-like interface
to them. </p>
<h2> <a name="ExtTypeAttrs"></a>Attributes</h2>
Attributes of an extension type are stored directly in the object's C struct.
The set of attributes is fixed at compile time; you can't add attributes
to an extension type instance at run time simply by assigning to them, as
you could with a Python class instance. (You can subclass the extension type
in Python and add attributes to instances of the subclass, however.)
<p>There are two ways that attributes of an extension type can be accessed:
by Python attribute lookup, or by direct access to the C struct from Pyrex
code. Python code is only able to access attributes of an extension type
by the first method, but Pyrex code can use either method. </p>
<p>By default, extension type attributes are only accessible by direct access,
not Python access, which means that they are not accessible from Python code.
To make them accessible from Python code, you need to declare them as <tt>public</tt> or <tt>readonly</tt>. For example, </p>
<blockquote><tt>cdef class Shrubbery:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; cdef public int width, height</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; cdef readonly float depth</tt></blockquote>
makes the <tt>width</tt> and <tt>height</tt> attributes readable and writable
from Python code, and the <tt>depth</tt> attribute readable but not writable.
<p>Note that you can only expose simple C types, such as ints, floats and
strings, for Python access. You can also expose Python-valued attributes,
although read-write exposure is only possible for generic Python attributes
(of type <tt>object</tt>). If the attribute is declared to be of an extension
type, it must be exposed <tt>readonly</tt>. </p>
<p>Note also that the <tt>public</tt> and <tt>readonly</tt> options apply
only to <i>Python</i> access, not direct access. All the attributes of an
extension type are always readable and writable by direct access. </p>
<p>Howerver, for direct access to be possible, the Pyrex compiler must know
that you have an instance of that type, and not just a generic Python object.
It knows this already in the case of the "self" parameter of the methods of
that type, but in other cases you will have to tell it by means of a declaration.
For example, </p>
<blockquote><tt>cdef widen_shrubbery(Shrubbery sh, extra_width):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; sh.width = sh.width + extra_width</tt></blockquote>
If you attempt to access an extension type attribute through a generic
object reference, Pyrex will use a Python attribute lookup. If the attribute
is exposed for Python access (using <tt>public</tt> or <tt>readonly</tt>)
then this will work, but it will be much slower than direct access.
<h2> <a name="NotNone"></a>Extension types and None</h2>
When you declare a parameter or C variable as being of an extension type,
Pyrex will allow it to take on the value None as well as values of its declared
type. This is analogous to the way a C pointer can take on the value NULL,
and you need to exercise the same caution because of it. There is no problem
as long as you are performing Python operations on it, because full dynamic
type checking will be applied. However, when you access C attributes of an
extension type (as in the <tt>widen_shrubbery</tt> function above), it's up
to you to make sure the reference you're using is not None -- in the interests
of efficiency, Pyrex does <i>not</i> check this.
<p>You need to be particularly careful when exposing Python functions which
take extension types as arguments. If we wanted to make <tt>widen_shrubbery</tt>
a Python function, for example, if we simply wrote </p>
<blockquote><tt>def widen_shrubbery(Shrubbery sh, extra_width): # <font color="#ed181e">This is</font></tt> <br>
<tt>&nbsp;&nbsp;&nbsp; sh.width = sh.width + extra_width&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
# <font color="#ed181e">dangerous!</font></tt></blockquote>
then users of our module could crash it by passing None for the <tt>sh</tt>
parameter.
<p>One way to fix this would be </p>
<blockquote><tt>def widen_shrubbery(Shrubbery sh, extra_width):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; if sh is None:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; raise TypeError</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; sh.width = sh.width + extra_width</tt></blockquote>
but since this is anticipated to be such a frequent requirement, Pyrex
provides a more convenient way. Parameters of a Python function declared
as an extension type can have a <b><tt>not None</tt></b> clause:
<blockquote><tt>def widen_shrubbery(Shrubbery sh not None, extra_width):</tt>
<br>
<tt>&nbsp;&nbsp;&nbsp; sh.width = sh.width + extra_width</tt></blockquote>
Now the function will automatically check that <tt>sh</tt> is not None
along with checking that it has the right type.
<p>Note, however that the <tt>not None</tt> clause can <i>only</i> be used
in Python functions (defined with <tt>def</tt>) and not C functions (defined
with <tt>cdef</tt>). If you need to check whether a parameter to a C function
is None, you will need to do it yourself. </p>
<p>Some more things to note: </p>
<ul>
<li> The <b>self</b> parameter of a method of an extension type is guaranteed
never to be None.</li>
</ul>
<ul>
<li> When comparing a value with None, keep in mind that, if <tt>x</tt> is a Python object, <tt>x is None</tt> and <tt>x is not None</tt> are very
efficient because they translate directly to C pointer comparisons, whereas
<tt>x == None</tt> and <tt>x != None</tt>, or simply using <tt>x</tt> as a boolean value (as in <tt>if x: ...</tt>) will invoke Python operations
and therefore be much slower.</li>
</ul>
<h2> <a name="ExtTypeSpecialMethods"></a>Special methods</h2>
Although the principles are similar, there are substantial differences
between many of the <span style="font-family: monospace;">__xxx__</span> special methods of extension types and their
Python counterparts. There is a <a href="special_methods.html">separate page</a> devoted to this subject, and you should read it carefully before attempting
to use any special methods in your extension types.
<h2> <a name="Properties"></a>Properties</h2>
There is a special syntax for defining <b>properties</b> in an extension
class:
<blockquote><tt>cdef class Spam:</tt> <p><tt>&nbsp;&nbsp;&nbsp; property cheese:</tt> </p>
<p><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "A doc string can go
here."</tt> </p>
<p><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; def __get__(self):</tt>
<br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
# This is called when the property is read.</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
...</tt> </p>
<p><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; def __set__(self, value):</tt>
<br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
# This is called when the property is written.</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
...</tt> </p>
<p><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; def __del__(self):</tt>
<br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
# This is called when the property is deleted.</tt> <br>
&nbsp;</p>
</blockquote>
The <tt>__get__</tt>, <tt>__set__</tt> and <tt>__del__</tt> methods are
all optional; if they are omitted, an exception will be raised when the corresponding
operation is attempted.
<p>Here's a complete example. It defines a property which adds to a list
each time it is written to, returns the list when it is read, and empties
the list when it is deleted. <br>
&nbsp; </p>
<center> <table align="center" cellpadding="5">
<tbody>
<tr>
<td bgcolor="#ffaf18"><b><tt>cheesy.pyx</tt></b></td>
<td bgcolor="#5dbaca"><b>Test input</b></td>
</tr>
<tr>
<td rowspan="3" bgcolor="#ffaf18" valign="top"><tt>cdef class CheeseShop:</tt>
<p><tt>&nbsp; cdef object cheeses</tt> </p>
<p><tt>&nbsp; def __new__(self):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; self.cheeses = []</tt> </p>
<p><tt>&nbsp; property cheese:</tt> </p>
<p><tt>&nbsp;&nbsp;&nbsp; def __get__(self):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return "We don't have: %s" % self.cheeses</tt>
</p>
<p><tt>&nbsp;&nbsp;&nbsp; def __set__(self, value):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.cheeses.append(value)</tt>
</p>
<p><tt>&nbsp;&nbsp;&nbsp; def __del__(self):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; del self.cheeses[:]</tt></p>
</td>
<td bgcolor="#5dbaca" valign="top"><tt>from cheesy import CheeseShop</tt>
<p><tt>shop = CheeseShop()</tt> <br>
<tt>print shop.cheese</tt> </p>
<p><tt>shop.cheese = "camembert"</tt> <br>
<tt>print shop.cheese</tt> </p>
<p><tt>shop.cheese = "cheddar"</tt> <br>
<tt>print shop.cheese</tt> </p>
<p><tt>del shop.cheese</tt> <br>
<tt>print shop.cheese</tt></p>
</td>
</tr>
<tr>
<td bgcolor="#8cbc1c"><b>Test output</b></td>
</tr>
<tr>
<td bgcolor="#8cbc1c"><tt>We don't have: []</tt> <br>
<tt>We don't have: ['camembert']</tt> <br>
<tt>We don't have: ['camembert', 'cheddar']</tt> <br>
<tt>We don't have: []</tt></td>
</tr>
</tbody> </table>
</center>
<h2> <a name="SubclassingExtTypes"></a>Subclassing</h2>
An extension type may inherit from a built-in type or another extension
type:
<blockquote><tt>cdef class Parrot:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt><tt></tt> <p><tt>cdef class Norwegian(Parrot):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt></p>
</blockquote>
<p><br>
A complete definition of the base type must be available to Pyrex, so if
the base type is a built-in type, it must have been previously declared as
an <b>extern</b> extension type. If the base type is defined in another Pyrex
module, it must either be declared as an extern extension type or imported
using the <b><a href="sharing.html">cimport</a></b> statement. </p>
<p>An extension type can only have one base class (no multiple inheritance).
</p>
<p>Pyrex extension types can also be subclassed in Python. A Python class
can inherit from multiple extension types provided that the usual Python
rules for multiple inheritance are followed (i.e. the C layouts of all the
base classes must be compatible).<br>
</p>
<h2><a name="CMethods"></a>C methods</h2>
Extension types can have C methods as well as Python methods. Like C functions,
C methods are declared using <tt>cdef</tt> instead of <tt>def</tt>. C methods
are "virtual", and may be overridden in derived extension types.<br>
<br>
<table align="center" cellpadding="5">
<tbody>
<tr>
<td bgcolor="#ffaf18" valign="top" width="50%"><b><tt>pets.pyx</tt></b><br>
</td>
<td bgcolor="#8cbc1c" valign="top" width="30%"><b>Output</b><br>
</td>
</tr>
<tr>
<td bgcolor="#ffaf18" valign="top" width="50%"><tt>cdef class Parrot:<br>
<br>
&nbsp; cdef void describe(self):<br>
&nbsp; &nbsp; print "This parrot is resting."<br>
<br>
cdef class Norwegian(Parrot):<br>
<br>
&nbsp; cdef void describe(self):<br>
&nbsp; &nbsp; Parrot.describe(self)<br>
&nbsp; &nbsp; print "Lovely plumage!"<br>
<br>
<br>
cdef Parrot p1, p2<br>
p1 = Parrot()<br>
p2 = Norwegian()<br>
print "p1:"<br>
p1.describe()<br>
print "p2:"<br>
p2.describe()</tt> <br>
</td>
<td bgcolor="#8cbc1c" valign="top" width="30%"><tt>p1:<br>
This parrot is resting.<br>
p2:<br>
</tt><tt>This parrot is resting.<br>
</tt><tt> Lovely plumage!</tt><br>
</td>
</tr>
</tbody> </table>
<br>
The above example also illustrates that a C method can call an inherited
C method using the usual Python technique, i.e.<br>
<blockquote><tt>Parrot.describe(self)</tt><br>
</blockquote>
<h2><a name="ForwardDeclaringExtTypes"></a>Forward-declaring extension types</h2>
Extension types can be forward-declared, like struct and union types. This
will be necessary if you have two extension types that need to refer to
each other, e.g.
<blockquote><tt>cdef class Shrubbery # forward declaration</tt> <p><tt>cdef class Shrubber:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; cdef Shrubbery work_in_progress</tt> </p>
<p><tt>cdef class Shrubbery:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; cdef Shrubber creator</tt></p>
</blockquote>
If you are forward-declaring an exension type that has a base class, you
must specify the base class in both the forward declaration and its subsequent
definition, for example,<br>
<blockquote><tt>cdef class A(B)<br>
<br>
...<br>
<br>
cdef class A(B):<br>
&nbsp; &nbsp; # attributes and methods</tt><br>
</blockquote>
<h2><a name="WeakRefs"></a>Making extension types weak-referenceable</h2>By
default, extension types do not support having weak references made to
them. You can enable weak referencing by declaring a C attribute of
type <span style="font-family: monospace;">object</span> called <span style="font-family: monospace; font-weight: bold;">__weakref__</span>. For example,<br>
<br>
<div style="margin-left: 40px;"><span style="font-family: monospace;">cdef class ExplodingAnimal:</span><br style="font-family: monospace;">
<span style="font-family: monospace;">&nbsp;&nbsp;&nbsp; """This animal will self-destruct when it is</span><br>
<span style="font-family: monospace;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; no longer strongly referenced."""</span><br>
<span style="font-family: monospace;">&nbsp;&nbsp;&nbsp; </span><br style="font-family: monospace;">
<span style="font-family: monospace;"></span><span style="font-family: monospace;">&nbsp;&nbsp;&nbsp; cdef object __weakref__</span><br>
</div>
<br>
<h2><a name="PublicAndExtern"></a>Public and external extension types</h2>
Extension types can be declared <b>extern</b> or <b>public</b>. An <a href="#ExternalExtTypes"><b>extern</b> extension type declaration</a> makes
an extension type defined in external C code available to a Pyrex module.
A <a href="#PublicExtensionTypes"><b>public</b> extension type declaration</a> makes an extension type defined in a Pyrex module available to external C
code.
<h3> <a name="ExternalExtTypes"></a>External extension types</h3>
An <b>extern</b> extension type allows you to gain access to the internals
of Python objects defined in the Python core or in a non-Pyrex extension
module.
<blockquote><b>NOTE:</b> In Pyrex versions before 0.8, <b>extern</b> extension
types were also used to reference extension types defined in another Pyrex
module. While you can still do that, Pyrex 0.8 and later provides a better
mechanism for this. See <a href="sharing.html">Sharing C Declarations Between
Pyrex Modules</a>.</blockquote>
Here is an example which will let you get at the C-level members of the
built-in <i>complex</i> object.
<blockquote><tt>cdef extern from "complexobject.h":</tt> <p><tt>&nbsp;&nbsp;&nbsp; struct Py_complex:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; double real</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; double imag</tt> </p>
<p><tt>&nbsp;&nbsp;&nbsp; ctypedef class __builtin__.complex [object PyComplexObject]:</tt>
<br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef Py_complex cval</tt>
</p>
<p><tt># A function which uses the above type</tt> <br>
<tt>def spam(complex c):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; print "Real:", c.cval.real</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; print "Imag:", c.cval.imag</tt></p>
</blockquote>
Some important things to note are:
<ol>
<li> In this example, <b>ctypedef class</b> has been used. This is because,
in the Python header files, the <tt>PyComplexObject</tt> struct is declared
with<br>
<br>
<div style="margin-left: 40px;"><tt>ctypedef struct {</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt> <br>
<tt>} PyComplexObject;<br>
<br>
</tt></div>
</li><li>As well as the name of the extension type, the <i>module</i> in which
its type object can be found is also specified. See the <a href="#ImplicitImport">implicit importing</a> section below.&nbsp; <br>
<br>
</li>
<li> When declaring an external extension type, you don't declare
any methods. Declaration of methods is not required in order to call them,
because the calls are Python method calls. Also, as with structs and unions,
if your extension class declaration is inside a <i>cdef extern from</i> block,
you only need to declare those C members which you wish to access.</li>
</ol>
<h3> <a name="ImplicitImport"></a>Implicit importing</h3>
<blockquote><font color="#ef1f1d">Backwards Incompatibility Note</font>:
You will have to update any pre-0.8 Pyrex modules you have which use <b>extern</b>
extension types. I apologise for this, but for complicated reasons it proved
to be too difficult to continue supporting the old way of doing these while
introducing the new features that I wanted.</blockquote>
Pyrex 0.8 and later requires you to include a module name in an extern
extension class declaration, for example,
<blockquote><tt>cdef extern class MyModule.Spam:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
The type object will be implicitly imported from the specified module and
bound to the corresponding name in this module. In other words, in this
example an implicit
<ol>
<pre>from <tt>MyModule</tt> import Spam</pre>
</ol>
statement will be executed at module load time.
<p>The module name can be a dotted name to refer to a module inside a package
hierarchy, for example, </p>
<blockquote><tt>cdef extern class My.Nested.Package.Spam:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
You can also specify an alternative name under which to import the type
using an <b>as</b> clause, for example,
<ol>
<tt>cdef extern class My.Nested.Package.Spam as Yummy:</tt> <br>
<tt>&nbsp;&nbsp; ...</tt> </ol>
which corresponds to the implicit import statement
<ol>
<pre>from <tt>My.Nested.Package</tt> import <tt>Spam</tt> as <tt>Yummy</tt></pre>
</ol>
<h3> <a name="TypeVsConstructor"></a>Type names vs. constructor names</h3>
Inside a Pyrex module, the name of an extension type serves two distinct
purposes. When used in an expression, it refers to a module-level global
variable holding the type's constructor (i.e. its type-object). However,
it can also be used as a C type name to declare variables, arguments and
return values of that type.
<p>When you declare </p>
<blockquote><tt>cdef extern class MyModule.Spam:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
the name <tt>Spam</tt> serves both these roles. There may be other names
by which you can refer to the constructor, but only <tt>Spam</tt> can be
used as a type name. For example, if you were to explicity <tt>import MyModule</tt>,
you could use<tt> MyModule.Spam()</tt> to create a Spam instance, but you
wouldn't be able to use <tt>MyModule.Spam</tt> as a type name.
<p>When an <b>as</b> clause is used, the name specified in the <b>as</b>
clause also takes over both roles. So if you declare </p>
<blockquote><tt>cdef extern class MyModule.Spam as Yummy:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
then <tt>Yummy</tt> becomes both the type name and a name for the constructor.
Again, there are other ways that you could get hold of the constructor,
but only <tt>Yummy</tt> is usable as a type name.
<h3> <a name="PublicExtensionTypes"></a>Public extension types</h3>
An extension type can be declared <b>public</b>, in which case a <b>.h</b>
file is generated containing declarations for its object struct and type
object. By including the <b>.h</b> file in external C code that you write,
that code can access the attributes of the extension type.
<h3> <a name="NameSpecClause"></a>Name specification clause</h3>
The part of the class declaration in square brackets is a special feature
only available for <b>extern</b> or <b>public</b> extension types. The full
form of this clause is
<blockquote><tt>[object </tt><i>object_struct_name</i><tt>, type </tt><i>type_object_name</i><span style="font-family: monospace;"> ]</span></blockquote>
where <i>object_struct_name</i> is the name to assume for the type's C
struct, and <i>type_object_name</i> is the name to assume for the type's
statically declared type object. (The object and type clauses can be written
in either order.)
<p>If the extension type declaration is inside a <b>cdef extern from</b>
block, the <b>object</b> clause is required, because Pyrex must be able to
generate code that is compatible with the declarations in the header file.
Otherwise, for <b>extern</b> extension types, the <b>object</b> clause is
optional. </p>
<p>For <b>public</b> extension types, the <b>object</b> and <b>type</b> clauses
are both required, because Pyrex must be able to generate code that is compatible
with external C code. </p>
<p> </p>
<hr width="100%"> <br>
Back to the <a href="overview.html">Language Overview</a> <br>
&nbsp; <br>
<br>
</body></html>
\ No newline at end of file
<!doctype html public "-//w3c//dtd html 4.0 transitional//en"><html><head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="GENERATOR" content="Mozilla/4.51 (Macintosh; I; PPC) [Netscape]"> <title>Pyrex - Front Page</title></head><body>&nbsp;<table CELLSPACING=0 CELLPADDING=10 WIDTH="500" ><tr><td VALIGN=TOP BGCOLOR="#FF9218"><font face="Arial,Helvetica"><font size=+4>Pyrex</font></font></td> <td ALIGN=RIGHT VALIGN=TOP WIDTH="200" BGCOLOR="#5DBACA"><font face="Arial,Helvetica"><font size=+1>A smooth blend of the finest Python&nbsp;</font></font><br><font face="Arial,Helvetica"><font size=+1>with the unsurpassed power&nbsp;</font></font><br><font face="Arial,Helvetica"><font size=+1>of raw C.</font></font></td></tr></table> <blockquote><font size=+1>Welcome to Pyrex, a language for writing Python extension modules. Pyrex makes creating an extension module is almost as easy as creating a Python module! To find out more, consult one of the edifying documents below.</font></blockquote> <h1><font face="Arial,Helvetica"><font size=+2>Documentation</font></font></h1> <blockquote><h2><font face="Arial,Helvetica"><font size=+1><a href="About.html">About Pyrex</a></font></font></h2> <blockquote><font size=+1>Read this to find out what Pyrex is all about and what it can do for you.</font></blockquote> <h2><font face="Arial,Helvetica"><font size=+1><a href="overview.html">Language Overview</a></font></font></h2> <blockquote><font size=+1>A description of all the features of the Pyrex language. This is the closest thing to a reference manual in existence yet.</font></blockquote> <h2><font face="Arial,Helvetica"><font size=+1><a href="FAQ.html">FAQ</a></font></font></h2> <blockquote><font size=+1>Want to know how to do something in Pyrex? Check here first<font face="Arial,Helvetica">.</font></font></blockquote></blockquote> <h1><font face="Arial,Helvetica"><font size=+2>Other Resources</font></font></h1> <blockquote><h2><font face="Arial,Helvetica"><font size=+1><a href="http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/mpj17-pyrex-guide/">Michael's Quick Guide to Pyrex</a></font></font></h2> <blockquote><font size=+1>This tutorial-style presentation will take you through the steps of creating some Pyrex modules to wrap existing C libraries. Contributed by <a href="mailto:mpj17@cosc.canterbury.ac.nz">Michael JasonSmith</a>.</font></blockquote> <h2><font face="Arial,Helvetica"><font size=+1><a href="mailto:greg@cosc.canterbury.ac.nz">Mail to the Author</a></font></font></h2> <blockquote><font size=+1>If you have a question that's not answered by anything here, you're not sure about something, or you have a bug to report or a suggestion to make, or anything at all to say about Pyrex, feel free to email me:<font face="Arial,Helvetica"> </font><tt><a href="mailto:greg@cosc.canterbury.ac.nz">greg@cosc.canterbury.ac.nz</a></tt></font></blockquote></blockquote> </body></html>
\ No newline at end of file
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Mozilla/4.61 (Macintosh; I; PPC) [Netscape]">
<title>Pyrex Language Overview</title>
</head>
<body>
<h1> <hr width="100%">Overview of the Pyrex Language&nbsp; <hr width="100%"></h1>
This document informally describes the extensions to the Python language
made by Pyrex. Some day there will be a reference manual covering everything
in more detail. <br>
&nbsp;
<h2> Contents</h2>
<ul>
<li> <a href="#Basics">Basics</a></li>
<ul>
<li> <a href="#PyFuncsVsCFuncs">Python functions vs. C functions</a></li>
<li> <a href="#PyObjParams">Python objects as parameters</a></li>
<li> <a href="#CVarAndTypeDecls">C variable and type definitions</a></li><li><a href="#AutomaticTypeConversions">Automatic type conversions</a></li>
<ul>
<li><a href="#PyToCStringCaveats">Caveats when using a Python string in a C context</a></li>
</ul>
<li> <a href="#ScopeRules">Scope rules</a></li>
<li> <a href="#StatsAndExprs">Statements and expressions</a></li>
<ul>
<li> <a href="#ExprSyntaxDifferences">Differences between C and Pyrex
expressions<br>
</a></li>
<li> <a href="#ForFromLoop">Integer for-loops</a></li>
</ul>
<li> <a href="#ExceptionValues">Error return values</a></li>
<ul>
<li> <a href="#CheckingReturnValues">Checking return values of non-Pyrex
functions</a></li>
</ul>
<li> <a href="#IncludeStatement">The <tt>include</tt> statement</a></li>
</ul>
<li> <a href="#InterfacingWithExternal">Interfacing with External C Code</a></li>
<ul>
<li> <a href="#ExternDecls">External declarations</a></li>
<ul>
<li> <a href="#ReferencingHeaders">Referencing C header files</a></li>
<li> <a href="#StructDeclStyles">Styles of struct/union/enum declaration</a></li>
<li> <a href="#AccessingAPI">Accessing Python/C API routines</a></li>
<li> <a href="#CNameSpecs">Resolving naming conflicts - C name specifications</a></li>
</ul>
<li> <a href="#PublicDecls">Public declarations</a></li>
</ul>
<li> <a href="extension_types.html">Extension Types</a> <font color="#006600">(Section revised in 0.9)</font></li>
<li> <a href="sharing.html">Sharing Declarations Between Pyrex Modules</a>
<font color="#006600">(NEW in 0.8)</font></li>
<li> <a href="#Limitations">Limitations</a></li>
<ul>
<li> <a href="#Unsupported">Unsupported Python features</a></li>
<li> <a href="#SemanticDifferences">Semantic differences between Python
and Pyrex</a></li>
</ul>
</ul>
<h2> <hr width="100%"><a name="Basics"></a>Basics
<hr width="100%"></h2>
This section describes the basic features of the Pyrex language. The facilities
covered in this section allow you to create Python-callable functions that
manipulate C data structures and convert between Python and C data types.
Later sections will cover facilities for <a href="#InterfacingWithExternal">wrapping external C code</a>, <a href="extension_types.html">creating new Python types</a> and <a href="sharing.html">cooperation between Pyrex modules</a>.
<h3> <a name="PyFuncsVsCFuncs"></a>Python functions vs. C functions</h3>
There are two kinds of function definition in Pyrex:
<p><b>Python functions</b> are defined using the <b>def</b> statement, as
in Python. They take Python objects as parameters and return Python objects.
</p>
<p><b>C functions</b> are defined using the new <b>cdef</b> statement. They
take either Python objects or C values as parameters, and can return either
Python objects or C values. </p>
<p>Within a Pyrex module, Python functions and C functions can call each other
freely, but only Python functions can be called from outside the module by
interpreted Python code. So, any functions that you want to "export" from
your Pyrex module must be declared as Python functions using <span style="font-weight: bold;">def</span>. </p>
<p>Parameters of either type of function can be declared to have C data types,
using normal C declaration syntax. For example, </p>
<blockquote> <pre>def spam(int i, char *s):<br>&nbsp;&nbsp;&nbsp; ...</pre>
<pre>cdef int eggs(unsigned long l, float f):<br>&nbsp;&nbsp;&nbsp; ...</pre>
</blockquote>
When a parameter of a Python function is declared to have a C data type,
it is passed in as a Python object and automatically converted to a C value,
if possible. Automatic conversion is currently only possible for numeric
types and string types; attempting to use any other type for the parameter
of a Python function will result in a compile-time error.
<p>C functions, on the other hand, can have parameters of any type, since
they're passed in directly using a normal C function call. </p>
<h3> <a name="PyObjParams"></a>Python objects as parameters and return values</h3>
If no type is specified for a parameter or return value, <i>it is assumed
to be a Python object.</i> (Note that this is different from the C convention,
where it would default to <tt>int</tt>.) For example, the following defines
a C function that takes two Python objects as parameters and returns a Python
object:
<blockquote> <pre>cdef spamobjs(x, y):<br>&nbsp;&nbsp;&nbsp; ...</pre>
</blockquote>
Reference counting for these objects is performed automatically according
to the standard Python/C API rules (i.e. borrowed references are taken as
parameters and a new reference is returned).
<p>The name <b>object</b> can also be used to explicitly declare something
as a Python object. This can be useful if the name being declared would otherwise
be taken as the name of a type, for example, </p>
<blockquote> <pre>cdef ftang(object int):<br>&nbsp;&nbsp;&nbsp; ...</pre>
</blockquote>
declares a parameter called <tt>int</tt> which is a Python object. You
can also use <b>object </b>as the explicit return type of a function, e.g.
<blockquote> <pre>cdef object ftang(object int):<br>&nbsp;&nbsp;&nbsp; ...</pre>
</blockquote>
In the interests of clarity, it is probably a good idea to always be explicit
about <b>object </b>parameters in C functions.
<h3> <a name="CVarAndTypeDecls"></a>C variable and type definitions</h3>
The <b>cdef</b> statement is also used to declare C variables, either
local or module-level:
<blockquote> <pre>cdef int i, j, k<br>cdef float f, g[42], *h</pre>
</blockquote>
and C struct, union or enum types:
<blockquote> <pre>cdef struct Grail:<br>&nbsp;&nbsp;&nbsp; int age<br>&nbsp;&nbsp;&nbsp; float volume</pre>
<pre>cdef union Food:<br>&nbsp;&nbsp;&nbsp; char *spam<br>&nbsp;&nbsp;&nbsp; float *eggs</pre>
<pre>cdef enum CheeseType:<br>&nbsp;&nbsp;&nbsp; cheddar, edam,&nbsp;<br>&nbsp;&nbsp;&nbsp; camembert</pre>
<pre>cdef enum CheeseState:<br>&nbsp;&nbsp;&nbsp; hard = 1<br>&nbsp;&nbsp;&nbsp; soft = 2<br>&nbsp;&nbsp;&nbsp; runny = 3</pre>
</blockquote>
There is currently no special syntax for defining a constant, but you
can use an anonymous enum declaration for this purpose, for example,
<blockquote><tt>cdef enum:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; tons_of_spam = 3</tt></blockquote>
Note that the words <span style="font-family: monospace;">struct</span>, <span style="font-family: monospace;">union</span> and <span style="font-family: monospace;">enum</span> are used only when <i>defining</i> a type, not when referring to it. For example, to declare a variable pointing
to a Grail you would write
<blockquote> <pre>cdef Grail *gp</pre>
</blockquote>
and <i>not</i>
<blockquote> <pre>cdef struct Grail *gp <font color="#ed181e"># WRONG</font></pre>
</blockquote>
There is also a <b>ctypedef</b> statement for giving names to types, e.g.
<blockquote> <pre>ctypedef unsigned long ULong</pre>
<pre>ctypedef int *IntPtr<br></pre></blockquote>
<h3><a name="AutomaticTypeConversions"></a>Automatic type conversions</h3>
In most situations, automatic conversions will be performed for the
basic numeric and string types when a Python object is used in a
context requiring a C value, or vice versa. The following table
summarises the conversion possibilities.<br>
<br>
<table style="margin-left: auto; margin-right: auto; width: 10%; text-align: left;" border="1" cellpadding="4" cellspacing="0">
<tbody>
<tr>
<th style="vertical-align: top; width: 40%; white-space: nowrap;">C types<br>
</th>
<th style="vertical-align: top; width: 150px; white-space: nowrap;">From Python types<br>
</th>
<th style="vertical-align: top; width: 150px; white-space: nowrap;">To Python types<br>
</th>
</tr>
<tr>
<td colspan="1" rowspan="1" style="vertical-align: top; width: 40%; white-space: nowrap;">[unsigned] char<br>
[unsigned] short<br>
int, long</td>
<td colspan="1" rowspan="1" style="vertical-align: top; width: 150px; white-space: nowrap;">int, long<br>
</td>
<td colspan="1" rowspan="1" style="vertical-align: top; width: 150px; white-space: nowrap;">int<br>
</td>
</tr>
<tr>
</tr>
<tr>
<td colspan="1" rowspan="1" style="vertical-align: top; width: 40%; white-space: nowrap;">unsigned int<br>
unsigned long<br>
[unsigned] long long<br>
</td>
<td colspan="1" rowspan="1" style="vertical-align: top; white-space: nowrap;">int, long<br>
<br>
</td>
<td colspan="1" rowspan="1" style="vertical-align: top; white-space: nowrap;">long<br>
<br>
</td>
</tr>
<tr>
</tr>
<tr>
<td style="vertical-align: top; width: 40%; white-space: nowrap;">float, double, long double<br>
</td>
<td style="vertical-align: top; width: 150px; white-space: nowrap;">int, long, float<br>
</td>
<td style="vertical-align: top; width: 150px; white-space: nowrap;">float<br>
</td>
</tr>
<tr>
<td style="vertical-align: top; width: 40%; white-space: nowrap;">char *<br>
</td>
<td style="vertical-align: top; width: 150px; white-space: nowrap;">str<span style="font-style: italic;"></span><br>
</td>
<td style="vertical-align: top; width: 150px; white-space: nowrap;">str<br>
</td>
</tr>
</tbody>
</table>
<br>
<h4><a name="PyToCStringCaveats"></a>Caveats when using a Python string in a C context</h4>
You need to be careful when using a Python string in a context expecting a <span style="font-family: monospace;">char *</span>.
In this situation, a pointer to the contents of the Python string is
used, which is only valid as long as the Python string exists. So you
need to make sure that a reference to the original Python string is
held for as long as the C string is needed. If you can't guarantee that
the Python string will live long enough, you will need to copy the C
string.<br>
<br>
Pyrex detects and prevents <span style="font-style: italic;">some</span> mistakes of this kind. For instance, if you attempt something like<br>
<pre style="margin-left: 40px;">cdef char *s<br>s = pystring1 + pystring2</pre>
then Pyrex will produce the error message "<span style="font-weight: bold;">Obtaining char * from temporary Python value</span>".
The reason is that concatenating the two Python strings produces a new
Python string object that is referenced only by a temporary internal
variable that Pyrex generates. As soon as the statement has finished,
the temporary variable will be decrefed and the Python string
deallocated, leaving <span style="font-family: monospace;">s</span> dangling. Since this code could not possibly work, Pyrex refuses to compile it.<br>
<br>
The solution is to assign the result of the concatenation to a Python variable, and then obtain the char * from that, i.e.<br>
<pre style="margin-left: 40px;">cdef char *s<br>p = pystring1 + pystring2<br>s = p<br></pre>
It is then your responsibility to hold the reference <span style="font-family: monospace;">p</span> for as long as necessary.<br>
<br>
Keep in mind that the rules used to detect such errors are only
heuristics. Sometimes Pyrex will complain unnecessarily, and sometimes
it will fail to detect a problem that exists. Ultimately, you need to
understand the issue and be careful what you do.<br>
<blockquote>
</blockquote>
<h3> <a name="ScopeRules"></a>Scope rules</h3>
Pyrex determines whether a variable belongs to a local scope, the module
scope, or the built-in scope <i>completely statically.</i> As with Python,
assigning to a variable which is not otherwise declared implicitly declares
it to be a Python variable residing in the scope where it is assigned. Unlike
Python, however, a name which is referred to but not declared or assigned
is assumed to reside in the <i>builtin scope, </i>not the module scope.
Names added to the module dictionary at run time will not shadow such names.
<p>You can use a <b>global</b> statement at the module level to explicitly
declare a name to be a module-level name when there would otherwise not be
any indication of this, for example, </p>
<blockquote><tt>global __name__</tt> <br>
<tt>print __name__</tt></blockquote>
Without the <b>global</b> statement, the above would print the name of
the builtins module.<br>
<br>
Note: A consequence of these rules is that the module-level scope behaves
the same way as a Python local scope if you refer to a variable before assigning
to it. In particular, tricks such as the following will <i>not</i> work
in Pyrex:<br>
<blockquote> <pre>try:<br>&nbsp; x = True<br>except NameError:<br>&nbsp; True = 1<br></pre>
</blockquote>
because, due to the assignment, the True will always be looked up in the
module-level scope. You would have to do something like this instead:<br>
<blockquote> <pre>import __builtin__<br>try:<br> True = __builtin__.True<br>except AttributeError:<br> True = 1<br></pre>
</blockquote>
<hr width="100%">
<h3> <a name="StatsAndExprs"></a>Statements and expressions</h3>
Control structures and expressions follow Python syntax for the most part.
When applied to Python objects, they have the same semantics as in Python
(unless otherwise noted). Most of the Python operators can also be applied
to C values, with the obvious semantics.
<p>If Python objects and C values are mixed in an expression, conversions
are performed automatically between Python objects and C numeric or string
types. </p>
<p>Reference counts are maintained automatically for all Python objects, and
all Python operations are automatically checked for errors, with appropriate
action taken. </p>
<h4> <a name="ExprSyntaxDifferences"></a>Differences between C and Pyrex
expressions</h4>
There
are some differences in syntax and semantics between C expressions and
Pyrex expressions, particularly in the area of C constructs which have
no direct equivalent in Python.<br>
<ul>
<li>An integer literal without an <span style="font-family: monospace; font-weight: bold;">L</span> suffix is treated as a C constant, and will be truncated to whatever size your C compiler thinks appropriate. With an <span style="font-family: monospace; font-weight: bold;">L</span> suffix, it will be converted to Python long integer (even if it would be small enough to fit into a C int).<br>
<br>
</li>
<li> There is no <b><tt>-&gt;</tt></b> operator in Pyrex. Instead of <tt>p-&gt;x</tt>,
use <tt>p.x</tt></li>
&nbsp; <li> There is no <b><tt>*</tt></b> operator in Pyrex. Instead of
<tt>*p</tt>, use <tt>p[0]</tt></li>
&nbsp; <li> There is an <b><tt>&amp;</tt></b> operator, with the same semantics
as in C.</li>
&nbsp; <li> The null C pointer is called <b><tt>NULL</tt></b>, not 0 (and
<tt>NULL</tt> is a reserved word).</li>
&nbsp; <li> Character literals are written with a <b>c</b> prefix, for
example:</li>
<ul>
<pre>c'X'</pre>
</ul>
<li> Type casts are written <b><tt>&lt;type&gt;value</tt></b> , for example:</li>
<ul>
<pre>cdef char *p, float *q<br>p = &lt;char*&gt;q</pre>
</ul>
<i><b>Warning</b>: Don't attempt to use a typecast to convert between
Python and C data types -- it won't do the right thing. Leave Pyrex to perform
the conversion automatically.</i>
</ul>
<h4> <a name="ForFromLoop"></a>Integer for-loops</h4>
You should be aware that a for-loop such as
<blockquote><tt>for i in range(n):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
won't be very fast, even if <tt>i</tt> and <tt>n</tt> are declared as
C integers, because <tt>range</tt> is a Python function. For iterating over
ranges of integers, Pyrex has another form of for-loop:
<blockquote><tt>for i from 0 &lt;= i &lt; n:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
If the loop variable and the lower and upper bounds are all C integers,
this form of loop will be much faster, because Pyrex will translate it into
pure C code.
<p>Some things to note about the <tt>for-from</tt> loop: </p>
<ul>
<li> The target expression must be a variable name.</li>
<li> The name between the lower and upper bounds must be the same as
the target name.</li>
<li> The direction of iteration is determined by the relations. If they
are both from the set {<tt>&lt;</tt>, <tt>&lt;=</tt>} then it is upwards;
if they are both from the set {<tt>&gt;</tt>, <tt>&gt;=</tt>} then it is
downwards. (Any other combination is disallowed.)</li>
</ul>
Like other Python looping statements, <tt>break</tt> and <tt>continue</tt> may be used in the body, and the loop may have an <tt>else</tt> clause.
<h2> <hr width="100%"></h2>
<h3> <a name="ExceptionValues"></a>Error return values</h3>
If you don't do anything special, a function declared with <b>cdef</b> that does not return a Python object has no way of reporting Python exceptions
to its caller. If an exception is detected in such a function, a warning
message is printed and the exception is ignored.
<p>If you want a C function that does not return a Python object to be able
to propagate exceptions to its caller, you need to declare an <b>exception
value</b> for it. Here is an example: </p>
<blockquote><tt>cdef int spam() except -1:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
With this declaration, whenever an exception occurs inside <tt>spam</tt>,
it will immediately return with the value <tt>-1</tt>. Furthermore, whenever
a call to <tt>spam</tt> returns <tt>-1</tt>, an exception will be assumed
to have occurred and will be propagated.
<p>When you declare an exception value for a function, you should never explicitly
return that value. If all possible return values are legal and you can't
reserve one entirely for signalling errors, you can use an alternative form
of exception value declaration: </p>
<blockquote><tt>cdef int spam() except? -1:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
The "?" indicates that the value <tt>-1</tt> only indicates a <i>possible</i> error. In this case, Pyrex generates a call to <tt>PyErr_Occurred</tt>if the
exception value is returned, to make sure it really is an error.
<p>There is also a third form of exception value declaration: </p>
<blockquote><tt>cdef int spam() except *:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
This form causes Pyrex to generate a call to <tt>PyErr_Occurred</tt> after
<i>every</i> call to spam, regardless of what value it returns. If you have
a function returning <tt>void</tt> that needs to propagate errors, you will
have to use this form, since there isn't any return value to test.
<p>Some things to note: </p>
<ul>
<li> Currently, exception values can only declared for functions returning
an integer, float or pointer type, and the value must be a <i>literal</i>,
not an expression (although it can be negative). The only possible pointer
exception value is <tt>NULL</tt>. Void functions can only use the <tt>except
*</tt> form.</li>
<br>
&nbsp; <li> The exception value specification is part of the signature
of the function. If you're passing a pointer to a function as a parameter
or assigning it to a variable, the declared type of the parameter or variable
must have the same exception value specification (or lack thereof). Here
is an example of a pointer-to-function declaration with an exception value:</li>
<ul>
<pre><tt>int (*grail)(int, char *) except -1</tt></pre>
</ul>
<li> You don't need to (and shouldn't) declare exception values for functions
which return Python objects. Remember that a function with no declared return
type implicitly returns a Python object.</li>
</ul>
<h4> <a name="CheckingReturnValues"></a>Checking return values of non-Pyrex
functions</h4>
It's important to understand that the <tt>except</tt> clause does <i>not</i> cause an error to be <i>raised</i> when the specified value is returned. For
example, you can't write something like
<blockquote> <pre>cdef extern FILE *fopen(char *filename, char *mode) except NULL <font color="#ed181e"># WRONG!</font></pre>
</blockquote>
and expect an exception to be automatically raised if a call to fopen
returns NULL. The except clause doesn't work that way; its only purpose
is for <i>propagating</i> exceptions that have already been raised, either
by a Pyrex function or a C function that calls Python/C API routines. To
get an exception from a non-Python-aware function such as fopen, you will
have to check the return value and raise it yourself, for example,
<blockquote> <pre>cdef FILE *p<br>p = fopen("spam.txt", "r")<br>if p == NULL:<br>&nbsp;&nbsp;&nbsp; raise SpamError("Couldn't open the spam file")</pre>
</blockquote>
<h4> <hr width="100%"></h4>
<h4> <a name="IncludeStatement"></a>The <tt>include</tt> statement</h4>
For convenience, a large Pyrex module can be split up into a number of
files which are put together using the <b>include</b> statement, for example
<blockquote> <pre>include "spamstuff.pxi"</pre>
</blockquote>
The contents of the named file are textually included at that point. The
included file can contain any complete top-level Pyrex statements, including
other <b>include</b> statements. The <b>include</b> statement itself can
only appear at the top level of a file.
<p>The <b>include</b> statement can also be used in conjunction with <a href="#PublicDecls"><b>public</b> declarations</a> to make C functions and
variables defined in one Pyrex module accessible to another. However, note
that some of these uses have been superseded by the facilities described
in <a href="sharing.html">Sharing Declarations Between Pyrex Modules</a>,
and it is expected that use of the <b>include</b> statement for this purpose
will be phased out altogether in future versions. </p>
<h2> <hr width="100%"><a name="InterfacingWithExternal"></a>Interfacing with External
C Code
<hr width="100%"></h2>
One of the main uses of Pyrex is wrapping existing libraries of C code.
This is achieved by using <a href="#ExternDecls">external declarations</a> to declare the C functions and variables from the library that you want to
use.
<p>You can also use <a href="#PublicDecls">public declarations</a> to make
C functions and variables defined in a Pyrex module available to external
C code. The need for this is expected to be less frequent, but you might
want to do it, for example, if you are embedding Python in another application
as a scripting language. Just as a Pyrex module can be used as a bridge to
allow Python code to call C code, it can also be used to allow C code to
call Python code. </p>
<h3> <a name="ExternDecls"></a>External declarations</h3>
By default, C functions and variables declared at the module level are
local to the module (i.e. they have the C <b>static</b> storage class). They
can also be declared <b>extern</b> to specify that they are defined elsewhere,
for example:
<blockquote> <pre>cdef extern int spam_counter</pre>
<pre>cdef extern void order_spam(int tons)</pre>
</blockquote>
<blockquote> </blockquote>
<h4> <a name="ReferencingHeaders"></a>Referencing C header files</h4>
When you use an extern definition on its own as in the examples above,
Pyrex includes a declaration for it in the generated C file. This can cause
problems if the declaration doesn't exactly match the declaration that will
be seen by other C code. If you're wrapping an existing C library, for example,
it's important that the generated C code is compiled with exactly the same
declarations as the rest of the library.
<p>To achieve this, you can tell Pyrex that the declarations are to be found
in a C header file, like this: </p>
<blockquote> <pre>cdef extern from "spam.h":</pre>
<pre>&nbsp;&nbsp;&nbsp; int spam_counter</pre>
<pre>&nbsp;&nbsp;&nbsp; void order_spam(int tons)</pre>
</blockquote>
The <b>cdef extern from</b> clause does three things:
<ol>
<li> It directs Pyrex to place a <b>#include</b> statement for the named
header file in the generated C code.<br>
</li>
&nbsp; <li> It prevents Pyrex from generating any C code for the declarations
found in the associated block.<br>
</li>
&nbsp; <li> It treats all declarations within the block as though they
started with <b>cdef extern</b>.</li>
</ol>
It's important to understand that Pyrex does <i>not</i> itself read the
C header file, so you still need to provide Pyrex versions of any declarations
from it that you use. However, the Pyrex declarations don't always have to
exactly match the C ones, and in some cases they shouldn't or can't. In particular:
<ol>
<li> Don't use <b>const</b>. Pyrex doesn't know anything about const,
so just leave it out. Most of the time this shouldn't cause any problem,
although on rare occasions you might have to use a cast.<sup><a href="#Footnote1"> 1</a></sup><br>
</li>
&nbsp; <li> Leave out any platform-specific extensions to C declarations
such as <b>__declspec()</b>.<br>
</li>
&nbsp; <li> If the header file declares a big struct and you only want
to use a few members, you only need to declare the members you're interested
in. Leaving the rest out doesn't do any harm, because the C compiler will
use the full definition from the header file.<br>
<br>
In some cases, you might not need <i>any</i> of the struct's members, in
which case you can just put <tt>pass</tt> in the body of the struct declaration,
e.g.<br>
<br>
<tt>&nbsp; &nbsp; cdef extern from "foo.h":<br>
&nbsp; &nbsp; &nbsp; &nbsp; struct spam:<br>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pass</tt><br>
<br>
Note that you can only do this inside a <b>cdef extern from</b> block; struct
declarations anywhere else must be non-empty.<br>
<br>
</li>
<li> If the header file uses typedef names such as <b>size_t </b>to refer
to platform-dependent flavours of numeric types, you will need a corresponding
<b>ctypedef</b> statement, but you don't need to match the type exactly,
just use something of the right general kind (int, float, etc). For example,</li>
<ol>
<pre>ctypedef int size_t</pre>
</ol>
will work okay whatever the actual size of a size_t is (provided the header
file defines it correctly). <br>
&nbsp; <li> If the header file uses macros to define constants, translate
them into a dummy <b>enum</b> declaration.<br>
</li>
&nbsp; <li> If the header file defines a function using a macro, declare
it as though it were an ordinary function, with appropriate argument and
result types.</li>
</ol>
A few more tricks and tips:
<ul>
<li> If you want to include a C header because it's needed by another
header, but don't want to use any declarations from it, put <tt><font size="+1">pass</font></tt> in the extern-from block:</li>
</ul>
<ul>
<ul>
<tt>cdef extern from "spam.h":</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; pass</tt> </ul>
</ul>
<ul>
<li> If you want to include some external declarations, but don't want
to specify a header file (because it's included by some other header that
you've already included) you can put <tt>*</tt> in place of the header file
name:</li>
</ul>
<blockquote> <blockquote><tt>cdef extern from *:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
</blockquote>
<h4> <a name="StructDeclStyles"></a>Styles of struct, union and enum declaration</h4>
There are two main ways that structs, unions and enums can be declared
in C header files: using a tag name, or using a typedef. There are also some
variations based on various combinations of these.
<p>It's important to make the Pyrex declarations match the style used in the
header file, so that Pyrex can emit the right sort of references to the type
in the code it generates. To make this possible, Pyrex provides two different
syntaxes for declaring a struct, union or enum type. The style introduced
above corresponds to the use of a tag name. To get the other style, you prefix
the declaration with <b>ctypedef</b>, as illustrated below. </p>
<p>The following table shows the various possible styles that can be found
in a header file, and the corresponding Pyrex declaration that you should
put in the <b>cdef exern from </b>block. Struct declarations are used as
an example; the same applies equally to union and enum declarations. </p>
<p>Note that in all the cases below, you refer to the type in Pyrex code simply
as <tt><font size="+1">Foo</font></tt>, not <tt><font size="+1">struct Foo</font></tt>.
<br>
&nbsp; <table cellpadding="5">
<tbody>
<tr bgcolor="#8cbc1c" valign="top">
<td bgcolor="#8cbc1c">&nbsp;</td>
<td bgcolor="#ff9933" nowrap="nowrap"><b>C code</b></td>
<td bgcolor="#66cccc" valign="top"><b>Possibilities for corresponding
Pyrex code</b></td>
<td bgcolor="#99cc33" valign="top"><b>Comments</b></td>
</tr>
<tr bgcolor="#8cbc1c" valign="top">
<td>1</td>
<td bgcolor="#ff9900"><tt>struct Foo {</tt> <br>
<tt>&nbsp; ...</tt> <br>
<tt>};</tt></td>
<td bgcolor="#66cccc"><tt>cdef struct Foo:</tt> <br>
<tt>&nbsp; ...</tt></td>
<td>Pyrex will refer to the type as <tt>struct Foo </tt>in the generated
C code<tt>.</tt></td>
</tr>
<tr bgcolor="#8cbc1c" valign="top">
<td valign="top">2</td>
<td bgcolor="#ff9900" nowrap="nowrap"><tt>typedef struct {</tt> <br>
<tt>&nbsp; ...</tt> <br>
<tt>} Foo;</tt></td>
<td bgcolor="#66cccc" valign="top"><tt>ctypedef struct Foo:</tt> <br>
<tt>&nbsp; ...</tt></td>
<td valign="top">Pyrex will refer to the type simply as <tt>Foo</tt>
in the generated C code.</td>
</tr>
<tr bgcolor="#8cbc1c" valign="top">
<td rowspan="2">3</td>
<td rowspan="2" bgcolor="#ff9900" nowrap="nowrap"><tt>typedef struct
foo {</tt> <br>
<tt>&nbsp; ...</tt> <br>
<tt>} Foo;</tt></td>
<td bgcolor="#66cccc" nowrap="nowrap" valign="top"><tt>cdef struct foo:</tt> <br>
<tt>&nbsp; ...</tt> <br>
<tt>ctypedef foo Foo #optional</tt></td>
<td rowspan="2" valign="top">If the C header uses both a tag and a typedef
with <i>different</i> names, you can use either form of declaration in Pyrex
(although if you need to forward reference the type, you'll have to use
the first form).</td>
</tr>
<tr>
<td bgcolor="#66cccc"><tt>ctypedef struct Foo:</tt> <br>
<tt>&nbsp; ...</tt></td>
</tr>
<tr bgcolor="#8cbc1c" valign="top">
<td>4</td>
<td bgcolor="#ff9900" nowrap="nowrap"><tt>typedef struct Foo {</tt> <br>
<tt>&nbsp; ...</tt> <br>
<tt>} Foo;</tt></td>
<td bgcolor="#66cccc" valign="top"><tt>cdef struct Foo:</tt> <br>
<tt>&nbsp; ...</tt></td>
<td>If the header uses the <i>same</i> name for the tag and the typedef,
you won't be able to include a <b>ctypedef</b> for it -- but then, it's not
necessary.</td>
</tr>
</tbody> </table>
</p>
<h4> <a name="AccessingAPI"></a>Accessing Python/C API routines</h4>
One particular use of the <b>cdef extern from</b> statement is for gaining
access to routines in the Python/C API. For example,
<blockquote> <pre>cdef extern from "Python.h":</pre>
<pre>&nbsp;&nbsp;&nbsp; object PyString_FromStringAndSize(char *s, int len)</pre>
</blockquote>
will allow you to create Python strings containing null bytes.
<p> </p>
<hr width="100%">
<h3> <a name="CNameSpecs"></a>Resolving naming conflicts - C name specifications</h3>
Each Pyrex module has a single module-level namespace for both Python
and C names. This can be inconvenient if you want to wrap some external
C functions and provide the Python user with Python functions of the same
names.
<p>Pyrex 0.8 provides a couple of different ways of solving this problem.
The best way, especially if you have many C functions to wrap, is probably
to put the extern C function declarations into a different namespace using
the facilities described in the section on <a href="sharing.html">sharing
declarations between Pyrex modules</a>. </p>
<p>The other way is to use a <b>c name specification</b> to give different
Pyrex and C names to the C function. Suppose, for example, that you want
to wrap an external function called <tt>eject_tomato</tt>. If you declare
it as </p>
<blockquote> <pre>cdef extern void c_eject_tomato "eject_tomato" (float speed)</pre>
</blockquote>
then its name inside the Pyrex module will be <tt>c_eject_tomato</tt>,
whereas its name in C will be <tt>eject_tomato</tt>. You can then wrap it
with
<blockquote> <pre>def eject_tomato(speed):<br>&nbsp; c_eject_tomato(speed)</pre>
</blockquote>
so that users of your module can refer to it as <tt>eject_tomato</tt>.
<p>Another use for this feature is referring to external names that happen
to be Pyrex keywords. For example, if you want to call an external function
called <tt>print</tt>, you can rename it to something else in your Pyrex
module. </p>
<p>As well as functions, C names can be specified for variables, structs,
unions, enums, struct and union members, and enum values. For example, </p>
<blockquote> <pre>cdef extern int one "ein", two "zwei"<br>cdef extern float three "drei"<br><br>cdef struct spam "SPAM":<br>&nbsp; int i "eye"</pre>
<tt>cdef enum surprise "inquisition":</tt> <br>
<tt>&nbsp; first "alpha"</tt> <br>
<tt>&nbsp; second "beta" = 3</tt></blockquote>
<hr width="100%">
<h3> <a name="PublicDecls"></a>Public Declarations</h3>
You can make C variables and functions defined in a Pyrex module accessible
to external C code (or another Pyrex module) using the <b><tt>public</tt></b> keyword, as follows:
<blockquote><tt>cdef public int spam # public variable declaration</tt> <p><tt>cdef public void grail(int num_nuns): # public function declaration</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt></p>
</blockquote>
If there are any <tt>public</tt> declarations in a Pyrex module, a <b>.h</b> file is generated containing equivalent C declarations for inclusion in other
C code.
<p>Pyrex also generates a <b>.pxi</b> file containing Pyrex versions of the
declarations for inclusion in another Pyrex module using the <b><a href="#IncludeStatement">include</a></b> statement. If you use this, you
will need to arrange for the module using the declarations to be linked
against the module defining them, and for both modules to be available to
the dynamic linker at run time. I haven't tested this, so I can't say how
well it will work on the various platforms. </p>
<blockquote>NOTE: If all you want to export is an extension type, there is
now a better way -- see <a href="sharing.html">Sharing Declarations Between
Pyrex Modules</a>.</blockquote>
<h2> <hr width="100%">Extension Types
<hr width="100%"></h2>
One of the most powerful features of Pyrex is the ability to easily create
new built-in Python types, called <b>extension types</b>. This is a major
topic in itself, so there is a&nbsp; <a href="extension_types.html">separate
page</a> devoted to it.
<h2> <hr width="100%">Sharing Declarations Between Pyrex Modules
<hr width="100%"></h2>
Pyrex 0.8 introduces a substantial new set of facilities allowing a Pyrex
module to easily import and use C declarations and extension types from another
Pyrex module. You can now create a set of co-operating Pyrex modules just
as easily as you can create a set of co-operating Python modules. There is
a <a href="sharing.html">separate page</a> devoted to this topic.
<h2> <hr width="100%"><a name="Limitations"></a>Limitations
<hr width="100%"></h2>
<h3> <a name="Unsupported"></a>Unsupported Python features</h3>
Pyrex is not quite a full superset of Python. The following restrictions
apply:
<blockquote> <li> Function definitions (whether using <b>def</b> or <b>cdef</b>)
cannot be nested within other function definitions.<br>
</li>
&nbsp; <li> Class definitions can only appear at the top level of a module,
not inside a function.<br>
</li>
&nbsp; <li> The<tt> import *</tt> form of import is not allowed anywhere
(other forms of the import statement are fine, though).<br>
</li>
&nbsp; <li> Generators cannot be defined in Pyrex.<br>
<br>
</li>
<li> The <tt>globals()</tt> and <tt>locals()</tt> functions cannot be
used.</li>
</blockquote>
The above restrictions will most likely remain, since removing them would
be difficult and they're not really needed for Pyrex's intended applications.
<p>There are also some temporary limitations, which may eventually be lifted, including:
</p>
<blockquote> <li> Class and function definitions cannot be placed inside
control structures.<br>
</li>
&nbsp; <li> In-place arithmetic operators (+=, etc) are not yet supported.<br>
</li>
&nbsp; <li> List comprehensions are not yet supported.<br>
</li>
&nbsp; <li> There is no support for Unicode.<br>
</li>
&nbsp; <li> Special methods of extension types cannot have functioning
docstrings.<br>
<br>
</li>
<li> The use of string literals as comments is not recommended at present,
because Pyrex doesn't optimize them away, and won't even accept them in
places where executable statements are not allowed.</li>
</blockquote>
<h3> <a name="SemanticDifferences"></a>Semantic differences between Python
and Pyrex</h3>
<h4> Behaviour of class scopes</h4>
In Python, referring to a method of a class inside the class definition,
i.e. while the class is being defined, yields a plain function object, but
in Pyrex it yields an unbound method<sup><font size="-2"><a href="#Footnote2">2</a></font></sup>. A consequence of this is that the
usual idiom for using the classmethod and staticmethod functions, e.g.
<blockquote> <pre>class Spam:</pre>
<pre>&nbsp; def method(cls):<br>&nbsp;&nbsp;&nbsp; ...</pre>
<pre>&nbsp; method = classmethod(method)</pre>
</blockquote>
will not work in Pyrex. This can be worked around by defining the function
<i>outside</i> the class, and then assigning the result of classmethod or
staticmethod inside the class, i.e.
<blockquote> <pre>def Spam_method(cls):<br>&nbsp; ...</pre>
<pre>class Spam:</pre>
<pre>&nbsp; method = classmethod(Spam_method)</pre>
</blockquote>
<h1> <hr width="100%"><font size="+0">Footnotes</font> <hr width="100%"></h1>
<a name="Footnote1"></a>1. A problem with const could arise if you have
something like
<blockquote> <pre>cdef extern from "grail.h":<br>&nbsp; char *nun</pre>
</blockquote>
where grail.h actually contains
<blockquote> <pre>extern const char *nun;</pre>
</blockquote>
and you do
<blockquote> <pre>cdef void languissement(char *s):<br>&nbsp; #something that doesn't change s</pre>
<pre>...</pre>
<pre>languissement(nun)</pre>
</blockquote>
which will cause the C compiler to complain. You can work around it by
casting away the constness:
<blockquote> <pre>languissement(&lt;char *&gt;nun)</pre>
</blockquote>
<hr width="100%"><a name="Footnote2"></a>2. The reason for the different behaviour
of class scopes is that Pyrex-defined Python functions are PyCFunction objects,
not PyFunction objects, and are not recognised by the machinery that creates
a bound or unbound method when a function is extracted from a class. To get
around this, Pyrex wraps each method in an unbound method object itself before
storing it in the class's dictionary. <br>
&nbsp; <br>
<br>
</body></html>
\ No newline at end of file
#include "Python.h" static PyObject *__Pyx_UnpackItem(PyObject *, int); static int __Pyx_EndUnpack(PyObject *, int); static int __Pyx_PrintItem(PyObject *); static int __Pyx_PrintNewline(void); static void __Pyx_ReRaise(void); static void __Pyx_RaiseWithTraceback(PyObject *, PyObject *, PyObject *); static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); static PyObject *__Pyx_GetExcValue(void); static PyObject *__Pyx_GetName(PyObject *dict, char *name); static PyObject *__pyx_m; static PyObject *__pyx_d; static PyObject *__pyx_b; PyObject *__pyx_f_primes(PyObject *__pyx_self, PyObject *__pyx_args); /*proto*/ PyObject *__pyx_f_primes(PyObject *__pyx_self, PyObject *__pyx_args) { int __pyx_v_kmax; int __pyx_v_n; int __pyx_v_k; int __pyx_v_i; int (__pyx_v_p[1000]); PyObject *__pyx_v_result; PyObject *__pyx_r; PyObject *__pyx_1 = 0; int __pyx_2; int __pyx_3; int __pyx_4; PyObject *__pyx_5 = 0; PyObject *__pyx_6 = 0; if (!PyArg_ParseTuple(__pyx_args, "i", &__pyx_v_kmax)) return 0; __pyx_v_result = Py_None; Py_INCREF(__pyx_v_result); /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":2 */ /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":3 */ /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":4 */ __pyx_1 = PyList_New(0); if (!__pyx_1) goto __pyx_L1; Py_DECREF(__pyx_v_result); __pyx_v_result = __pyx_1; __pyx_1 = 0; /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":5 */ __pyx_2 = (__pyx_v_kmax > 1000); if (__pyx_2) { /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":6 */ __pyx_v_kmax = 1000; goto __pyx_L2; } __pyx_L2:; /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":7 */ __pyx_v_k = 0; /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":8 */ __pyx_v_n = 2; /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":9 */ while (1) { __pyx_L3:; __pyx_2 = (__pyx_v_k < __pyx_v_kmax); if (!__pyx_2) break; /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":10 */ __pyx_v_i = 0; /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":11 */ while (1) { __pyx_L5:; if (__pyx_3 = (__pyx_v_i < __pyx_v_k)) { __pyx_3 = ((__pyx_v_n % (__pyx_v_p[__pyx_v_i])) != 0); } if (!__pyx_3) break; /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":12 */ __pyx_v_i = (__pyx_v_i + 1); } __pyx_L6:; /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":13 */ __pyx_4 = (__pyx_v_i == __pyx_v_k); if (__pyx_4) { /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":14 */ (__pyx_v_p[__pyx_v_k]) = __pyx_v_n; /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":15 */ __pyx_v_k = (__pyx_v_k + 1); /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":16 */ __pyx_1 = PyObject_GetAttrString(__pyx_v_result, "append"); if (!__pyx_1) goto __pyx_L1; __pyx_5 = PyInt_FromLong(__pyx_v_n); if (!__pyx_5) goto __pyx_L1; __pyx_6 = PyTuple_New(1); if (!__pyx_6) goto __pyx_L1; PyTuple_SET_ITEM(__pyx_6, 0, __pyx_5); __pyx_5 = 0; __pyx_5 = PyObject_CallObject(__pyx_1, __pyx_6); if (!__pyx_5) goto __pyx_L1; Py_DECREF(__pyx_6); __pyx_6 = 0; Py_DECREF(__pyx_5); __pyx_5 = 0; goto __pyx_L7; } __pyx_L7:; /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":17 */ __pyx_v_n = (__pyx_v_n + 1); } __pyx_L4:; /* "ProjectsA:Python:Pyrex:Demos:primes.pyx":18 */ Py_INCREF(__pyx_v_result); __pyx_r = __pyx_v_result; goto __pyx_L0; __pyx_r = Py_None; Py_INCREF(__pyx_r); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_5); Py_XDECREF(__pyx_6); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_result); return __pyx_r; } static struct PyMethodDef __pyx_methods[] = { {"primes", (PyCFunction)__pyx_f_primes, METH_VARARGS, 0}, {0, 0, 0, 0} }; void initprimes(void); /*proto*/ void initprimes(void) { __pyx_m = Py_InitModule4("primes", __pyx_methods, 0, 0, PYTHON_API_VERSION); __pyx_d = PyModule_GetDict(__pyx_m); __pyx_b = PyImport_AddModule("__builtin__"); PyDict_SetItemString(__pyx_d, "__builtins__", __pyx_b); }/* Runtime support code */
\ No newline at end of file
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Mozilla/4.61 (Macintosh; I; PPC) [Netscape]"><title>Sharing Declarations Between Pyrex Modules</title></head>
<body>
<h1> <hr width="100%">Sharing Declarations Between Pyrex Modules
<hr width="100%"></h1>
This section describes a new set of facilities introduced in Pyrex 0.8
for making C declarations and extension types in one Pyrex module available
for use in another Pyrex module. These facilities are closely modelled on
the Python import mechanism, and can be thought of as a compile-time version
of it.
<h2> Contents</h2>
<ul>
<li> <a href="#DefAndImpFiles">Definition and Implementation files</a></li>
<ul>
<li> <a href="#WhatDefFileContains">What a Definition File contains</a></li>
<li> <a href="#WhatImpFileContains">What an Implementation File contains</a></li>
</ul>
<li> <a href="#CImportStatement">The <tt>cimport</tt> statement</a></li>
<ul>
<li> <a href="#SearchPaths">Search paths for definition files</a></li>
<li> <a href="#ResolvingNamingConflicts">Using <tt>cimport</tt> to resolve
naming conflicts</a></li>
</ul>
<li> <a href="#SharingExtensionTypes">Sharing extension types</a></li>
</ul>
<h2> <a name="DefAndImpFiles"></a>Definition and Implementation files</h2>
A Pyrex module can be split into two parts: a <i>definition file</i> with
a <tt>.pxd</tt> suffix, containing C declarations that are to be available
to other Pyrex modules, and an <i>implementation file</i> with a <tt>.pyx</tt>
suffix, containing everything else. When a module wants to use something
declared in another module's definition file, it imports it using the <a href="#CImportStatement"><b>cimport</b> statement</a>.
<h3> <a name="WhatDefFileContains"></a>What a Definition File contains</h3>
A definition file can contain:
<ul>
<li> Any kind of C type declaration.</li>
<li> <b>extern</b> C function or variable declarations.</li>
<li> The definition part of an extension type (<a href="#SharingExtensionTypes">see below</a>).</li>
</ul>
It cannot currently contain any non-extern C function or variable declarations
(although this may be possible in a future version).
<p>It cannot contain the implementations of any C or Python functions, or
any Python class definitions, or any executable statements. </p>
<blockquote>NOTE: You don't need to (and shouldn't) declare anything in a
declaration file <b>public</b> in order to make it available to other Pyrex
modules; its mere presence in a definition file does that. You only need a
public declaration if you want to make something available to external C code.</blockquote>
<h3> <a name="WhatImpFileContains"></a>What an Implementation File contains</h3>
An implementation file can contain any kind of Pyrex statement, although
there are some restrictions on the implementation part of an extension type
if the corresponding definition file also defines that type (see below).
<h2> <a name="CImportStatement"></a>The <tt>cimport</tt> statement</h2>
The <b>cimport</b> statement is used in a definition or implementation
file to gain access to names declared in another definition file. Its syntax
exactly parallels that of the normal Python import statement:
<blockquote><tt>cimport </tt><i>module</i><tt> [, </tt><i>module</i><tt>...]</tt></blockquote>
<blockquote><tt>from </tt><i>module</i><tt> cimport </tt><i>name</i><tt>
[as </tt><i>name</i><tt>] [, </tt><i>name</i><tt> [as </tt><i>name</i><tt>]
...]</tt></blockquote>
Here is an example. The file on the left is a definition file which exports
a C data type. The file on the right is an implementation file which imports
and uses it. <br>
&nbsp; <table cellpadding="5" cols="2" width="100%">
<tbody>
<tr>
<td bgcolor="#ffcc00" width="40%"><b><tt>dishes.pxd</tt></b></td>
<td bgcolor="#5dbaca"><b><tt>restaurant.pyx</tt></b></td>
</tr>
<tr align="left" valign="top">
<td bgcolor="#ffcc18" width="40%"><tt>cdef enum otherstuff:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; sausage, eggs, lettuce</tt> <p><tt>cdef struct spamdish:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; int oz_of_spam</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; otherstuff filler</tt></p>
</td>
<td bgcolor="#5dbaca"><tt>cimport dishes</tt> <br>
<tt>from dishes cimport spamdish</tt> <p><tt>cdef void prepare(spamdish *d):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; d.oz_of_spam = 42</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; d.filler = dishes.sausage</tt> </p>
<p><tt>def serve():</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; spamdish d</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; prepare(&amp;d)</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; print "%d oz spam, filler no. %d" % \</tt>
<br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (d-&gt;oz_of_spam,
d-&gt;otherstuff)</tt></p>
</td>
</tr>
</tbody> </table>
<p>It is important to understand that the <b>cimport</b> statement can <i>only</i>
be used to import C data types, external C functions and variables, and extension
types. It cannot be used to import any Python objects, and (with one exception)
it doesn't imply any Python import at run time. If you want to refer to any
Python names from a module that you have cimported, you will have to include
a regular <b>import</b> statement for it as well. </p>
<p>The exception is that when you use <b>cimport</b> to import an extension
type, its type object is imported at run time and made available by the
name under which you imported it. Using <b>cimport</b> to import extension
types is covered in more detail <a href="#SharingExtensionTypes">below</a>.
</p>
<h3> <a name="SearchPaths"></a>Search paths for definition files</h3>
When you <b>cimport</b> a module called <tt>modulename</tt>, the Pyrex
compiler searches for a file called <tt>modulename.pxd</tt> along the search
path for include files, as specified by <b>-I</b> command line options.
<p>Also, whenever you compile a file <tt>modulename.pyx</tt>, the corresponding
definition file <tt>modulename.pxd</tt> is first searched for along the
same path, and if found, it is processed before processing the <tt>.pyx</tt>
file. </p>
<h3> <a name="ResolvingNamingConflicts"></a>Using cimport to resolve naming
conflicts</h3>
The cimport mechanism provides a clean and simple way to solve the problem
of wrapping external C functions with Python functions of the same name.
All you need to do is put the extern C declarations into a .pxd file for
an imaginary module, and cimport that module. You can then refer to the C
functions by qualifying them with the name of the module. Here's an example:
<br>
&nbsp; <table cellpadding="5" cols="2" width="100%">
<tbody>
<tr>
<td bgcolor="#ffcc00" width="50%"><b><tt>c_lunch.pxd</tt></b></td>
<td bgcolor="#5dbaca"><b><tt>lunch.pyx</tt></b></td>
</tr>
<tr align="left" valign="top">
<td bgcolor="#ffcc18" width="50%"><tt>cdef extern from "lunch.h":</tt>
<br>
<tt>&nbsp;&nbsp;&nbsp; void eject_tomato(float)</tt></td>
<td bgcolor="#5dbaca"><tt>cimport c_lunch</tt> <p><tt>def eject_tomato(float speed):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; c_lunch.eject_tomato(speed)</tt></p>
</td>
</tr>
</tbody> </table>
<p>You don't need any <tt>c_lunch.pyx</tt> file, because the only things
defined in <tt>c_lunch.pxd</tt> are extern C entities. There won't be any
actual <tt>c_lunch</tt> module at run time, but that doesn't matter -- <tt>c_lunch</tt>
has done its job of providing an additional namespace at compile time. </p>
<h2> <a name="SharingExtensionTypes"></a>Sharing Extension Types</h2>
An extension type declaration can also be split into two parts, one in
a definition file and the other in the corresponding implementation file.
<br>
<br>
The definition part of the extension type can only declare C attributes
and C methods, not Python methods, and it must declare <i>all</i> of that
type's C attributes and C methods.<br>
<br>
The implementation part must implement all of the C methods declared in
the definition part, and may not add any further C attributes. It may also
define Python methods.
<p>Here is an example of a module which defines and exports an extension
type, and another module which uses it. <br>
&nbsp; <table cellpadding="5" cols="2" width="100%">
<tbody>
<tr>
<td bgcolor="#ffcc18" width="30%"><b><tt>Shrubbing.pxd</tt></b></td>
<td bgcolor="#5dbaca" width="50%"><b><tt>Shrubbing.pyx</tt></b></td>
</tr>
<tr align="left" valign="top">
<td bgcolor="#ffcc18" width="30%"><tt>cdef class Shrubbery:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; cdef int width</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; cdef int length</tt></td>
<td bgcolor="#5dbaca" width="50%"><tt>cdef class Shrubbery:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; def __new__(self, int w, int l):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.width = w</tt>
<br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.length = l</tt>
<p><tt>def standard_shrubbery():</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; return Shrubbery(3, 7)</tt></p>
</td>
</tr>
<tr>
<td colspan="2" bgcolor="#8cbc1c" width="30%"><b><tt>Landscaping.pyx</tt></b></td>
</tr>
<tr>
<td colspan="2" bgcolor="#99cc00" width="30%"><tt>cimport Shrubbing</tt>
<br>
<tt>import Shrubbing</tt> <p><tt>cdef Shrubbing.Shrubbery sh</tt> <br>
<tt>sh = Shrubbing.standard_shrubbery()</tt> <br>
<tt>print "Shrubbery size is %d x %d" % (sh.width, sh.height)</tt>
<br>
&nbsp;</p>
</td>
</tr>
</tbody> </table>
</p>
<p>Some things to note about this example: </p>
<ul>
<li> There is a <tt>cdef class Shrubbery</tt> declaration in both Shrubbing.pxd
and Shrubbing.pyx. When the Shrubbing module is compiled, these two declarations
are combined into one.</li>
&nbsp; <li> In Landscaping.pyx, the <tt>cimport Shrubbing</tt> declaration
allows us to refer to the Shrubbery type as <tt>Shrubbing.Shrubbery</tt>.
But it doesn't bind the name <tt>Shrubbery</tt> in Landscaping's module namespace
at run time, so to access <tt>Shrubbery.standard_shrubbery</tt> we also
need to <tt>import Shrubbing</tt>.</li>
</ul>
<hr width="100%">Back to the <a href="overview.html">Language Overview</a>
<br>
<br>
</body></html>
\ No newline at end of file
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Mozilla/4.61 (Macintosh; I; PPC) [Netscape]"><title>Special Methods of Extenstion Types</title></head>
<body>
<h1> <hr width="100%">Special Methods of Extension Types
<hr width="100%"></h1>
This page describes the special methods currently supported by Pyrex extension
types. A complete list of all the special methods appears in the table at
the bottom. Some of these methods behave differently from their Python counterparts
or have no direct Python counterparts, and require special mention.
<p><span style="font-weight: bold;">Note:</span><i> Everything said on this page applies only to </i><span style="font-weight: bold;">extension</span><i style="font-weight: bold;">
</i><span style="font-weight: bold;">types</span><i>, defined with the </i><span style="font-weight: bold; font-family: monospace;">cdef class</span><i> statement. It doesn't apply&nbsp;
to classes defined with the Python </i><span style="font-family: monospace;">class</span><i><span style="font-family: monospace;"> </span>statement, where the normal
Python rules apply.</i> </p>
<h2><small>Declaration</small></h2>Special methods of extension types must be declared with <span style="font-family: monospace; font-weight: bold;">def</span>, <span style="font-style: italic;">not</span> <span style="font-family: monospace;">cdef</span>.<br>
<h2><font size="+1">Docstrings</font></h2>
Currently, docstrings are not fully supported in special methods of extension
types. You can place a docstring in the source to serve as a comment, but
it won't show up in the corresponding <span style="font-family: monospace;">__doc__</span> attribute at run time. (This
is a Python limitation -- there's nowhere in the PyTypeObject data structure
to put such docstrings.)
<h2> <font size="+1">Initialisation methods: <tt>__new__</tt> and <tt>__init__</tt></font></h2>
There are two methods concerned with initialising the object<tt>.</tt>
<p>The <b><tt>__new__</tt></b> method is where you should perform basic C-level
initialisation of the object, including allocation of any C data structures
that your object will own. You need to be careful what you do in the __new__
method, because the object may not yet be a valid Python object when it is
called. Therefore, you must not invoke any Python operations which might touch
the object; in particular, do not try to call any of its methods. </p>
<p>Unlike the corresponding method in Python, your <tt>__new__</tt> method
is <i>not</i> responsible for <i>creating</i> the object. By the time your
<tt>__new__</tt> method is called, memory has been allocated for the object
and any C attributes it has have been initialised to 0 or null. (Any Python
attributes have also been initialised to <tt>None</tt>, but you probably shouldn't
rely on that.) Your <tt>__new__</tt> method is guaranteed to be called exactly
once.<br>
<br>
If your extension type has a base type, the <tt>__new__</tt> method of the
base type is automatically called <i>before</i> your <tt>__new__</tt> method
is called; you cannot explicitly call the inherited <tt>__new__</tt> method.
If you need to pass a modified argument list to the base type, you will have
to do the relevant part of the initialisation in the <tt>__init__</tt> method
instead (where the normal rules for calling inherited methods apply).<br>
</p>
<p>Note that the first parameter of the <tt>__new__</tt> method is the object
to be initialised, not the class of the object as it is in Python. </p>
<p>Any initialisation which cannot safely be done in the <tt>__new__</tt>
method should be done in the <b><tt>__init__</tt></b> method. By the time
<tt>__init__</tt> is called, the object is a fully valid Python object and
all operations are safe. Under some circumstances it is possible for <tt>__init__</tt>
to be called more than once or not to be called at all, so your other methods
should be designed to be robust in such situations. </p>
<p>Keep in mind that any arguments passed to the constructor will be passed
to the <tt>__new__</tt> method as well as the <tt>__init__</tt> method.
If you anticipate subclassing your extension type in Python, you may find
it useful to give the <tt>__new__</tt> method * and ** arguments so that
it can accept and ignore extra arguments. Otherwise, any Python subclass
which has an <tt>__init__</tt> with a different signature will have to override
<tt>__new__</tt> as well as <tt>__init__</tt>, which the writer of a Python
class wouldn't expect to have to do. </p>
<h2> <font size="+1">Finalization method: <tt>__dealloc__</tt><tt></tt></font></h2>
The counterpart to the <tt>__new__</tt> method is the <b><tt>__dealloc__</tt></b>
method, which should perform the inverse of the <tt>__new__</tt> method.
Any C data structures that you allocated in your <tt>__new__</tt> method
should be freed in your <tt>__dealloc__</tt> method.
<p>You need to be careful what you do in a <tt>__dealloc__</tt> method. By
the time your <tt>__dealloc__</tt> method is called, the object may already
have been partially destroyed and may not be in a valid state as far as Python
is concerned, so you should avoid invoking any Python operations which might
touch the object. In particular, don't call any other methods of the object
or do anything which might cause the object to be resurrected. It's best if
you stick to just deallocating C data. </p>
<p>You don't need to worry about deallocating Python attributes of your object,
because that will be done for you by Pyrex after your <tt>__dealloc__</tt>
method returns.<br>
<br>
<b>Note:</b> There is no <tt>__del__</tt> method for extension types. (Earlier
versions of the Pyrex documentation stated that there was, but this turned
out to be incorrect.)<br>
</p>
<h2><font size="+1">Arithmetic methods</font></h2>
Arithmetic operator methods, such as <tt>__add__</tt>, behave differently
from their Python counterparts. There are no separate "reversed" versions
of these methods (<tt>__radd__</tt>, etc.) Instead, if the first operand
cannot perform the operation, the <i>same</i> method of the second operand
is called, with the operands in the <i>same order</i>.
<p>This means that you can't rely on the first parameter of these methods
being "self", and you should test the types of both operands before deciding
what to do. If you can't handle the combination of types you've been given,
you should return <tt>NotImplemented</tt>. </p>
<p>This also applies to the in-place arithmetic method <tt>__ipow__</tt>.
It doesn't apply to any of the <i>other</i> in-place methods (<tt>__iadd__</tt>,
etc.) which always take self as the first argument. </p>
<h2> <font size="+1">Rich comparisons</font></h2>
There are no separate methods for the individual rich comparison operations
(<tt>__eq__</tt>, <tt>__le__</tt>, etc.) Instead there is a single method
<tt>__richcmp__</tt> which takes an integer indicating which operation is
to be performed, as follows:
<ul>
<ul>
&nbsp; <table nosave="" border="0" cellpadding="5" cellspacing="0">
<tbody>
<tr nosave="">
<td nosave="" bgcolor="#ffcc33" width="30"> <div align="right">&lt;</div>
</td>
<td nosave="" bgcolor="#66ffff" width="30">0</td>
<td><br>
</td>
<td nosave="" bgcolor="#ffcc33" width="30"> <div align="right">==</div>
</td>
<td nosave="" bgcolor="#66ffff" width="30">2</td>
<td><br>
</td>
<td nosave="" bgcolor="#ffcc33" width="30"> <div align="right">&gt;</div>
</td>
<td nosave="" bgcolor="#66ffff" width="30">4</td>
</tr>
<tr nosave="">
<td nosave="" bgcolor="#ffcc33"> <div align="right">&lt;=</div>
</td>
<td nosave="" bgcolor="#66ffff">1</td>
<td><br>
</td>
<td nosave="" bgcolor="#ffcc33"> <div align="right">!=</div>
</td>
<td nosave="" bgcolor="#66ffff">3</td>
<td><br>
</td>
<td nosave="" bgcolor="#ffcc33"> <div align="right">&gt;=</div>
</td>
<td nosave="" bgcolor="#66ffff">5</td>
</tr>
</tbody> </table>
</ul>
</ul>
<h2> <font size="+1">The __next__ method</font></h2>
Extension types wishing to implement the iterator interface should define
a method called <b><tt>__next__</tt></b>, <i>not</i> <tt>next</tt>. The Python
system will automatically supply a <tt>next</tt> method which calls your
<span style="font-family: monospace;">__next__</span>. <b>Do NOT explicitly give your type a <tt>next</tt> method</b>,
or bad things could happen (see note 3).
<h2> <font size="+1">Special Method Table</font></h2>
This table lists all of the special methods together with their parameter
and return types. A parameter named <b>self</b> is of the type the method
belongs to. Other untyped parameters are generic Python objects.
<p>You don't have to declare your method as taking these parameter types.
If you declare different types, conversions will be performed as necessary.
<br>
&nbsp; <table nosave="" bgcolor="#ccffff" border="1" cellpadding="5" cellspacing="0">
<tbody>
<tr nosave="" bgcolor="#ffcc33">
<td nosave=""><b>Name</b></td>
<td><b>Parameters</b></td>
<td><b>Return type</b></td>
<td><b>Description</b></td>
</tr>
<tr nosave="" bgcolor="#66ffff">
<td colspan="4" nosave=""><b>General</b></td>
</tr>
<tr>
<td><tt>__new__</tt></td>
<td>self, ...</td>
<td>&nbsp;</td>
<td>Basic initialisation (no direct Python equivalent)</td>
</tr>
<tr>
<td><tt>__init__</tt></td>
<td>self, ...</td>
<td>&nbsp;</td>
<td>Further initialisation</td>
</tr>
<tr>
<td><tt>__dealloc__</tt></td>
<td>self</td>
<td>&nbsp;</td>
<td>Basic deallocation (no direct Python equivalent)</td>
</tr>
<tr>
<td><tt>__cmp__</tt></td>
<td>x, y</td>
<td>int</td>
<td>3-way comparison</td>
</tr>
<tr>
<td><tt>__richcmp__</tt></td>
<td>x, y, int op</td>
<td>object</td>
<td>Rich comparison (no direct Python equivalent)</td>
</tr>
<tr>
<td><tt>__str__</tt></td>
<td>self</td>
<td>object</td>
<td>str(self)</td>
</tr>
<tr>
<td><tt>__repr__</tt></td>
<td>self</td>
<td>object</td>
<td>repr(self)</td>
</tr>
<tr nosave="">
<td nosave=""><tt>__hash__</tt></td>
<td>self</td>
<td>int</td>
<td>Hash function</td>
</tr>
<tr>
<td><tt>__call__</tt></td>
<td>self, ...</td>
<td>object</td>
<td>self(...)</td>
</tr>
<tr>
<td><tt>__iter__</tt></td>
<td>self</td>
<td>object</td>
<td>Return iterator for sequence</td>
</tr>
<tr>
<td><tt>__getattr__</tt></td>
<td>self, name</td>
<td>object</td>
<td>Get attribute</td>
</tr>
<tr>
<td><tt>__setattr__</tt></td>
<td>self, name, val</td>
<td>&nbsp;</td>
<td>Set attribute</td>
</tr>
<tr>
<td><tt>__delattr__</tt></td>
<td>self, name</td>
<td>&nbsp;</td>
<td>Delete attribute</td>
</tr>
<tr nosave="" bgcolor="#66ffff">
<td colspan="4" nosave=""><b>Arithmetic operators</b></td>
</tr>
<tr>
<td><tt>__add__</tt></td>
<td>x, y</td>
<td>object</td>
<td>binary + operator</td>
</tr>
<tr>
<td><tt>__sub__</tt></td>
<td>x, y</td>
<td>object</td>
<td>binary - operator</td>
</tr>
<tr>
<td><tt>__mul__</tt></td>
<td>x, y</td>
<td>object</td>
<td>* operator</td>
</tr>
<tr>
<td><tt>__div__</tt></td>
<td>x, y</td>
<td>object</td>
<td>/&nbsp; operator for old-style division</td>
</tr>
<tr>
<td><tt>__floordiv__</tt></td>
<td>x, y</td>
<td>object</td>
<td>//&nbsp; operator</td>
</tr>
<tr>
<td><tt>__truediv__</tt></td>
<td>x, y</td>
<td>object</td>
<td>/&nbsp; operator for new-style division</td>
</tr>
<tr>
<td><tt>__mod__</tt></td>
<td>x, y</td>
<td>object</td>
<td>% operator</td>
</tr>
<tr>
<td><tt>__divmod__</tt></td>
<td>x, y</td>
<td>object</td>
<td>combined div and mod</td>
</tr>
<tr>
<td><tt>__pow__</tt></td>
<td>x, y, z</td>
<td>object</td>
<td>** operator or pow(x, y, z)</td>
</tr>
<tr>
<td><tt>__neg__</tt></td>
<td>self</td>
<td>object</td>
<td>unary - operator</td>
</tr>
<tr>
<td><tt>__pos__</tt></td>
<td>self</td>
<td>object</td>
<td>unary + operator</td>
</tr>
<tr>
<td><tt>__abs__</tt></td>
<td>self</td>
<td>object</td>
<td>absolute value</td>
</tr>
<tr>
<td><tt>__nonzero__</tt></td>
<td>self</td>
<td>int</td>
<td>convert to boolean</td>
</tr>
<tr>
<td><tt>__invert__</tt></td>
<td>self</td>
<td>object</td>
<td>~ operator</td>
</tr>
<tr>
<td><tt>__lshift__</tt></td>
<td>x, y</td>
<td>object</td>
<td>&lt;&lt; operator</td>
</tr>
<tr>
<td><tt>__rshift__</tt></td>
<td>x, y</td>
<td>object</td>
<td>&gt;&gt; operator</td>
</tr>
<tr>
<td><tt>__and__</tt></td>
<td>x, y</td>
<td>object</td>
<td>&amp; operator</td>
</tr>
<tr>
<td><tt>__or__</tt></td>
<td>x, y</td>
<td>object</td>
<td>| operator</td>
</tr>
<tr>
<td><tt>__xor__</tt></td>
<td>x, y</td>
<td>object</td>
<td>^ operator</td>
</tr>
<tr nosave="" bgcolor="#66ffff">
<td colspan="4" nosave=""><b>Numeric conversions</b></td>
</tr>
<tr>
<td><tt>__int__</tt></td>
<td>self</td>
<td>object</td>
<td>Convert to integer</td>
</tr>
<tr>
<td><tt>__long__</tt></td>
<td>self</td>
<td>object</td>
<td>Convert to long integer</td>
</tr>
<tr>
<td><tt>__float__</tt></td>
<td>self</td>
<td>object</td>
<td>Convert to float</td>
</tr>
<tr>
<td><tt>__oct__</tt></td>
<td>self</td>
<td>object</td>
<td>Convert to octal</td>
</tr>
<tr>
<td><tt>__hex__</tt></td>
<td>self</td>
<td>object</td>
<td>Convert to hexadecimal</td>
</tr>
<tr nosave="" bgcolor="#66ffff">
<td colspan="4" nosave=""><b>In-place arithmetic operators</b></td>
</tr>
<tr>
<td><tt>__iadd__</tt></td>
<td>self, x</td>
<td>object</td>
<td>+= operator</td>
</tr>
<tr>
<td><tt>__isub__</tt></td>
<td>self, x</td>
<td>object</td>
<td>-= operator</td>
</tr>
<tr>
<td><tt>__imul__</tt></td>
<td>self, x</td>
<td>object</td>
<td>*= operator</td>
</tr>
<tr>
<td><tt>__idiv__</tt></td>
<td>self, x</td>
<td>object</td>
<td>/= operator for old-style division</td>
</tr>
<tr>
<td><tt>__ifloordiv__</tt></td>
<td>self, x</td>
<td>object</td>
<td>//= operator</td>
</tr>
<tr>
<td><tt>__itruediv__</tt></td>
<td>self, x</td>
<td>object</td>
<td>/= operator for new-style division</td>
</tr>
<tr>
<td><tt>__imod__</tt></td>
<td>self, x</td>
<td>object</td>
<td>%= operator</td>
</tr>
<tr>
<td><tt>__ipow__</tt></td>
<td>x, y, z</td>
<td>object</td>
<td>**= operator</td>
</tr>
<tr>
<td><tt>__ilshift__</tt></td>
<td>self, x</td>
<td>object</td>
<td>&lt;&lt;= operator</td>
</tr>
<tr>
<td><tt>__irshift__</tt></td>
<td>self, x</td>
<td>object</td>
<td>&gt;&gt;= operator</td>
</tr>
<tr>
<td><tt>__iand__</tt></td>
<td>self, x</td>
<td>object</td>
<td>&amp;= operator</td>
</tr>
<tr>
<td><tt>__ior__</tt></td>
<td>self, x</td>
<td>object</td>
<td>|= operator</td>
</tr>
<tr>
<td><tt>__ixor__</tt></td>
<td>self, x</td>
<td>object</td>
<td>^= operator</td>
</tr>
<tr nosave="" bgcolor="#66ffff">
<td colspan="4" nosave=""><b>Sequences and mappings</b></td>
</tr>
<tr>
<td><tt>__len__</tt></td>
<td>self</td>
<td>int</td>
<td>len(self)</td>
</tr>
<tr>
<td><tt>__getitem__</tt></td>
<td>self, x</td>
<td>object</td>
<td>self[x]</td>
</tr>
<tr>
<td><tt>__setitem__</tt></td>
<td>self, x, y</td>
<td>&nbsp;</td>
<td>self[x] = y</td>
</tr>
<tr>
<td><tt>__delitem__</tt></td>
<td>self, x</td>
<td>&nbsp;</td>
<td>del self[x]</td>
</tr>
<tr>
<td><tt>__getslice__</tt></td>
<td>self, int i, int j</td>
<td>object</td>
<td>self[i:j]</td>
</tr>
<tr>
<td><tt>__setslice__</tt></td>
<td>self, int i, int j, x</td>
<td>&nbsp;</td>
<td>self[i:j] = x</td>
</tr>
<tr>
<td><tt>__delslice__</tt></td>
<td>self, int i, int j</td>
<td>&nbsp;</td>
<td>del self[i:j]</td>
</tr>
<tr>
<td><tt>__contains__</tt></td>
<td>self, x</td>
<td>int</td>
<td>x in self</td>
</tr>
<tr nosave="" bgcolor="#66ffff">
<td colspan="4" nosave=""><b>Iterators</b></td>
</tr>
<tr>
<td><tt>__next__</tt></td>
<td>self</td>
<td>object</td>
<td>Get next item (called <tt>next</tt> in Python)</td>
</tr>
<tr nosave="" bgcolor="#66ffff">
<td colspan="4" nosave=""><b>Buffer interface</b>&nbsp; (no Python equivalents
- see note 1)</td>
</tr>
<tr>
<td><tt>__getreadbuffer__</tt></td>
<td>self, int i, void **p</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><tt>__getwritebuffer__</tt></td>
<td>self, int i, void **p</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><tt>__getsegcount__</tt></td>
<td>self, int *p</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><tt>__getcharbuffer__</tt></td>
<td>self, int i, char **p</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr nosave="" bgcolor="#66ffff">
<td colspan="4" nosave=""><b>Descriptor objects</b>&nbsp; (no Python equivalents
- see note 2)</td>
</tr>
<tr>
<td><tt>__get__</tt></td>
<td>self, instance, class</td>
<td>object</td>
<td>Get value of attribute</td>
</tr>
<tr>
<td><tt>__set__</tt></td>
<td>self, instance, value</td>
<td>&nbsp;</td>
<td>Set value of attribute</td>
</tr>
<tr>
<td style="font-family: monospace;">__delete__</td>
<td>self, instance</td>
<td>&nbsp;</td>
<td>Delete attribute</td>
</tr>
</tbody> </table>
</p>
<p>Note 1: The buffer interface is intended for use by C code and is not
directly accessible from Python. It is described in the <a href="http://www.python.org/doc/current/api/api.html">Python/C API Reference
Manual</a> under sections <a href="http://www.python.org/doc/current/api/abstract-buffer.html">6.6</a>
and <a href="http://www.python.org/doc/current/api/buffer-structs.html">10.6</a>.
</p>
<p>Note 2: Descriptor objects are part of the support mechanism for new-style
Python classes. See the <a href="http://www.python.org/doc/2.2.1/whatsnew/sect-rellinks.html#SECTION000320000000000000000">discussion
of descriptors in the Python documentation</a>. See also <a href="http://www.python.org/peps/pep-0252.html">PEP 252, "Making Types Look
More Like Classes"</a>, and <a href="http://www.python.org/peps/pep-0253.html">PEP 253, "Subtyping Built-In
Types"</a>. </p>
<p>Note 3: If your type defines a <tt>__new__</tt> method, any method called
<tt>new</tt> that you define will be overwritten with the system-supplied
<tt>new</tt> at module import time. </p>
<br>
<br>
</body></html>
\ No newline at end of file
Pyrex - Installation Instructions
=================================
You have two installation options:
(1) Run the setup.py script in this directory
as follows:
python setup.py install
This will install the Pyrex package
into your Python system.
OR
(2) If you prefer not to modify your Python
installation, arrange for the directory
containing this file (INSTALL.txt) to be in
your PYTHONPATH. On unix, also put the bin
directory on your PATH.
See README.txt for pointers to other documentation.
The PYTHON SOFTWARE FOUNDATION LICENSE:
PSF LICENSE AGREEMENT FOR PYTHON 2.4
------------------------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
otherwise using Python 2.4 software in source or binary form and its
associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 2.4
alone or in any derivative version, provided, however, that PSF's
License Agreement and PSF's notice of copyright, i.e., "Copyright (c)
2001, 2002, 2003, 2004 Python Software Foundation; All Rights Reserved"
are retained in Python 2.4 alone or in any derivative version prepared
by Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 2.4 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 2.4.
4. PSF is making Python 2.4 available to Licensee on an "AS IS"
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.4 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
2.4 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.4,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python 2.4, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
include MANIFEST.in README.txt INSTALL.txt CHANGES.txt ToDo.txt USAGE.txt
include setup.py
include bin/pyrexc
include pyrexc.py
include Pyrex/Compiler/Lexicon.pickle
include Doc/*
include Demos/*
VERSION = 0.9.4.1
version:
@echo "Setting version to $(VERSION)"
@echo "version = '$(VERSION)'" > Pyrex/Compiler/Version.py
#check_contents:
# @if [ ! -d Pyrex/Distutils ]; then \
# echo Pyrex/Distutils missing; \
# exit 1; \
# fi
clean:
@echo Cleaning Source
@rm -f *.pyc */*.pyc */*/*.pyc
@rm -f *~ */*~ */*/*~
@rm -f core */core
@(cd Demos; $(MAKE) clean)
Welcome to Cython!
=================
Cython (http://www.cython.org) is based on Pyrex, but
supports more cutting edge functionality and optimizations.
LICENSE:
The original Pyrex program was licensed "free of restrictions" (see
below). Cython itself is licensed under the
PYTHON SOFTWARE FOUNDATION LICENSE
http://www.python.org/psf/license/
--------------------------
To see the change history, go to the Pyrex directory and type
$ hg log
This requires that you have installed Mercurial.
-- William Stein (wstein@gmail.com)
xxxx
The following is from Pyrex:
------------------------------------------------------
This is a development version of Pyrex, a language
for writing Python extension modules.
For more info, see:
Doc/About.html for a description of the language
INSTALL.txt for installation instructions
USAGE.txt for usage instructions
Demos for usage examples
Comments, suggestions, bug reports, etc. are
welcome!
Copyright stuff: Pyrex is free of restrictions. You
may use, redistribute, modify and distribute modified
versions.
The latest version of Pyrex can be found here:
http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury, | A citizen of NewZealandCorp, a |
Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. |
greg@cosc.canterbury.ac.nz +--------------------------------------+
DONE - Pointer-to-function types.
DONE - Nested declarators.
DONE - Varargs C func defs and calls.
DONE - * and ** args in Python func defs.
DONE - Default argument values.
DONE - Tracebacks.
DONE - Disallow creating char * from Python temporary anywhere
(not just on assignment).
DONE - Module and function and class doc strings.
DONE - Predeclare C functions.
DONE - Constant expressions.
DONE - Forward C struct declarations.
DONE - Prefix & operator.
DONE - Get rid of auto string->char coercion and
add a c'X' syntax for char literals.
DONE - Cascaded assignments (a = b = c).
DONE - 'include' statement for including other Pyrex files.
DONE - Add command line option for specifying name of generated C file.
DONE - Add 'else' clause to try-except.
DONE - Allow extension types to be declared "public" so they
can be accessed from another Pyrex module or a C file.
DONE - Don't try to generate objstruct definition for external
extension type declared without suite (treat as though
declared with empty suite).
DONE - Implement two-argument form of 'assert' statement.
Const types.
Tuple/list construction: Evaluate & store items one at a time?
Varargs argument traversal.
Use PyDict_SetItemString to build keyword arg dicts?
(Or wait until names are interned.)
Intern names.
print >>file
abs() and anything similar.
Semicolon-separated statement lists.
Optional semicolons after C declarations.
Multiple C declarations on one line?
Optimise return without value outside of try-finally.
exec statement.
from ... import statement.
Use iterator protocol for unpacking.
Save & restore exception being handled on function entry/exit.
In-place operators (+=, etc).
Constant declarations. Syntax?
DONE - Some way for C functions to signal Python errors?
Check for lack of return with value in non-void C functions?
Allow 'pass' in struct/union/enum definition.
Make C structs callable as constructors.
DONE - Provide way of specifying C names.
DONE - Public cdefs.
When calling user __dealloc__ func, save & restore exception.
DONE - Forward declaration of extension types.
Complex number parsetuple format?
DONE - long long type
DONE - long double type?
Windows __fooblarg function declaration things.
Generate type, var and func declarations in the same order that
they appear in the source file.
Provide a way of declaring a C function as returning a
borrowed Python reference.
Provide a way of specifying whether a Python object obtained
by casting a pointer should be treated as a new reference
or not.
Optimize integer for-loops.
Make sizeof() take types as well as variables.
Allow "unsigned" to be used alone as a type name.
Allow duplicate declarations, at least in extern-from.
Do something about installing proper version of pyrexc
script according to platform in setup.py.
DONE - Add "-o filename" command line option to unix/dos versions.
Recognise #line directives?
Catch floating point exceptions?
Check that forward-declared non-external extension types
are defined.
Generate type test when casting from one Python type
to another.
Generate a Pyrex include file for public declarations
as well as a C one.
Syntax for defining indefinite-sized int & float types.
Allow ranges of exception values.
Support "complex double" and "complex float"?
Allow module-level Python variables to be declared extern.
Consider:
>cdef extern from "foo.h":
> int dosomething() except -1 raise MyException
Properties for Python types.
DONE - Properties for extension types.
Find a way to make classmethod and staticmethod work better.
DONE - Document workarounds for classmethod and staticmethod.
Statically initialised C arrays & structs.
Reduce generation of unused vars and unreachable code?
Support for acquiring and releasing GIL.
Make docstrings of extension type special methods work.
Treat result of getting C attribute of extension type as non-ephemeral.
Make None a reserved identifier.
Teach it about builtin functions that correspond to
Python/C API calls.
Teach it about common builtin types.
Option for generating a main() function?
DONE - Allow an extension type to inherit from another type.
Do something about external C functions declared as returning
const * types?
Use PyString_FromStringAndSize for string literals?
DONE - C functions as methods of extension types.
What to do about __name__ etc. attributes of a module (they are
currently assumed to be built-in names).
Use PyDict_GetItem etc. on module & builtins dicts for speed.
Intern all string literals used as Python strings?
[Koshy <jkoshy@freebsd.org>]
Make extension types weak-referenceable.
[Matthias Baas <baas@ira.uka.de>]
Make 'pass' work in the body of an extern-from struct
or union.
Disallow a filename which results in an illegal identifier when
used as a module name.
Use ctypedef names.
Provide an easy way of exposing a set of enum values as Python names.
[John J Lee <jjl@pobox.com>]
Prevent user from returning a value from special methods that
return an error indicator only.
Use PyObject_TypeCheck instead of PyObject_IsInstance?
Allow * in cimport? [John J Lee <jjl@pobox.com>]
FAQ: Q. Pyrex says my extension type object has no attribute 'rhubarb', but
I know it does.
A. Have you declared the type at the point where you're using it?
Eliminate lvalue casts! (Illegal in C++, also disallowed by some C compilers)
[Matthias Baas <baas@ira.uka.de>]
Make Python class construction work more like it does in Python.
Give the right module name to Python classes.
Command line switch for full pathnames in backtraces?
Use PyString_FromStringAndSize on string literals containing
nulls.
Peephole optimisation? [Vladislav Bulatov <vrbulatov@list.ru>]
Avoid PyArg_ParseTuple call when a function takes no positional args.
Omit incref/decref of arguments that are not assigned to?
Can a faster way of instantiating extension types be found?
Disallow declaring a special method of an extension type with
'cdef' instead of 'def'.
Use PySequence_GetItem instead of PyObject_GetItem when index
is an integer.
If a __getitem__ method is declared with an int index, use the
sq_item slot instead of the mp_subscript slot.
Provide some way of controlling the argument list passed to
an extension type's base __new__ method?
[Alain Pointdexter <alainpoint@yahoo.fr>]
Rename __new__ in extension types to __alloc__.
Implement a true __new__ for extension types.
Way to provide constructors for extension types that are not
available to Python and can accept C types directly?
Support generators by turning them into extension types?
List comprehensions.
Variable declarations inside inner code blocks?
Initial values when declaring variables?
Do something about __stdcall.
Support class methods in extension types using METH_CLASS flag.
Disallow defaulting types to 'object' in C declarations?
C globals with static initialisers.
Find a way of providing C-only initialisers for extension types.
Metaclasses for extension types?
Make extension types use Py_TPFLAGS_HEAPTYPE so their __module__
will get set dynamically?
;;;; `Pyrex' mode. (add-to-list 'auto-mode-alist '("\\.pyx\\'" . pyrex-mode)) (define-derived-mode pyrex-mode python-mode "Pyrex" (font-lock-add-keywords nil `((,(concat "\\<\\(NULL" "\\|c\\(def\\|har\\|typedef\\)" "\\|e\\(num\\|xtern\\)" "\\|float" "\\|in\\(clude\\|t\\)" "\\|object\\|public\\|struct\\|type\\|union\\|void" "\\)\\>") 1 font-lock-keyword-face t))))
\ No newline at end of file
/** * Name: pyrex * Description: Pyrex - a Language for Writing Python Extension Modules * Author: Markku Rossi <mtr@iki.fi> */ state pyrex extends python{ /* Additional keywords. (build-re '( NULL as cdef char ctypedef double enum extern float include int long private public short signed sizeof struct union unsigned void )) */ /\b(NULL|as|c(def|har|typedef)|double|e(num|xtern)|float|in(clude|t)\|long|p(rivate|ublic)|s(hort|i(gned|zeof)|truct)|un(ion|signed)|void)\b/ { keyword_face(true); language_print($0); keyword_face(false); }} /*Local variables:mode: cEnd:*/
\ No newline at end of file
Pyrex - Usage Instructions
==========================
Building Pyrex extensions using distutils
-----------------------------------------
Pyrex comes with an experimental distutils extension for compiling
Pyrex modules, contributed by Graham Fawcett of the University of
Windsor (fawcett@uwindsor.ca).
The Demos directory contains a setup.py file demonstrating its use. To
compile the demos:
(1) cd Demos
(2) python setup.py build_ext --inplace
or
python setup.py build --build-lib=.
(You may get a screed of warnings from the C compiler, but you can
ignore these -- as long as there are no actual errors, things are
probably okay.)
Try out the extensions with:
python run_primes.py
python run_spam.py
python run_numeric_demo.py
Building Pyrex extensions by hand
---------------------------------
You can also invoke the Pyrex compiler on its own to translate a .pyx
file to a .c file. On Unix,
pyrexc filename.pyx
On other platforms,
python pyrexc.py filename.pyx
It's then up to you to compile and link the .c file using whatever
procedure is appropriate for your platform. The file
Makefile.nodistutils in the Demos directory shows how to do this for
one particular Unix system.
Command line options
--------------------
The pyrexc command supports the following options:
Short Long Argument Description
-----------------------------------------------------------------------------
-v --version Display version number of pyrex compiler
-l --create-listing Write error messages to a .lis file
-I --include-dir <directory> Search for include files in named
directory (may be repeated)
-o --output-file <filename> Specify name of generated C file (only
one source file allowed if this is used)
Anything else is taken as the name of a Pyrex source file and compiled
to a C source file. Multiple Pyrex source files can be specified
(unless -o is used), in which case each source file is treated as the
source of a distinct extension module and compiled separately to
produce its own C file.
#!/usr/bin/env python
#
# Pyrex -- Main Program, Unix
#
from Pyrex.Compiler.Main import main
main(command_line = 1)
#!/usr/bin/env python
#
# Go through the Tests directory and its subdirectories
# copying the latest versions of the test outputs into
# the Reference directories.
#
import os, sys
ignore_names = [".DS_Store", "Icon\r"]
def copy_file(from_path, to_path):
# We copy the contents from one file to the other
# so as to preserve metadata on the Mac.
#print from_path, "-->", to_path
f = open(from_path)
g = open(to_path, "w+")
g.write(f.read())
f.close()
g.close()
def update_references(out_dir, ref_dir):
for name in os.listdir(ref_dir):
if name not in ignore_names:
out_file = os.path.join(out_dir, name)
ref_file = os.path.join(ref_dir, name)
if os.path.isfile(out_file):
print "Updating", name
copy_file(out_file, ref_file)
def update_references_in_dir(dir):
print "Updating references in", dir
for name in os.listdir(dir):
if name <> "Reference" and not name.startswith("("):
item_path = os.path.join(dir, name)
if os.path.isdir(item_path):
update_references_in_dir(item_path)
ref_dir = os.path.join(dir, "Reference")
if os.path.isdir(ref_dir):
update_references(dir, ref_dir)
def main():
bin_dir = os.path.dirname(sys.argv[0])
source_dir = os.path.dirname(bin_dir)
tests_dir = os.path.join(source_dir, "Tests")
update_references_in_dir(tests_dir)
if __name__ == "__main__":
main()
#
# Pyrex -- Main Program, generic
#
from Pyrex.Compiler.Main import main
main(command_line = 1)
from distutils.core import setup
from distutils.sysconfig import get_python_lib
import os
from Cython.Compiler.Version import version
compiler_dir = os.path.join(get_python_lib(prefix=''), 'Cython/Compiler')
if os.name == "posix":
scripts = ["bin/cython"]
else:
scripts = ["cython.py"]
setup(
name = 'Cython',
version = version,
url = 'http://www.cython.org',
author = 'Greg Ewing, William Stein, Robert Bradshaw, Stefan Behnel, et al.',
author_email = 'wstein@gmail.com',
scripts = scripts,
packages=[
'Cython',
'Cython.Compiler',
'Cython.Distutils',
'Cython.Mac',
'Cython.Plex'
],
data_files=[
(compiler_dir, ['Cython/Compiler/Lexicon.pickle'])
]
)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment