3

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?

2
  • 2
    You need to do import math in sinner.py. Every module is its own namespace. When the main module imports sinner.py, it gets access to sinner.py's namespace: not the other way around. Commented May 22, 2018 at 14:40
  • 1
    Possible duplicate of Python: why can't an imported module reference another imported module? Commented May 22, 2018 at 14:42

3 Answers 3

5

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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)

2 Comments

Yep that works. Thought I had tried that, but apparently I mistyped something... silly.
@mmann1123 If this is correct do you mind selecting it as the answer to help others in the future.
0

You could also pass mt as a parameter to sinner

def sinner(x, mt): code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.