1

I have the following piece of code:

quantity_of_units = int(funding_time_left.split[0])
unit_of_measurement = funding_time_left.split()[1]
now = datetime.datetime.now()
if unit_of_measurement == 'days':
    end = (now + timedelta(days=quantity_of_units)).strftime('%Y-%m-%d')
elif unit_of_measurement == 'hours':
    end = (now + timedelta(hours=quantity_of_units)).strftime('%Y-%m-%d')
else: # unit_of_measure == 'minutes'
    end = (now + timedelta(minutes=quantity_of_units)).strftime('%Y-%m-%d')
funding.append([aeles.get_attribute('href'), end])

I was wondering if it is possible to use a variable (unit_of_measurement) as the keyword argument (days, hours, minutes)?

If it is indeed possible, I could scrap the if elif else block altogether and turn it all into a single line. Below is what I'm hoping to do.

quantity_of_units = int(funding_time_left.split[0])
unit_of_measurement = funding_time_left.split()[1]
now = datetime.datetime.now()
end = (now + timedelta(unit_of_measurement=quantity_of_units)).strftime('%Y-%m-%d')
funding.append([aeles.get_attribute('href'), end])
Taku
  • 31,927
  • 11
  • 74
  • 85
oldboy
  • 5,729
  • 6
  • 38
  • 86

1 Answers1

1

You can, by using ** to unpack a dict in the arguments, which sets them to be keyword arguments.

timedelta(**{unit_of_measurement: quantity_of_units})

The reason why it works is because that unpacks to:

timedelta(<unit_of_measurement>=quantity_of_units)

Where <unit_of_measurement> is minutes, seconds, days...


So you can replace your if... elif... else... statements with:

end = (now + timedelta(**{unit_of_measurement: quantity_of_units})).strftime('%Y-%m-%d')
Taku
  • 31,927
  • 11
  • 74
  • 85
  • can you elaborate. im new to python. im not sure what the `**` does nor why i would have to include both the `key` and `value` of the dictionary? – oldboy Jul 20 '18 at 05:10
  • @Anthony you can see this post if you're unsure what `**` does: https://stackoverflow.com/a/36926/6622817 – Taku Jul 20 '18 at 05:13
  • i've just edited my question. can you please look? thanks for the link, i'll check it out right now! – oldboy Jul 20 '18 at 05:14
  • Even after your edits, I'm still fairly confident that my solution can replace your `if... elif... else...` statements. Just give it a try :) – Taku Jul 20 '18 at 05:18
  • i'm goign to test this right now and ill mark as correct if it works – oldboy Jul 20 '18 at 05:21
  • so when i unpack the dict via `**{u:q}` it basically converts it to `u=q`??? instead of writing `timedelta(**{unit_of_measurement: quantity_of_units} = quantity_of_units)`, i can just write `timedelta(**{unit_of_measurement: quantity_of_units})`?? – oldboy Jul 20 '18 at 05:28
  • @Anthony correct, where `u` is the evaluated keyword argument string. – Taku Jul 20 '18 at 05:32
  • wow, that's amazing!! i'm amazed at all the cool stuff python is capable of doing!! – oldboy Jul 20 '18 at 05:33