Intended audience: relatively experienced software engineers who don't know Python (yet).
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.
*args
: Variable arity arguments
- Also known as "non-keyword args"
- Similar to
argc
andargv
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
The Python with
keyword class __enter()__
and __exit()__
.
- Python evaluates the expression;
- Then calls
__enter()__
on the resulting value (context guard); - Then assigns whatever
__enter()__
returned to the variable given by as._ - Then executes the code body;
- Finally, no matter what has occurred, calls
__exit()__
(context guard).
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
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()
.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")
- `