Home > Software design >  How to reuse a function within a python module
How to reuse a function within a python module

Time:01-18

Im trying to reuse a function within another function of a Python module im writing. My search only reveals the same tutorial over and over again on how to write and use simple modules.

What I'm trying to do:

module.py:

def func1(num1, num2):
    return num1   num2

def func2(num1, num2, num3):
    return func1(num1, num2) * num3

main.py

import module as mod

num1 = 1
num2 = 2
num3 = 3

res = mod.func2(num1, num2, num3)

But this throws a NameError: NameError: name 'func1' is not defined

I think this happens because func1 from module.py has not been loaded in the kernel, but I don't know how to solve this without using from module import * which I really want to avoid.

Is there a way to reference func1 from within func2? Or any other way to specify, that func2 should load and use func1?

CodePudding user response:

I tried this and it worked without any problems with Ubuntu default Python 2.7

from module import func2
num1 = 1
num2 = 2
num3 = 3
res = func2(num1, num2, num3)
res
9
  •  Tags:  
  • Related