Use Function Without Calling Module [duplicate] - python

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

Related

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]

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

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.

Could I find a variable in the bessel function in python?

I am using Python to solve an equation. I added the 'Bessel function' in scipy.special, It was working. Now I want to find a variable using Bessel function. For example, I added the order(1) and value(0.44005058574) in Python, but it is not working. (in order to find the variable, I also used solver)
How I can solve the problem?
import numpy as np
import scipy.special as sc
import math
from sympy import Symbol
from sympy.solvers import solve
x=Symbol('x')
y=sc.jn(1,x)-0.44005058574
print(solve(x))
As the output is hinting, the function scipy.special.jn does not know how to handle the object x from simpy. Instead, you should use a numerical approach
>>> from scipy import optimize
>>> f = lambda x: sc.jn(1, x) - 0.44005058574
>>> root = optimize.newton(f, 1.0)
>>> print(root)
0.9999999999848267

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.

python: importing module in package namespace

I wonder if there is some standard way to do something like
import scipy as sp
from scipy import interpolate as sp.interpolate
that is not allowed.
Specifically:
I'd like to know if there is some reason why the above is not allowed. If I'm developing my own package foo, it seems reasonable to pollute its namespace as little as possible.
Things like
import scipy as sp
__import__('scipy.interpolate')
do the job, but are not all that nice and the docs recommend not to use __import__, unless strictly necessarily. Similarly
import importlib
import scipy as sp
importlib.import_module('scipy.interpolate',sp)
does the job, but it is still ugly, even longer and puts importlib in the namespace...
Imported modules are treated like regular objects so if you really want to you can import a module and assign it to an arbitrary variable like so
import scipy as sp
from scipy import interpolate
sp.interpolate = interpolate
sp.interpolate will behave as expected, it just points to the interpolate module whenever you call sp.interpolate. They are the same object underneath, i.e
print sp.interpolate is interpolate
>>> True
Then to finally remove the original 'interpolate' pointer call
del interpolate

Categories