Reputation: 1809
I was poking through what is available in numpy.random
after importing
from numpy import random
with dir(random)
, and noticed that there was a variable np
in scope, which appears equivalent to the top-level module, for example
In[1]: from numpy import random
In[2]: random.np.fft.fft2
Out[2]: <function numpy.fft.fftpack.fft2>
In[3]: random.np.random.np.fft.np # not the same for fft
AttributeErrorTraceback (most recent call last)
<ipython-input-78-a64e04c36c80> in <module>()
----> 1 random.np.random.np.fft.np
AttributeError: module 'numpy.fft' has no attribute 'np'
This seems a bit strange to me... or at least not something I've seen before in other Python modules. It looks like I can access everything I could with import numpy as np
through the np
variable in random
.
I wanted to see how it was available to the submodule, so I looked in numpy/random/__init__.py
in the source code, and didn't see how it is made available. I also looked in numpy/random/info.py
at __all__
, but can't find how it is exposed to the module.
How is the top level module made available to numpy.random
, and is there any motivation for having it available?
Upvotes: 1
Views: 129
Reputation: 49794
So in numpy/random/mtrand/mtrand.pyx
line 146 we find:
import numpy as np
Thus placing the symbol into the module's namespace. Which, this being python, you can access. I would imagine that this line is present for the same reason we litter it all over our modules, namely this module needs access to numpy
functionality.
And backing up one level we find in /numpy/random/__init__.py
line 99:
from .mtrand import *
Which closes the circle and gets us access to np
via the numpy.random
module.
Upvotes: 2