Skip to content
Advertisement

Is there a better way to use a function from a different .py file?

I am making an agent that uses different sets of functions to solve different types of problems. My issue is – there are many different types of problems to solve, so I have many, many different functions that the agent needs to use. My main .py file is likely going to end up at least 1000 lines, which I’d like to avoid.

To fix this problem, rather than having all the functions defined in the main .py file, I would like to add a folder to my current directory and, in that folder, have different .py files for each type of problem (each set of functions). I then want those functions accessible to the agent class in my main .py file.

I figured out a way to do it but I don’t know if this is the best way. Here is what I did:

in main .py file:

#testing process to import methods from other py file
from methods import general as gen

class Agent:
    def __init__(self):
        Agent.method_one = gen.method_one(self)

    def solve(self):
        self.method_one()

agent = Agent()
agent.solve

in methods/general.py

def method_one(self):
    print('you did it bro')

Is there a better way to do this? Any thoughts/help will be appreciated.

Advertisement

Answer

I think you can just create the file for each of your function and import these files to your main.py file. The functions in the other files will be accessible once you import those files to your main.py file.

For example: For a.py:

def main():
    print("Hi")

For main.py:

import a
a.main()  # prints "Hi". 

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement