Home > OS >  Write a function to reduce duplicate code
Write a function to reduce duplicate code

Time:11-17

I have two very similar for loops, I want to have an inner function to reduce the duplicate codes, they look like this:

team_members = TeamMember.objects.all()
managers = Manager.objects.all()
for m in managers:
        name = f"{m.name.first_name} {m.name.last_name}"
//reset of the code are the same
for t in team_members:
        name = f"{t.member.first_name} {t.member.last_name}"
//reset of the code are the same

So the problem is managers and team_members querysets have different field names for people's names. If I want to write an inner function, how to solve the different field names?

CodePudding user response:

you could pass in m.name and t.member to that function which would allow it to access that item.

for m in managers:
    func(m.name)
for t in team_members:
    func(t.member)

def func(member):
    name = f'{member.first_name} {member.last_name}
    #Rest of code

CodePudding user response:

Tom Karzes solution in code:

team_members = TeamMember.objects.all()
managers = Manager.objects.all()
    
for group, attr_name in zip([team_members, managers], ['name', 'member']):
    for person in group:
        name = f"{getattr(person, attr_name).first_name} {getattr(person, attr_name).last_name}"

CodePudding user response:

Here is the inner function which will take objs as input and fetch the values based on objects attribute.

def inner_fun(objs):
    for obj in objs:
        if hasattr(obj, 'name'):
            name_obj = getattr(obj, 'name')
        else:
            name = getattr(obj, 'member')
        name = f"{name_obj.first_name} {name_obj.last_name}"
    return name

team_members = TeamMember.objects.all()
managers = Manager.objects.all()

team_name = inner_fun(team_members)
manager_name = inner_fun(managers)
  • Related