[Python-3000] Adaptation vs. Generic Functions
Ian Bicking
ianb at colorstudy.com
Thu Apr 13 17:34:16 CEST 2006
Michael Chermside wrote:
> But in a more realistic situation, the NumPy folks realize that
> many of their users are doing scientific work and a noticable
> number make use of mpz. (The mpz folks are just wrapping an
> external library so they don't think of these things, but that's
> OK since only one of them needs to.) The NumPy folks add the
> following lines of code:
>
> try:
> import mpz
>
> @operator.add.register(NumPy.array, mpz.mpz)
> def leftAdd(array1, mpz1):
> ... # invoke mpz.rightAdd() on each component
>
> @operator.add.register(mpz.mpz, NumPy.array)
> def rightAdd(mpz1, array1):
> ... # invoke mpz.leftAdd() on each component
>
> except ImportError:
> pass
A niggling detail here, but with setuptools and package activation
try:except ImportError: doesn't work very well for these things. If mpz
is available through pkg_resources.require(), but not directly
importable, this may fail until mpz is required. You don't have to be
using pkg_resources.require() directly either to see this, though you'll
only really see it when features are dynamically activated at runtime
(instead of being activated entirely through requirements statically
provided in your setup.py/entry_points.txt).
And even if that wasn't a problem, it means mpz would be eagerly loaded
along with NumPy even if it wasn't needed. Or if you had to manually
import this operator.add-glue, then if you forget it is likely to be
difficult to debug, because there's no *bad* code, just code that is
missing.
This is somewhat tangential to generic functions, but I guess happens
whenever you have any kind of registry that is modified on import.
--
Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org
More information about the Python-3000
mailing list