History of Python Wiki

The Zen of Python

import this
T B E S C F S R S A E U I T A N A I I N h e x i o l p e p l r n n h l o l f f a e a p m m a a a e t r l e t w t m u l p p t r d c h o e t r h h t t e Z t i l l s a i o r s h e o i o h h s e i c e e i e b a u s s e u s u e e p n f i x s i l g s g g a u t i i l h s e f h h b h i i c o l s i b s i c h x a o e m m e f i s e t a p o p c u t t n p p s i s b t b y s r u l e l h t e l l P s e b t e e a l i d a e v e e a y b t e e t c s c d c o t r e m m r t b e t t r t o t i f b r e e e h e t e t e u a i n t e w t n n o t t r e t r n r c e l a a h i t t o n t e r h t e a v y m o y a s a a n , e r t a t s n l e b n n t t e r h t n h . ' i r s i e m o i i b t a h a t t i g - a n f o o h y t h n a n n y p l u - y e t n n o h a n e s a e i v e n T a n c s d p b s n t a n e n i i k i n o c t e e e s c y n o r s s i m i m o e n c a e , d t . b n u m p m d s i t s d e h e g P g p l p . e a s i . r p b t a a e l l e l . l l e r e t r s g t y i x i p e f e e d y r e . c . c e u n u f o r e r i a n r t s e b t t a s t t o i l e r v t o o t . e u t y a i h d g y . t b o a e e i . h . h l u n x x d e y s p p e t * l l a o t o a r a a e n t i i i b m l g n n r p y f h , , e t i t l a a o r * i i e k t n s t t t i e t n ' ' t o o s m s h n u w a e n . a y d t o l o r o b e b b u v s a e m l g i s d o e u o a r s e u y i e . s s o d g s u e o o . w ' a o f a r . d y e t i h t D d o o u e s t a e d c . ! o h . i t .

Python Class Descriptors

Build in descriptors

type() - class type

>>> class MyClass:
...     def __init__(self):
...         self.data = 0
...     def add_one(self):
...         self.data += 1
...
>>> mc = MyClass()
>>> type(mc)
<class '__main__.MyClass'>
>>>

dir() - class directory

>>> dir(mc)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'add_one', 'data']
>>>

vars() - class variables

>>> vars(MyClass)
mappingproxy({'__module__': '__main__', '__init__': <function MyClass.__init__ at 0x10ff374c0>, 'add_one': <function MyClass.add_one at 0x10ff37740>, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None})
>>>
>>> vars(mc)
{'data': 0}
>>>

id() - memory location

>>> hex(id(MyClass))
'0x7fe6fa806260'
>>>
>>> hex(id(mc))
'0x10ff38b50'
>>>

Using F strings

Formatting a string is probably the number one task you’ll need to do almost daily. There are various ways you can format strings in Python; my favorite one is using f strings.

# Formatting strings with f string.
str_val = 'books'
num_val = 15
print(f'{num_val} {str_val}') # 15 books
print(f'{num_val % 2 = }') # 1
print(f'{str_val!r}') # books

# Dealing with floats
price_val = 5.18362
print(f'{price_val:.2f}') # 5.18

# Formatting dates
from datetime import datetime;
date_val = datetime.utcnow()
print(f'{date_val=:%Y-%m-%d}') # date_val=2021-09-24

Unfold List

Builds a list, using an iterator function and an initial seed value.

  • The iterator function accepts one argument (seed) and must always return a list with two elements ([value, nextSeed]) or False to terminate.
  • Use a generator function, fn_generator, that uses a while loop to call the iterator function and yield the value until it returns False.
  • Use a list comprehension to return the list that is produced by the generator, using the iterator function.

Code

def unfold(fn, seed):
  def fn_generator(val):
    while True:
      val = fn(val[1])
      if val == False: break
      yield val[0]
  return [i for i in fn_generator([None, seed])]

Use

f = lambda n: False if n > 50 else [-n, n + 10]
unfold(f, 10) # [-10, -20, -30, -40, -50]

Sorting Dictionaries

>>> people = {3: "Jim", 2: "Jack", 4: "Jane", 1: "Jill"}
>>> print(f"unsorted     = {people}")
unsorted     = {3: 'Jim', 2: 'Jack', 4: 'Jane', 1: 'Jill'}
>>>
>>> key_sorted = dict(sorted(people.items()))
>>> print(f"{key_sorted   = }")
key_sorted   = {1: 'Jill', 2: 'Jack', 3: 'Jim', 4: 'Jane'}
>>>
>>> value_sorted = dict(sorted(people.items(), key=lambda item: item[1]))
>>> print(f"{value_sorted = }")
value_sorted = {2: 'Jack', 4: 'Jane', 1: 'Jill', 3: 'Jim'}
>>>

Delete First Item in Dictionary

del value_sorted[next(iter(value_sorted))]

Indexing Combonations

>>> import itertools
>>> a = [7, 5, 5, 2]
>>> list(itertools.combinations(enumerate(a), 2))
[((0, 7), (1, 5)), ((0, 7), (2, 5)), ((0, 7), (3, 3)), ((1, 5), (2, 5)), ((1, 5), (3, 3)), ((2, 5), (3, 3))]
>>> list((i,j) for ((i,_),(j,_)) in itertools.combinations(enumerate(a), 2))
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
>>>