Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Import function from .py file with required modules

I am trying to do something fairly simple. I want to import a function from a .py file but use modules imported in my primary script. For instance the following function is stored

./files/sinner.py

def sinner(x):
  y = mt.sin(x)
  return y

I then want to run sinner using the math as mt

from sinner import sinner
import math as mt
sinner(10)

This not surprisingly throws an error

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-50006877ce3e> in <module>()
      2 import math as mt
      3 
----> 4 sinner(10)

/media/ssd/Lodging_Classifier/sinner.py in sinner(x)
      1 import math as mt
----> 2 
      3 def sinner(x):
      4   y = mt.sin(x)
      5   return y

NameError: global name 'mt' is not defined

I know how to handle this in R, but not in Python. What am I missing?

like image 206
mmann1123 Avatar asked Jul 03 '26 19:07

mmann1123


1 Answers

The math module does not exist in the sinner.py namespace. Unlike R, imported modules or packages do not span the global namespace. You need to import math in the sinner.py file:

import math as mt

def sinner(x):
  y = mt.sin(x)
  return y

Alternatively (and I really don't know why you'd do this), you can pass the module as an arg to the sinner function:

def sinner(mt, x):
  y = mt.sin(x)
  return y

And then you could pass different modules that implement the sin function:

from .sinner import sinner
import math as mt
import numpy as np
sinner(mt, 10)
sinner(np, 10)
like image 65
TayTay Avatar answered Jul 05 '26 12:07

TayTay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!