How does the two declarations differ from one another? [duplicate] - python

This question already has answers here:
Use 'import module' or 'from module import'?
(23 answers)
Closed 3 years ago.
When is from and import used? How does the two lines differ? What do they do?
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt

The first line imports the specific class ListedColormap from matplotlib.colors package.
The second line gives an alias plt to the package matplotlib.pyplot so that you can call any function or class of the package as plt.func()

import module
This imports the entire module. In this instance to access any functions defined in the module you would need to use "module.function"
from module import part_of_module
This imports a part of a module e.g. a class or function.
If you add the alias e.g.
import pandas as pd
Then you can access pandas functions etc. using e.g. pd.DataFrame rather than pandas.DataFrame, for brevity/convenience to call it what you want.
It is also an option, but not recommended, to go
from module import *
This imports the entire module, but if you want to use a function from that module you no longer need to explicitly state module.function in order to use it. This is not recommended because you could have multiple functions with the same name which could result in calling the wrong function.

from matplotlib.colors import ListedColormap
Import a specific class from a package.
import matplotlib.pyplot as plt
Import the package as an aliased package name.

Related

Why mock patching works with random but not with np?

I have a module where a number of different functions use random numbers or random choices.
I am trying to use mock and patch to inject pre-chosen values in place of these random selections but can't understand an error I am receiving.
In the function I am testing, I use
np.random.randint
when I use the code
from unittest import mock
import random
mocked_random_int = lambda : 7
with mock.patch('np.random.randint', mocked_random_int):
I get an error message no module named np. However, numpy is imported as np and other functions are calling it just fine.
Even more perplexing if I edit the code above to remove the 'np' at the front it does what I want:
with mock.patch('random.randint', mocked_random_int):
But I want to understand why the code works without the np. Thank you!
There is a difference between a module or package name and the variable it is assigned to in any given namespace. A simple import
import numpy
tells python to check its imported module list, import numpy as necessary, and assign the module to the variable "numpy"
import numpy as np
is almost the same, except that you assign to a variable "np". Its still the same numpy package, its just that you've aliased it differently.
mock.patch will import and patch the module regardless of whether you've already imported it, but you need to give the module name, not your current module's alias to the module.

Is there an import static equivalent in Python?

In java, one can import a class statically by calling import static com.Abc, for example. And then instead having to call Abc.doSomething() you can just call doSomething(). Is there an equivalent of this in Python, and if so, what is it?
You can just import the function directly. Consider the timedelta function in Python's datetime package. If I want to just import the function I use:
from datetime.datetime import timedelta
Then I can use the function on its own.
Also, I can rename packages to simplify things. For instance, it is a common convention to import matplotlib.pyplot as plt, pandas as pd, and seaborn as sns:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

How to check if a module is imported

I use numpy and scipy for data analysis. I want to write a code inside a function that I define so that when the function is called it check if, for example, numpy is imported and if it is not imported, then it should import it.
How can I check if any module such as numpy imported?
You can use sys.modules in the sys module for this:
>>> import sys
>>> import numpy
>>> 'numpy' in sys.modules
True
So your function could be:
def is_imported(module):
return module in sys.modules
From the comments, you also wanted to return True if you'd used
from skimage.morphology import watershed
You can check if a function is in the current namespace by using dir()
>>> 'watershed' in dir()
False
>>> from skimage.morphology import watershed
>>> 'watershed' in dir()
True
To import a module using a string, you can use importlib.import_module():
>>> import importlib
>>> importlib.import_module('numpy')
The import statement is idempotent - it already checks whether the module has been loaded. Using import module in your function already does what you want:
def my_func():
import numpy # load numpy if not available
# use numpy
This works for all kinds of imports, including submodules, relative imports and aliasing of members.
def my_other_func():
# load skimage, skimage.morphology, and
# skimage.morphology.watershed if they are unimported modules
from skimage.morphology import watershed
During import, the module name is looked up in sys.modules and if present, the associated value is the module satisfying the import, and the process completes. [...]
[The Python Language Reference: the import system]

The difference between np.function and function [duplicate]

This question already has answers here:
Why is "import *" bad?
(12 answers)
How do I import other Python files?
(23 answers)
Closed 5 years ago.
We can import numpy and use its functions directly as:
from numpy import *
a = arraay([1,2,3]) # and it works well.
Why do some people use the following method?
import numpy as np
a= np.array([1,2,3])
The difference is easy: from numpy import * imports all names from the top-level NumPy module into your current "module" (namespace). import numpy as np will just make that top-level NumPy module available if you use np.xxx.
However there is one reason why you shouldn't use from any_module import *: It may just overwrite existing names. For example NumPy has its own any, max, all and min functions, which will happily shadow the built-in Python any, max, ... functions (a very common "gotcha").
My advise: Avoid from numpy import * even if it seems like less effort than typing np. all the time!
It's a matter of neatness but also consistency: you might have multiple functions with the same name from different modules (for instance there's a function called "random" in Numpy, but also in other packages like SciPy) so it's important to denote which exact function you're using from which exact module. This link has a great explanation and makes the point about code readability as well.

Use Function Without Calling Module [duplicate]

This question already has an answer here:
Is there a way to bypass the namespace/module name in Python?
(1 answer)
Closed last month.
I am using Canopy with the Jupyter notebook. I was wondering if there was a way to use function from a module without having to call the module. For example if I have
import numpy as np
print np.sin(2)
I would want to be able to just type
print sin(2)
The first thing that comes to mind is to add the numpy functions into whatever function library that Python is using. But I was wondering if this is feasible and, if so, how I could go about doing it. Note that I want to import all functions, not just a select few.
You can import specific objects from a module. Try:
from numpy import sin
print sin(2)
To import all objects from a module into the global namespace you can use import *.
from numpy import *
print sin(2)
But this is not recommended because you can easily end up with name clashes, e.g. if two modules define a function named sin which version of sin should be called?
>>> import math
>>> import numpy
>>> math.sin
<built-in function sin>
>>> numpy.sin
<ufunc 'sin'>
>>> from math import *
>>> sin
<built-in function sin>
>>> from numpy import *
>>> sin
<ufunc 'sin'>
You can see here that the second import from numpy replaced sin in the global namespace.
For this reason it is best to import the specific objects that you need if there are only a few, otherwise just import the module and use the module name as a prefix (as per your first example). In my example if you wanted to use both math.sin and nump.sin you would either need to import the modules only and prefix using the module name, or import the functions and rename them like this:
from numpy import sin as np_sin
from math import sin
from numpy import sin
print sin(2)
https://docs.python.org/2/tutorial/modules.html read this in details

Categories