I am trying to adapt a singleton example from Real Python, and I have simplified the code for clarity.
# employees.py
class _EmployeeDatabase:
def __init__(self):
self._employees = {
1: {
'name': 'Mary Poppins',
'role': 'manager'
},
2: {
'name': 'John Smith',
'role': 'secretary'
},
3: {
'name': 'Kevin Bacon',
'role': 'sales'
},
4: {
'name': 'Jane Doe',
'role': 'factory'
},
5: {
'name': 'Robin Williams',
'role': 'secretary'
}
}
def employees(self):
return [Employee(id_) for id_ in sorted(self._employees)]
def get_employee_info(self, employee_id):
info = self._employees.get(employee_id)
if not info:
raise ValueError('invalid employee_id')
return info
class Employee:
def __init__(self, id):
self.id = id
info = employee_database.get_employee_info(self.id)
self.name = info.get('name')
self._role = get_role(info.get('role'))
employee_database = _EmployeeDatabase()
What I want is to replace the content of self._employees with a dictionary I generated from user input (called dict_employees if you will).
What would be the pythonic way to pass dict_employees to class _EmployeeDatabase?
What seem to be preventing me from passing the dictionary to the class are that
- If
employee_database = _EmployeeDatabase(dict_employees)takes place outside the moduleemployees.py,class Employeeloses access toemployee_database. - On the other hand, I do not want to naively import the module where
dict_employeesis generated for various reasons*.
Sorry in case this is a duplicate question but I am not familiar with Python enough to tell.
===========================
* You probably do not need to know but one reason is that dict_employees has already been generated before my program needs the employees.py module. Another reason is that my program is running multiprocessing and importing dict_employees will result in it being generated multiple times which is wasteful.
_EmployeeDatabase.__init__?employee_database = _EmployeeDatabase(dict_employees). But where would I put this statement? If it is outside the moduleemployees.py,class Employeeloses access toemployee_database; if it is left where it currently is, I seem to have to importdict_employeesfrom where it is born which I am trying to avoid for reasons explained at the end of my question.employee_database = _EmployeeDatabase(dict_employees)can be stated outside the module, if this is the right direction of thinking...