Skip to content

Instantly share code, notes, and snippets.

@birkholz
Created October 10, 2017 19:43
Show Gist options
  • Save birkholz/67f8c9bfc8b1737ae10c0e869752ea41 to your computer and use it in GitHub Desktop.
Save birkholz/67f8c9bfc8b1737ae10c0e869752ea41 to your computer and use it in GitHub Desktop.
Different ways of writing a python function call with parameters

Different ways of writing a function call with parameters

Example 1

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

Example 2

# 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

Example 3

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment