1

I have two scripts, test1.py and test2.py, with the following contents:

# test1.py

box = []

def run():
    box.append(20)
    box.append(30)
    print(box)
    print(f'test1 {id(box)}')

    from test2 import b
    print(b)

if __name__ == '__main__':
    run()
# test2.py

from test1 import box

print(f'test2 {id(box)}')
box.append(40)
b = box

And this is the result I get when I run test1.py:

[20, 30]
test1 4320983560
test2 4320994504
[40]

In my opinion box is a mutable object, so the final result should be [20, 30, 40], but in fact, box in test1.py and test2.py has a different id and it looks not the same one. This confuses me, can anybody tell me why?

Xhhhhh
  • 35
  • 6
  • please don't send code as photo, send as code block – I'mahdi Aug 28 '21 at 10:24
  • Please, avoid [posting images of text](https://unix.meta.stackexchange.com/questions/4086/psa-please-dont-post-images-of-text). It is a better practice to transcribe them instead. – accdias Aug 28 '21 at 10:27
  • how is that the result when you run the test2.py?? i think you meant by running test1.py – alexzander Aug 28 '21 at 10:43
  • btw. good question. i've imported a list from a module and it had the same address in both scripts. your case is very interesting. – alexzander Aug 28 '21 at 10:52

1 Answers1

1

In test2.py when you imported test1 it went to the file, and imported a like it say on the first line:

a = []

It doesn’t matter that you first ran test1.py script and imported test2 from it. Once

from test1 import a

is imported, you only import an empty list. It doesn’t use the run function as well, this is happen only if test1 isn’t imported.

Eladtopaz
  • 1,036
  • 1
  • 6
  • 21