mmann1123
mmann1123

Reputation: 5295

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?

Upvotes: 3

Views: 3685

Answers (3)

ak_slick
ak_slick

Reputation: 1016

You need to import math in sinner.py. It will import the function with all it's dependencies in the file. if a dependency it not present in the file it will not work.

sinner.py

import math as mt

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

then in your other file...

from sinner import sinner
sinner(10)

Upvotes: 3

TayTay
TayTay

Reputation: 7160

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)

Upvotes: 5

Rambarun Komaljeet
Rambarun Komaljeet

Reputation: 646

You could also pass mt as a parameter to sinner

def sinner(x, mt): code

Upvotes: 0

Related Questions