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
Related
I want to import the random.sample() method, but I can either import the whole library by typing import random or lose the namespace by typing from random import sample.
How can I just import the single method but a able to call it with random.sample()? Is there a elegant way to do it?
Is it okay to call any numpy function without using the library name before the function (example: numpy.linspace())? Can we call it simply
linspace()
instead of calling
numpy.linspace()
You can import it like this
from numpy import linspace
and then use it like this
a = linspace(1, 10)
yes, its completely fine when you are importing the function separately from the numpy such as
from numpy import linespace
#you can call the function by just writing its name
result=linespace(3,50)
but the convention is to use the name alias the pakage as np
import numpy as np
#then calling the function with short name
result = np.linespace(3,50)
alias can be helpful when working with large number of libraries.and it also improves the code readability.
If you import the function from the library directly there is nothing wrong with calling said function directly.
i.e.
from numpy import linspace
# Then call linspace by itself
a = linspace(1, 10)
That being said, many find that having numpy (often shortened to np) in front of function names help improve code readability. As almost everyone does this with certain libraries (Tensorflow as tf, Numpy as np, Pandas as pd) some may view it in a poor light if you simply directly import and use the function.
I would recommend importing the library as the shortened name and then using it appropriately.
i.e.
import numpy as np
# Then call np.linspace
a = np.linspace(1, 10)
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.
Cufflinks provides an interface between Panda's DataFrame and plotly iplot in the form of DataFrame.iplot. The first two output examples below do not surprise me, but the third does. Each is run in a new instance of iPython3.
import pandas as pd
pd.DataFrame.iplot
Out[1]: AttributeError: type object 'DataFrame' has no attribute 'iplot'
import pandas as pd
import cufflinks as cf
pd.DataFrame.iplot
Out[1]: <function cufflinks.plotlytools._iplot>
import cufflinks as cf
import pandas as pd
pd.DataFrame.iplot
Out[1]: <function cufflinks.plotlytools._iplot>
In the first we see pd.DataFrame does not contain iplot by default. When cufflinks is imported after Pandas in the second example, it could easily add an extra method to the DataFrame class to provide additional functionality. However, in the third method the DataFrame class will be defined during the import pandas statement after cufflinks has been imported. How is the additional method still added? This is definitely convenient, as my understanding of how the middle example could work would require always importing the libraries in order, which is undesirable, so I would be interested to know the trick used here.
I'm fairly sure this is because python caches the modules it loads. For example, all of the below expressions are true:
import sys.modules
import pandas as pd
import pandas as pds
print(pd is pds)
print(pd is sys.modules['pandas'])
print(pds is sys.modules['pandas'])
prints:
True
True
True
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