Use a function from numpy in a python function - python

I'd like to define a function in Python which itself uses a function from numpy, namely, the sine function 'sin'. To simplify the problem, I've made a test function "sine_test.py" as follows:
import numpy
def sine_test(theta):
return numpy.sin(theta)
I also want to run this function from a script, named "use_sine_test.py" and saved in the same directory, which reads as follows:
import numpy
from sine_test import sine_test
u=sine_test(1)
I would expect this to define u as the sine of 1 radian, about 0.84. Both "use_sine_test.py" and "sine_test.py" are in the same folder (D:/Python). However, if I run the "use_sine_test.py" Python script using the run button, I get a "NameError: global name 'sin' is not defined" error as shown below.
Any ideas what might be causing this?
Best regards,
Kurt
%run D:/Python/use_sine_test.py
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
C:\Program Files\Enthought Python 7.2.2\lib\site-packages\IPython\utils\py3compat.py in execfile(fname, glob, loc)
166 else:
167 filename = fname
--> 168 exec compile(scripttext, filename, 'exec') in glob, loc
169 else:
170 def execfile(fname, *where):
D:\Python\use_sine_test.py in <module>()
1 import numpy
2 from sine_test import sine_test
----> 3 u=sine_test(1)
D:\Python\sine_test.py in sine_test(theta)
1 import numpy
----> 2 def sine_test(theta):
3 return numpy.sin(theta)
NameError: global name 'sin' is not defined

more a comment than an answer (but i cant put code properly in a comment):
does it work if you put the next code in one 'something.py' file, and than just do python something.py in your terminal.
import numpy
def sine_test(theta):
return numpy.sin(theta)
u=sine_test(1)
Just to see if it is something related to a bad install, or if it is something related to ipython, or if it is something to do with how your files interact with each other. This way the problem can be narrowed down a bit. If this works as it should, than it is related to how your files work with each other or to your ipython. The next step would than be to just test it in different files like you do, but not in ipython, but just in terminal to see if it works in python, and if it is not a ipython problem. Than if that works too, than it is probably related to your ipython.

All,
Following BrenBarn's comment, I've tried to restart the Code Editor in Canopy and it seems to work now:
Welcome to EPD's interactive data-analysis environment!
with pylab-backend: wx
Type '?' for more information.
Welcome to pylab, a matplotlib-based Python environment [backend: WXAgg].
For more information, type 'help(pylab)'.
%run D:/Python/use_sine_test.py
u
Out[2]: 0.8414709848078965
Thanks for your comments!

Related

NameError when trying to import function from another script

I've seen many posts on this and the solution always seems to be to add * when importing the original script to be able to access its functions. I have done this and still get the error.
I have a file called toolbox.py whose path is: /Users/justinbenfit/Desktop/Programming/Python/Explorium /transformations_deduping/ipynb/toolbox.py and contains the following:
def tz():
print('works')
Then I have a file called explorium_check_acceptable.ipynb whose path is: /Users/justinbenfit/Desktop/Programming/Python/Explorium /transformations_deduping/ipynb/explorium_check_acceptable.ipynb
and contains:
from toolbox import *
tz()
which results in:
NameError Traceback (most recent call last)
/var/folders/cf/ft88j_856fv5rk3whgs12d9w0000gq/T/ipykernel_20696/4114475549.py in <module>
2 import numpy as np
3 from toolbox import *
----> 4 tz()
NameError: name 'tz' is not defined
I don't know what else could be wrong unless you can't import functions from a .py file to a .ipynb file.
update:
I ran
!export PYTHONPATH=.
!python -m site
in one of my ipynb code blocks and got this:
sys.path = [
'/Users/justinbenfit/Desktop/Programming/Python/Explorium /transformations_deduping/ipynb',
'/Users/justinbenfit/opt/anaconda3/lib/python39.zip',
'/Users/justinbenfit/opt/anaconda3/lib/python3.9',
'/Users/justinbenfit/opt/anaconda3/lib/python3.9/lib-dynload',
'/Users/justinbenfit/opt/anaconda3/lib/python3.9/site-packages',
'/Users/justinbenfit/opt/anaconda3/lib/python3.9/site-packages/aeosa',
'/Users/justinbenfit/opt/anaconda3/lib/python3.9/site-packages/locket-0.2.1-py3.9.egg',
]
USER_BASE: '/Users/justinbenfit/.local' (exists)
USER_SITE: '/Users/justinbenfit/.local/lib/python3.9/site-packages' (exists)
ENABLE_USER_SITE: False
To debug import issues, it is always helpful to view (and post on SO) the output of python -m site, which will reveal the contents of sys.path in a readable way.
You will usually want
export PYTHONPATH=.
or similar, to ensure that current directory is in sys.path.
Notice that you'll need that export
in the context of the running python kernel,
when you start it.
Also, the current working directory
at time of starting will make a difference.
Inspect sys.path within your notebook to verify,
perhaps using:
from pprint import pp
import sys
pp(sys.path)
It appears you have this module in your path:
https://pypi.org/project/toolbox
Try
from toolbox import Item
to verify that.
Also, as a very generic way of testing such import details,
a rename to e.g. toolbox1.py is a good sanity check.
That is, we expect the import's success to track
whether it has caught up with the new name yet, or not.
A classic example is some poor student naming a file test.py.
Notice that python -c 'import test' always succeeds,
since there is a seldom-used builtin test module.
Prefer
from toolbox import tz
over the * format.
It makes your code easier to read and to analyze.
And here, it would offer a clearer diagnostic,
failing in the import statement rather than waiting until the tz() reference.

python calling function from another file while using import from the main file

I'm trying to use multiple files in my programing and I ran into a problem.
I have two files: main.py, nu.py
The main file is:
import numpy
import nu
def numarray():
numpy.array(some code goes here)
nu.createarray()
The nu file is:
def createarray():
numpy.array(some code goes here)
When I run main I get an error:
File "D:\python\nu.py", line 2, in createarray
numpy.array(some code goes here)
NameError: name 'numpy' is not defined
numpy is just an exaple, I'm using about six imports.
As far as I see it, I have to import all moduls on all files, but it creating a problem where certain modules can't be loaded twice, it just hang.
What I'm doing wrong and how can I properly import functions from another file while using imported modules from the main file?
I hope i explain it well.
thanks for helping!
I have years in python and importing from other files is still a headache..
The problmen here is that you are not importing numpy in "nu.py".
But as you say sometimes it's a little annoying have to import al libraries in all files.
The last thing is, How do you get the error a module cannot be imported twice? can you give me an example?
In each separate python script if you are using a module within you need to import it to access. So you will need to 'import numpy' in your nu.py script like below
If possible try keeping the use of a module within a script so you dont have import the same multiple times, although this wont always be appropriate

Module "x" has no attribute "y", creating my own module .py

I am trying to create my own module (mi_modulo.py) and move there all the functions that I have defined in my Jupyter Notebook script, so that it looks cleaner.
However, when I am trying to use these functions that I have already moved to the module, I am not able to use them all, and I get the following message:
module 'mi_modulo' has no attribute 'train4_data_import'
I have installed Anaconda 3.0 and I am running Python 3.7.0 through Jupyter Notebooks. (Forgive me if the expressions sound awkward, I know a bit of Python, but I am not really into all the installation, software, IDE, etc details.)
## mi_modulo.py ##
def train4_data_import(file_name):
df = pandas.read_excel(file_name)
force = df["Signal 1"].values[13:]
acceleration1 = df["Signal 2"].values[13:]
acceleration2 = df["Signal 3"].values[13:]
return force, acceleration1, acceleration2
def hola_mundo():
print("whatever")
## script ##
import pandas
import mi_modulo as mi
mi.hola_mundo()
mi.train4_data_import("Tren4.xlsx")
And this is what I get:
(I was going to show an image but I am not sure how to do that with this stackoverflow new form style)
whatever
AttributeError Traceback (most recent call last)
<ipython-input-18-69a38929f7e6> in <module>()
3 mi.hola_mundo()
4
----> 5 mi.train4_data_import()
AttributeError: module 'mi_modulo' has no attribute 'train4_data_import'
I don't understand why it is able to read one function but not the other.
----------------------------- EDIT 1 ----------------------------
Doing what U9-Forward suggests:
import pandas
from mi_modulo import *
hola_mundo()
train4_data_import("Tren4.xlsx")
I get now the following error:
whatever
NameError Traceback (most recent call last)
<ipython-input-25-e1885200beb7> in <module>()
3 hola_mundo()
4
----> 5 train4_data_import("Tren4.xlsx")
NameError: name 'train4_data_import' is not defined
In jupyter-notebook, sometimes you need to restart the kernel to import all the unsaved module you have. Also, you need to import all the dependency for the custom module within that module.
It is probably because you didn't press Ctrl+S or hit the save button on the file, it will probably work if you do that:
Ctrl+S
Or save button.
then run script.py and see it working :-)

A first use of python function

Sorry for the very silly question. I am a self-study beginner in python and I am having issues with using a function and calling it. I am coming from a MATLAB background so i was trying to do something similar.
Tools used: Python 2 in a Linux environment
As a test, I created a function that i called prthis (for "print this") within a file called also prthis.py. This function just takes a number as an input, and then outputs two numbers, respectively the same one and its square. I defined it like this:
#----------------------------------------
# content of the file prthis.py
#----------------------------------------
def prthis(x):
y=x*x
nb=x
return (y, nb)
#------------------------------------------
then, within the python prompt, I try to call the newly created prthis function, and I do this:
>>> import prthis
>>> g,t = prthis(7)
The import seems to be succesful, but when I try the function on two outputs variable called g and t , like above, i get the following error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
Perhaps I am too much MATLAB-izing my thinking. Does anyone has a suggestion on how to deal with this?
PS: it's my first question ever on stackexchange, so please could you let me know how to thank/accept valuable answers from other users? I do not wish to look like ungrateful to those who would try to help.
you are importing a module, not the function. If you want to import just the function you could do this:
from prthis import prthis
g,t = prthis(7)
but if you import the full module you have to define the module you are calling the function from as well:
import prthis
g,t = prthis.prthis(7)
you are successfully able to import prthis but this is not the correct way either you should try "from prthis import prthis. Refer this for a better understanding of calling a function.
What does it mean to "call" a function in Python?

can import numpy module but cannot use functionalities

i had succesfully installed numpy (numpy-1.6.2-win32-superpack-python2.7.exe). But, whenever i try to call any functions i am getting following the error below. Thanks in advance for help.
import numpy as np
if __name__ == "__main__":
k = np.arange(10)
AttributeError: 'module' object has no attribute 'arange'
Echoing one of the comments above (as I just had this problem, over 4 years later):
You probably named your file numpy.py. When trying to load a module, I believe the path checks the current directory first, and thus it isn't found.
For sanity, to check that it really is this issue, you should run the Python REPL (python) and type:
import numpy as np, followed by dir(np)
And you should see all of the actual functions as output.
This might also happen because you probably named your program file numpy.py (i made the same mistake)
try the following:
for x in dir(np):
print x
this should list all methods etc of your import, that way you can see if arange() is available.
you could also try
from numpy import *
and then just try:
print arange(10)
Can't think of much else. Odd that the import does not produce an error if arange is not there.

Categories

Resources