1

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
3
  • 3
    Parent depends from child, and child depends from parent. This is a circular dependency, which is not a quite good idea in general. Commented Jan 24, 2018 at 6:18
  • You shouldn't want to do this, this creates a circular import where child.py needs parent.py and vice-versa. Commented Jan 24, 2018 at 6:18
  • The issues you are having are exactly why this is a bad design. Reconsider why you are doing it like this. Commented Jan 24, 2018 at 6:21

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

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.