problems loading modules

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Feb 5 01:13:43 EST 2007


"Frank" <supervau at gmail.com> writes:

> >>> import random
> >>> print random.randrange(10)
> 8
> >>>
>
> Everything is fine.
>
> >>> import random
> >>> from numpy import *
> >>>
> >>> print random.randrange(10)
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
> AttributeError: 'module' object has no attribute 'randrange'
> >>>
>
> Here it does not work.

"Don't do that, then."

More specifically, 'from foo import *' is deprecated for exactly the
reason you found here: you risk clobbering an existing name in the
current namespace, and there's no way to determine that by looking at
the code.

Instead, import modules preserving a module namespace, which is the
behaviour you get from 'import foo'. That way, all names remain
explicit and you can see where you might be re-binding an existing
name.

    >>> import random
    >>> random
    <module 'random' from '/usr/lib/python2.4/random.pyc'>
    >>> import numpy
    >>> random
    <module 'random' from '/usr/lib/python2.4/random.pyc'>
    >>> numpy.random
    <module 'numpy.random' from '/usr/lib/python2.4/site-packages/numpy/random/__init__.pyc'>

Alternatively, if you want *specific* attributes from a module or
package to be in the current namespace, import them explicitly by
name; the same applied above, that you can see which names in
particular are being re-bound.

    >>> import random
    >>> random
    <module 'random' from '/usr/lib/python2.4/random.pyc'>
    >>> from numpy import random
    >>> random
    <module 'numpy.random' from '/usr/lib/python2.4/site-packages/numpy/random/__init__.pyc'>

Again: don't use 'from foo import *', without knowing exactly why
you're doing it. 'import foo' or 'from foo import bar' are always
available, and usually better.

-- 
 \       "I always wanted to be somebody. I see now that I should have |
  `\                              been more specific."  -- Lily Tomlin |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list