user49404
user49404

Reputation: 917

Why does import package.module.function fail in python?

I've tried googling (to little avail) to more clearly understand what different meaning period . has during an import statement, vs. once a module has already been imported.

For example, these all work:

import numpy
X = numpy.random.standard_normal

from numpy.random import standard_normal

import numpy.random

but this doesn't work:

import numpy.random.standard_normal

I'm a bit confused as to why this is. Why is there a difference in what the period . does when accessing a module before vs. after an import?

Upvotes: 0

Views: 63

Answers (1)

Ice Bear
Ice Bear

Reputation: 4086

It's because standard_normal is a method

<built-in method standard_normal of numpy.random.mtrand.RandomState object at 0x0000029D722FBD40>

whenever you do from numpy.random import standard_normal you are importing the method

and i don't think you can do this import numpy.random.standard_normal cause standard_normal again is a method, this would be possible if standard_normal would be some module.

Take a look at this, you when I typed dir(standard_normal) I get the output of those things which are attributes and when I typed standard_normal it says <built-in method standard_normal of numpy.random.mtrand.RandomState object at 0x000002509D504740> cause it simply says it is a method

sample

Now when I did this import numpy.random.standard_normal , you are expecting to import the method right? But what it really does is trying to import a module, Well... there is no such thing as standard_normal module or standard_normal.py file.

Take a look at this again. I imported the random module and I used the . operator to access the standard_normal function. You can see the sense of it right. Cause on the random.py module it has there a standard_normal function or method.

sampe

Sorry I had to use the CMD.

Upvotes: 2

Related Questions