rocksNwaves
rocksNwaves

Reputation: 6164

How do I know if I am calling numpy.array() or using built in array function?

If, for example, I import as follows:

from numpy import empty, full, zeros, matrix, arange, asarray, array

Then I might have some list that I generated:

stuff = []

for i in range(N):
    stuff.append(things)

then, I realize I have to do some math! so I type:

math_stuff = array(stuff)

Since I didn't have to type numpy.array or np.array, based on how I declared my imports, how do I know that my IDE is preferring the numpy version over the built in version? Is this automatic?

I checked the docs on for numpy.array() and python's built in array(), and it looks like they both accept the same "list like" argument.

Upvotes: 1

Views: 146

Answers (2)

tel
tel

Reputation: 13999

As the commenters have said, you can easily tell which one is being used just by looking at the most recent import statement. However, in case you get worried/confused, you can also directly check the module from which a function or class originates using Python's handy built-in reflection features.

For example, the following Python statement:

print(array.__module__)

will print out the string 'numpy.core.multiarray' if array was imported from the numpy package, or the string 'array' if it was imported from the array package.

If x.__module__ fails, explore alternatives via dir(x)

@ShadowRanger raises the good point that some Python objects don't have the __module__ property. In particular, if you run just import array, then array is a module and the print(array.__module__) call will fail. In these kinds of situations you can always discover what reflection information is actually available via the dir() function.

dir() is easily my favorite feature of Python. For any Python object x, dir(x) prints out the complete list of the attributes of x. For example, given that you just ran import array, executing dir(array) would then print out:

['ArrayType',
'__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'_array_reconstructor',
'array',
'typecodes']

Which shows that even though the array module lacks __module__, if does have other reflection information available such as __name__ and __file__.

Upvotes: 2

Reblochon Masque
Reblochon Masque

Reputation: 36702

The best way is probably to keep your namespaces clean, if you can:

do: import numpy or import numpy as np,

instead of: from numpy import empty, full, zeros, matrix, arange, asarray, array

In case it is not up to you, and it is unclear what came earlier, help(array), or repr(array), or type(array) will be handy. (as mentioned in the comments)

Upvotes: 1

Related Questions