Arjuna
Arjuna

Reputation: 189

How to reuse functions in python

We are having some issue here. There are two python files parent and child in same folder. I want to reuse the function("sum") of parent in child, instead of copying the same function("sum") into child. Please refer the image below.

child.py

def add(a,b):
    sum(a,b)

parent.py

import child
def sum(a,b):
    print(a+b)
def main():
    child.add(1,2) # Prints 3

Upvotes: 1

Views: 5558

Answers (3)

Narendra
Narendra

Reputation: 1529

You can use it as:-

In child.py use:-

from parent import sum
def add(a,b):
    sum(a,b)

add(3,10) #output 13 as expected

Upvotes: 1

minboost
minboost

Reputation: 2563

Put sum() in a third module that is imported by both.

Upvotes: 3

havanagrawal
havanagrawal

Reputation: 1039

You can use imports:

In child.py

from parent import sum

Now you can use the sum function as you want.

Having said that, it looks like this question has multiple issues that will be a debugging nightmare

  1. Circular imports
  2. Overriding builtin functions

Consider reading a basic tutorial on Python imports and builtin functions.

Upvotes: 1

Related Questions