Home > Enterprise >  Call Python function w/ values from a locally set up module
Call Python function w/ values from a locally set up module

Time:10-22

I have a module named my_math set up with basic functions inside, such as:

def triangle(base, height):
    return base*height/2

When I import my_math in the terminal (python3) and call the function w/ parameters like this it gives me the answer:

>>> import my_math
>>> my_math.triangle(2, 8)
8.0

However, if I place the values for base and height inside or outside in the function in the my_math module and try to call the function using those values, I receive an error:

# my_math.py
base = 3
height = 4

def triangle(base, height):
    # base = 3
    # height = 4
    return base*height/2

# trying it at the interpreter prompt
>>> my_math.triangle(base, height)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'base' is not defined. Did you mean: 'False'?

How can I make the code use the values defined in the module instead?

CodePudding user response:

One option is to import all variables and methods from the module, like so:

from my_math import *

triangle(base,height)
# returns 6

Alternatively, you could statically reference the variables directly from the module:

import my_math

my_math.triangle(my_math.base, my_math.height)
# returns 6

CodePudding user response:

I'm not sure why you'd want to do this, and it's usually better to just put in the parameters each time.

You could set default parameters for your functions like this:

def myFunction(value1 = 10, value2 = 10):
   pass

this will set the values to 10 if nothing is passed in for them: more on this

But as far as I'm aware, this really doesn't work and it's better practice to pass in your arguments each time.

CodePudding user response:

In Python, variables are defined only locally unless otherwise specified. This means that in the scope of your function, those variables are not defined. Declaring them as globals should fix your issue:

global base
base = 3
global height
height = 4

def triangle():
    global base
    global height
    # base = 3
    # height = 4
    return base*height/2
  • Related