Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-Python- Can I share functions from 2 scripts?

Tags:

python

import

I have 2 scripts and both need to use a function which is defined on the other script. I want to do something like this:

file1.py:

from file2 import function2
def function1():
    someCode...

... some code where I use function2...

file2.py:

from file1 import function1
def function2():
    someCode...

... some code where I use funcion1 ...

The problem is that it doesn't work and i don't know neither why nor how to fix it. How can I do it?

like image 219
Sergio Ferrer Sánchez Avatar asked Mar 26 '26 20:03

Sergio Ferrer Sánchez


2 Answers

Option #1 move function1 and function2 to a common file:

common.py:

def function1():
    # some stuff
    pass

def function2():
    # some stuff
    pass

And import function1 and function2 from common.

Option #2 use a local import instead:

def function1():
    someCode...

def some_method_where_function_2_is_used():
    from .file2 import function2
    ... some code where I use function2...
like image 82
2ps Avatar answered Mar 29 '26 10:03

2ps


The problem is that the code to run the function from the other file runs on import, so you end up with an endless cycle, which python doesn't like.

To fix, perhaps run the functions in two more separate .py s and define them in another two.

like image 35
Ben Stobbs Avatar answered Mar 29 '26 09:03

Ben Stobbs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!