Skip to content

Instantly share code, notes, and snippets.

@abstractmachines
Last active August 25, 2022 01:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abstractmachines/138bc434723faee8d8b9f2bea70b5f2e to your computer and use it in GitHub Desktop.
Save abstractmachines/138bc434723faee8d8b9f2bea70b5f2e to your computer and use it in GitHub Desktop.
Python language

Python Handbook

Intended audience: relatively experienced software engineers who don't know Python (yet).

Python lambdas

Python isn't a "functional" language, but it has adopted some FP methods around 1994.

A function in Python:

def identity(x):
   return x

A lambda function in Python (a unary arity anonymous function without parentheses):

lambda x: x

Here's another one.

something_terse=lambda t: t.property_thing

^ What's it doing? This expression is a lambda function which takes t as unary arg, returns t.property_thing, and assigns the returned value of t.property_thing to something_terse variable.

Python *args and **kwargs

*args: Variable arity arguments

  • Also known as "non-keyword args"
  • Similar to argc and argv in C
  • Similar to the spread or rest operator ... in JavaScript
  • Example:
    def a_func(arg1, *argv): # Note that there's no need to _actually_ call it *args. That's just an idiomatic nomenclature.
       print(arg1)
       for arg in argv:
          print("next arg:", arg)
     
     a_func("hello", "I", "liek", "catz") # prints each one. Variadic!

**kwargs: Variable arity collection (dict) of arguments with key-value pairs

  • Example:
  def so_func(**kwargs):
     for key, val in kwargs.items:
        print("%s == %s &(key,val))
   
   so_func(first = "hello", mid = "I", last = "catz") # prints each

Python with keyword: context manager / context guard.

The Python with keyword class __enter()__ and __exit()__.

  1. Python evaluates the expression;
  2. Then calls __enter()__ on the resulting value (context guard);
  3. Then assigns whatever __enter()__ returned to the variable given by as._
  4. Then executes the code body;
  5. Finally, no matter what has occurred, calls __exit()__ (context guard).

Python getattr() method:

Returns the value of a named attributed of an object.

If not found, returns the default value supplied.

getattr(object, name, [default_value])

Uses:

  • The with keyword in Python is good for un-managed resources, like file streams
  • The classic example is opening a file:
    with open('file.txt', 'w') as f:
    f.write('hi there!')
    ``
  • Consider try/catch:
     # set things up:
     try:
       # do something
     finally:
       # teardown

Unit Testing in Python: UnitTest and Pytest

Pytest: native language features instead of special assertion methods like UnitTest

Test fixtures in Pytest can be shared by multiple test cases.

# decorator. Specify args to test function. 
# Should have same name that resource does
@pytest.fixture
def resource():
   return Resource()

UnitTest library

  • .assertEqual(expected, actual)
  • > python -m unittest : Execute Python Unit Test Module on the CLI

Exceptions: UnitTest

  • self.assert : Raises method
  • use context, with keyword:
    def test_missing_name(self):
    phonebook = PhoneBook()
    with self.assert Raises  (KeyError) ???
    phonebook.lookup("missing")
    • `
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment