Different ways of writing a function call with parameters
Model.objects.create(
timestamp=datetime.datetime.now(), # The current time
name=f'{first_name} {last_name}', # The user's full name
foo=True if is_thing else False # Some boolean field
)
Everything is done inline.
Pros:
- Fewest total lines
- No intermediate variables created
Cons:
- Errors will point to the first line of
.create()
rather than the parameter - Text is denser, a bit harder to grep
- Line lengths can easily break the limit with indent + code + comment
# The current time
timestamp = datetime.datetime.now()
# The user's full name
name = f'{first_name} {last_name}'
# Some boolean field
foo = True if is_thing else False
Model.objects.create(timestamp=timestamp, name=name, foo=foo)
Parameters are separated from the function call.
Pros:
- Errors will point to the correct line
- Each line has more room for code/comments
- The function call is reduced to just
parameter=parameter
Cons:
- Parameter names are written redundantly, allowing for spelling mistakes/errors
- Intermediate variables hurt performance when done at scale
params = {}
# The current time
params['timestamp'] = datetime.datetime.now()
# The user's full name
params['name'] = f'{first_name} {last_name}'
# Some boolean field
params['foo'] = True if is_thing else False
Model.objects.create(**params)
Adding to Example 2; parameters are assigned to a dict, dict is expanded during function call
Pros:
- The function call looks the same no matter the number of parameters
- Parameter names are only written in one location
Cons:
- An extra line is added for the initialization of the dict