#!/usr/bin/env python # coding: utf-8 # # Asides # # This is a notebook that is a collection of 'cool things'. # # Either Language or Library features demonstrated in isolation, or 'clever' algorithms with better explanations. # # ## F-strings # # Introduced in [Python 3.6](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498), f-strings are now the simplest *and* fastest way to print values in interesting formats; # In[1]: val = 'world' print(f'hello {val}') # However, considering that the f-string effectively puts the entire kernel at your disposal, becareful not to get too clever, otherwise you end up with unreadable messes # In[2]: print(f'Hello {input("What is your name?")}!') # ## Walrus Operators # # Introduced in [Python 3.8](https://docs.python.org/3/whatsnew/3.8.html), a new language construct was added; the walrus operator; `:=` # # To understand why this is cool; start off with the case where it doesn't exist. # # For instance, we have some basic conditional logic; if a list is too long to be processed, complain about it # # In[3]: def check_input(a): if len(a) > 10: raise ValueError(f'List is too long; got {len(a)}, expected < 10') else: return a check_input(range(100)) # But we're calling `len` twice when we really don't have to (and `len` can have some nasty side effects on some types of iterators) # # The walrus operator allows us to 'grab' the value of the output of `len` while also comparing it; like this # In[ ]: def check_input(a): a_len = len(a) if a_len > 10: raise ValueError(f'List is too long; got {a_len}, expected < 10') else: return a check_input(range(100)) # In[4]: def check_input(a): if (a_len :=len(a)) > 10: raise ValueError(f'List is too long; got {a_len}, expected < 10') else: return a check_input(range(100)) # However, be careful with your brackets # In[7]: def check_input(a): if (a_len :=len(a) > 10): raise ValueError(f'List is too long; got {a_len}, expected < 10') else: return a check_input(range(100)) # In[ ]: