How do I call an inner function in one py file from another py file?

38 Views Asked by At

Trying in a loop_file.py to import an inner function defined in stats_file.py, imported in shared_data.py file, but I experience only to be able to call the outer function. shared_data.py file is used for other similar purposes as well...this is what I got:

stats_file:

# Outer function:
def one_function():

    # Inner function

    threshold = 1
    # Define a function to do some calculation 
    def some_function(variable_1, variable_2, variable_3):
        outcome_text = ""

        if x > y > threshold:
            if ratio <= 0.69 * threshold:
                outcome_text = "text 1"
            elif ratio <= 0.70 * threshold:
                outcome_text = "text 2"
            elif ratio >= 0.80 * threshold:
                outcome_text = "text 3"
            elif ratio >= 0.90 * threshold:
                outcome_text = "text 4"
            else:
                outcome_text = "text 5"
        else:
            outcome_text = "text 6"

        return outcome_text

    # Define a function to get the outcome text
    def get_outcome_text(variable_1, variable_2, variable_3):
        outcome_text = some_function(variable_1, _2, etc)
        return outcome_text

    outcome_text = get_outcome_text(variable_1, variable_2, variable_3)
    print(outcome_text)

shared_data file...not recognising the inner function: some_function(variable_1, variable_2, variable_3):

from stats_file import some_function

loop file - even when directly importing some_function -- i.e. not via shared_data, some_function is not recognised:

from shared_data import some_function

or

from stats_file import some_function

How do I reach some_function either directly from stats_file.py or via shared_data.py? Any support out there is highly appreciated

1

There are 1 best solutions below

0
Rustem Zakiev On

You have these functions defined within a scope of one_function so you would not be able to call them anywhere out of that scope.

If you want to reuse these functions, you want to move them to the scope one level higher.

something like this:

def some_function(variable_1, variable_2, variable_3):
    ...  # your code


def def get_outcome_text(variable_1, variable_2, variable_3):
    ... # your code


def one_function():
    outcome_text = get_outcome_text(variable_1, variable_2, variable_3)
    print(outcome_text)

and now you can both use them in one_function and any other place of your python file or import it to other python files/modules.