Sharing a list between Python modules

Viewed 349

SO feedback motivated me to create a package with often used routines, so I don't have to copy/paste functions into new modules any more. This works well, but now I encountered a problem. My module 2 function f2 is supposed to be called from module 1 with a number n1. If list1 exists in module 1, f2 uses it to analyse n1, otherwise it has to create list2 from scratch for this analysis. My approach so far is to use optional arguments.

module1.py

from standardpackage.module2 import f2
list1 = [1, 2, 3]
n = 1
a = f2(n, list1)               #works with existing list1
b = f2(n)                      #works without list1

module2.py

def f2(n, *arg):
    if arg:
        list2 = arg[0]         #uses list1
    else:
        list2 = [3, 2, 1]      #uses its own list

    res = dosth(n, list2)      #code executed within module2
    return res

This approach does, what it is supposed to do, but imho it doesn't look clever. I know from experience, that list1 can be very long and f2() might be called millions of times. To create a copy of list1 every time, you call f2(), seems to waste time and memory space.

My question is: Can module 2 somehow use list1 from module 1?

I read on SO and tutorial websites about global variable sharing and understand now, why my global list1 approach didn't work. I've seen suggestions to bind module 1 to module 2, but I want to use module 2 in future projects, so I don't know the name of those modules. I've seen suggestions with threading and multiprocessing, but as a Python newbie, I didn't understand the relevance to my question. Any suggestions welcome. Thank you.

1 Answers

You can avoid copying by passing arg[0] to the dosth function directly, also did a few changes to your code

def f2(n, *arg):
    if not arg:
        list2 = [3, 2, 1]         
        return dosth(n, list2)

    return dosth(n, arg[0])
Related