简体   繁体   中英

How to properly import dictionary in python and how to modify imported dictionary

I have a file called other.py

from src.data import users_stats
from datetime import timezone, datetime
first_timestamp = round(datetime.now().replace(tzinfo=timezone.utc).timestamp())

def clear_v1():
    users_stats.clear()
    users_stats = {'channels_exist': [{'num_channels_exist': 0, 'time_stamp': first_timestamp}],
                'dms_exist': [{'num_dms_exist': 0, 'time_stamp': first_timestamp}],
                'messages_exist': [{'num_messages_exist': 0, 'time_stamp': first_timestamp}]}

another file called data.py

from datetime import timezone, datetime
first_timestamp = round(datetime.now().replace(tzinfo=timezone.utc).timestamp())
users_stats = {'channels_exist': [{'num_channels_exist': 0, 'time_stamp': first_timestamp}],
                'dms_exist': [{'num_dms_exist': 0, 'time_stamp': first_timestamp}],
                'messages_exist': [{'num_messages_exist': 0, 'time_stamp': first_timestamp}]}

I want to Initialise the dictionary(users_stats) with the data(like in data.py). And when clear_v1 is called i want the dictionary(now filled with other data as well) to go back to the initial state.

Whenever i call clear, it says reference before assignment, which i think the programs think that i called users_stats.clear() before assignment. But isn't the users_stats imported from data.py so it is assigned already?

I have tried deleting the line users_stats.clear() and adding global user_stats, but the dictionary doesn't go back to the initial state.

Question: how do you make the users_stats in data.py back to the initial state in clear_v1()?

Edit: Sorry didn't provide more details for the problem. my folder structure is like:

📦project-backend
 ┣ 📂src
 ┃ ┣ 📜data.py
 ┃ ┗ 📜other.py
 ┗ 📂tests
 ┃ ┗ 📜testing.py

the testing file looks like:

from src.data import users_stats
from src.other import clear_v1()

print(users_stats)
users_stats['messages_exist'][0] = 'changed'
print(users_stats)
clear_v1()
print(users_stats)

def clear_v1() looks like:

def clear_v1():
    users_stats = {'channels_exist': [{'num_channels_exist': 0,'time_stamp': first_timestamp}],
    'dms_exist': [{'num_dms_exist': 0, 'time_stamp': first_timestamp}],
    'messages_exist': [{'num_messages_exist': 0, 'time_stamp': first_timestamp}]}

and it prints

{'channels_exist': [{'num_channels_exist': 0, 'time_stamp': 1618783441}], 'dms_exist': [{'num_dms_exist': 0, 'time_stamp': 1618783441}], 'messages_exist': [{'num_messages_exist': 0, 'time_stamp': 1618783441}]}
{'channels_exist': [{'num_channels_exist': 0, 'time_stamp': 1618783441}], 'dms_exist': [{'num_dms_exist': 0, 'time_stamp': 1618783441}], 'messages_exist': ['changed']}
{'channels_exist': [{'num_channels_exist': 0, 'time_stamp': 1618783441}], 'dms_exist': [{'num_dms_exist': 0, 'time_stamp': 1618783441}], 'messages_exist': ['changed']}

Edit2: I solved it by trying similar thing to the answer like

def clear_v1():
    first_timestamp = round(datetime.now().replace(tzinfo=timezone.utc).timestamp())
    og_users_stats = {'channels_exist': [{'num_channels_exist': 0, 'time_stamp': first_timestamp}],
              'dms_exist': [{'num_dms_exist': 0, 'time_stamp': first_timestamp}],
              'messages_exist': [{'num_messages_exist': 0, 'time_stamp': first_timestamp}]}   
    users_stats.clear()
    users_stats.update(og_users_stats)

I am not sure what your issue is as far as "reference before assignment". It would have been helpful if you had provided a stacktrace. My directory structure is:

lib
   src
      data.py

I then set environment variable PYTHONPATH to point to directory lib . My file other.py is (or you can place other.py in directory lib ):

from src.data import users_stats
from copy import deepcopy

save_users_stats = deepcopy(users_stats)

def clear_v1():
    users_stats.clear()
    users_stats.update(save_users_stats)

# change users_stats:
users_stats['messages_exist'][0] = 'changed'
# copy the reference:
d = users_stats
print(d)
clear_v1()
print(d)

Prints:

{'channels_exist': [{'num_channels_exist': 0, 'time_stamp': 1618730138}], 'dms_exist': [{'num_dms_exist': 0, 'time_stamp': 1618730138}], 'messages_exist': ['changed']}
{'channels_exist': [{'num_channels_exist': 0, 'time_stamp': 1618730138}], 'dms_exist': [{'num_dms_exist': 0, 'time_stamp': 1618730138}], 'messages_exist': [{'num_messages_exist': 0, 'time_stamp': 1618730138}]}

After importing user_stats , other.py uses deepcopy to makes a deep copy of the dictionary as save_user_stats . Then clear_v1 clears and updates in place the current user_stats dictionary rather than assigning a new dictionary reference to user_stats in case there is a copy of the user_stats reference being used in which case that reference copy would still be pointing to the modified dictionary. As you can see, I have no problems referencing users_stats from function clear_v1 .

Note

Your code clears the users_stats dictionary but then reassigns a completely new dictionary to users_stats making the clear operation you performed totally superfluous. Moreover, in my sample code where I have made a copy of the reference to the users_stats dictionary, d , after calling your clear_v1 , my d would now be pointing to an empty dictionary. With my implementation of clear_v1 it is still pointing to the original clear_stats dictionary that has been simply updated with the original values. By the way, ending up with a copy of the reference to the dictionary is entirely possible. You could easily have a class that gets instantiated with this dictionary as follows:

class MyClass:
    def __init__(self, users_stats):
        self._users_stats = users_stats # this is a copy of the reference

    ... #etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM