chrisis
chrisis

Reputation: 119

How to pass the results of a function from one file to another file

I get error when I print the result of a function in the main file (named as INPUT.py). The functions are made in another file (named as ENGINE.py). The error is: AttributeError: module 'ENGINE' has no attribute 'cross_section' I cannot understand why do I get such error.

Here the code example:

#-- Main file: INPUT.py

class Duct:
    def __init__(self, width, height):
        self.width = width 
        self.height = height 
    
Duct_ret = Duct(0.1, 0.1)

Duct_ret.width= 0.4
Duct_ret.height= 0.3

import ENGINE as EN
print(EN.cross_section)

#-- Engine file: ENGINE.py

from INPUT import width, height

def cross_section(self,):
    c_s=height*width
    return c_s 

Error: AttributeError: module 'ENGINE' has no attribute 'cross_section'

Upvotes: 0

Views: 64

Answers (2)

Digvijay Patel
Digvijay Patel

Reputation: 1

@costaparas has given a very detailed answer.

I also played around with the given code to find a solution. While trying to figure this out, I found there are 2 issues with your code:

  1. You shouldn't be using import to get class variables in a different file.
  2. You are using top level imports in both files with circular dependency which is causing the error.

Solution:

INPUT1.py

class Duct:
    def __init__(self, width, height):
        self.width = width 
        self.height = height 
    
Duct_ret = Duct(0.1, 0.1)

Duct_ret.width= 0.4
Duct_ret.height= 0.3

from ENGINE import cross_section1 as cs
cs(Duct_ret.width, Duct_ret.height)

ENGINE.py

def cross_section1(width,height):
    c_s=height*width
    print (c_s)

Upvotes: 0

costaparas
costaparas

Reputation: 5237

This is happening because you have a circular dependency in your code.

In ENGINE.py, you import height and width and in INPUT.py you import ENGINE.

You should pass Duct_ret.height and Duct_ret.width to your helper function instead of importing it.

So instead of this:

import ENGINE as EN
print(EN.cross_section)

do this:

import ENGINE as EN
print(EN.cross_section(Duct_ret.height, Duct_ret.width))

and in ENGINE.py, define the function like this:

def cross_section(height, width):
    c_s = height * width
    return c_s

NOTE: you also have self as an argument to cross_section which isn't right since cross_section is not a class method -- you just need to pass the relevant arguments to the function (which your original code didn't).

Side note: you should move your import to the start of the file in INPUT.py for better style in this case.

Upvotes: 1

Related Questions