DEV Community

loading...

Discussion on: API Design: Optional Parameters

Collapse
rhymes profile image
rhymes

Really good article, thank you Sam!

Collapse
samwho profile image
Sam Rose Author

Thank you so much! I'm glad you enjoyed it. If you don't mind, could you spare a few minutes to tell me things you like and didn't like? I'm looking to level up my writing. :)

Collapse
rhymes profile image
rhymes

ahha nothing I didn't like, the builder in Java is very verbose :D

BTW a little trick by more recent Python versions. You explained the problem with optional parameters, because you can do things like this:

>>> def get(url, follow_redirects=False, headers=None):
...     pass
...
>>> get("https://example.com")
>>> get("foobar", 3)

And for a reader it's not easy to know if 3 is referred to either parameter, or at least is not explicit at all which makes life complicated with many arguments to specify.

Since recently you can do this:

>>> def get(url, *, follow_redirects=False, headers=None):
...     pass
...
>>> get("foobar")
>>> get("foobar", True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: get() takes 1 positional argument but 2 were given
>>> get("foobar", follow_redirects=True)

The compiler now forces you to specify the name of each optional argument

Thread Thread
samwho profile image
Sam Rose Author

Oh that's super nice, I had no idea that was possible!

Thread Thread
rhymes profile image
rhymes

Yeah, it can also become a catch all for all unnamed optional parameters.

>>> def get(url, *args, follow_redirects=False, headers=None):
...     print(f"u: {url}, a: {args}, f: {follow_redirects}, h: {headers}")
...
>>> get("https://dev.to")
u: https://dev.to, a: (), f: False, h: None
>>> get("https://dev.to", 1, 2, 3)
u: https://dev.to, a: (1, 2, 3), f: False, h: None
>>> get("https://dev.to", 1, 2, 3, follow_redirects=True, headers={"user-agent": "acme"})
u: https://dev.to, a: (1, 2, 3), f: True, h: {'user-agent': 'acme'}
>>> get("https://dev.to", follow_redirects=True, headers={"user-agent": "acme"})
u: https://dev.to, a: (), f: True, h: {'user-agent': 'acme'}