Python Forum
Variable scope - "global x" didn't work...
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Variable scope - "global x" didn't work...
#4
(Dec-24-2020, 08:13 PM)bowlofred Wrote: You call it a copy, but there are no copies made anywhere. When you pass an object to a function, if that object is mutable the function can modify it.

Here you pass dict1 to upd_dict1 on line 19. This function both modifies the object that is passed in, and returns another reference to that object.

Before line 19 you have two dictionaries: dict_1 and dict_2. After line 19, both variables point at the same object (the original dict_2 is discarded). Line 24 doesn't do anything because they are already the same. You can add a statement like:

print(f"dict_1 and dict_2 are the same object: {dict_1 is dict_2}"

Thank you. The thing I am trying to fix is that when I do this in a third-level function:

for curr_id in dict_1: # loop through the dictionary
# code code code
    dict_1[curr_id].incl_ips.append(ipaddress.ip_network(rng_chop[0] + "/" + str(myprefix), False))
# code code code
it appends the value in the loop iteration to THE SAME dictionary entry.

Also, from my OP, essentially dict_1_copy is discarded when I exit the function and recreated the next time the function is called?
Reply


Messages In This Thread
RE: Variable scope - "global x" didn't work... - by ptrivino - Dec-25-2020, 12:00 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to create a variable only for use inside the scope of a while loop? Radical 10 1,751 Nov-07-2023, 09:49 AM
Last Post: buran
  It's saying my global variable is a local variable Radical 5 1,183 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Delete all Excel named ranges (local and global scope) pfdjhfuys 2 1,803 Mar-24-2023, 01:32 PM
Last Post: pfdjhfuys
  Library scope mike_zah 2 849 Feb-23-2023, 12:20 AM
Last Post: mike_zah
Question Sqlite3 how to know when cursor.execute didn't return anything ? SpongeB0B 2 871 Dec-18-2022, 06:13 PM
Last Post: deanhystad
  code running for more than an hour now, yet didn't get any result, what should I do? aiden 2 1,514 Apr-06-2022, 03:41 PM
Last Post: Gribouillis
  Scope of variable confusion Mark17 10 2,866 Feb-24-2022, 06:03 PM
Last Post: deanhystad
  Variable scope issue melvin13 2 1,548 Nov-29-2021, 08:26 PM
Last Post: melvin13
  Getting a GET request output text into a variable to work with it. LeoT 2 3,036 Feb-24-2021, 02:05 PM
Last Post: LeoT
  DataFrame operations didn't change orginal HoldYourBreath 5 2,465 Jan-10-2021, 02:01 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020