Native Code vs. Python code for modules

castironpi castironpi at
Sun Aug 31 17:36:31 CEST 2008

On Jul 29, 10:56 pm, koblas <kob... at> wrote:
> To that end why would somebody write big try catch blocks to see if
> modules exist and if they exist alias their names.  Wouldn't it be
> better if there was a way that if I have an "interface compatible"
> native (aka C) module that has better performance that there could be
> a way that python would give it preference.
> e.g.
>   import random(version=1.2, lang=c)
> or
>   import random(version=1.2, lang=py)   # use the python version by
> default
> or
>   import random     #  use the latest version in the "fastest" code (C
> given preference)
> where there could be a nice set of "standard" key value pairs that
> could provide addtional hints as to what language and version of a
> library was to be used.

I don't see any reason why you couldn't write your own.  You won't get
that exact syntax in Python but here's a few things that come close.

versioned_import( 'random', 1.2, versioning.C )
versioned_import( 'random', 1.2, 'C' )
versioned_import( 'random', lang= 'python' )

In order to get your new module added to the namespace, you might need
an assignment.

randomC= versioned_import( 'random', lang= 'python' )

This would perform the same functionality as 'import random as

The exact details of priority and search order (you find a better
match in a more remote search location, you find a better version
match and worse language match) are up to you, which there are ways to
specify or decide behind the scenes.  You could even have two versions
of a lookup table in the same language, one implemented with a hash
table and one with an AVL tree.  Do you specify that with version
numbers, version names, or extra keywords?  If you're dealing with
lookups frequently on powers of two, for example, you might want to
avoid a hash table, or at least avoid Python's.

>>> [ hash(2**x) for x in range( 0, 700, 32 ) ]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

Can a package that's 'versioned_import - ready' offer additional
keywords, such as enabling particular options, etc.?  Perhaps the
function can begin to import a package, make some run-time
determinations based on parameters, and branch from there.

More information about the Python-list mailing list