So, I am working on personal project which generates random data depending on locale, so, I have a below code
class _DataProto (DataProvider): # DataProto.py
value_dict = {}
data_obj = {'data':[]}
def get_name(self):
value_dict['name'] = self.name() # Method provided by DataProvider
def get_dob(self):
value_dict['dob'] = self.dob() # Method provided by DataProvider
def get_email(self):
value_dict['email'] = self.email() # SAME
def set_data(self):
# that calls all the method above
return self.value_dict
def get_multiple_data(self,quantity):
for _ in range(quantity):
self.data_obj['data'].append(self.set_data())
return data_obj # this returns multiple values but with same data in them,
# I have also tried with temp.append(self.value_dict) calling self.set_data() first
def get_multiple_data2 (self,quantity):
temp = []
for _ in range(quantity):
temp.append(self.set_data())
return temp # this also does same thing as above I have also tried with temp.append(self.value_dict)
class Data1(_DataProto, DataProvider1): # Data1.py
# DataProvier1 provides local based data
pass
# main.py
gh = Data1()
# gh.get_name(), gh.get_dob() and all works as expected
gh.get_multiple_data2(2) # returns {"data":[{valueA}, {same value as valueA}]}
for _ in range(2):
print(gh.set_data) # return different value everytime
I would like to implement method within _DataProto
that allows me to get data_obj with multiple values appended to it that are unique.
set_data
method alwasy return unique value.
CodePudding user response:
If the self.email()
and self.dob()
and self.name()
methods generate unique data every time they are called then you can change the set_data
method to call the methods above it every time it is called.
You will also want to copy the dictionary contents using deepcopy
as the return value from set_data
so that each iteration doesn't update the same dictionary.
from copy import deepcopy
class _DataProto (DataProvider):
value_dict = {}
def get_name(self):
value_dict['name'] = self.name()
def get_dob(self):
value_dict['dob'] = self.dob()
def get_email(self):
value_dict['email'] = self.email()
def set_data(self):
self.get_email()
self.get_dob()
self.get_name()
return deepcopy(self.value_dict)
def get_multiple_data(self, quantity):
data_obj = {'data': []}
for _ in range(quantity):
data_obj['data'].append(self.set_data())
return data_obj
You could also simplify your code by simply returning a new dictionary each time set_data
is called.
For example:
class _DataProto (DataProvider):
def set_data(self):
return {
'name': get_name(),
'email': get_email(),
'dob': get_dob()
}
def get_multiple_data(self, quantity):
data_obj = {'data': []}
for _ in range(quantity):
data_obj['data'].append(self.set_data())
return data_obj