Functions Flashcards

1
Q

Preloading arguments

A

import os

def load_file(file, base_path=’/’, mode=’rb’):

__return open(os.path.join(base_path, file), mode)

f = load_file(‘example.txt’)

f.mode

‘rb’

f.close()

import functools

load_writable = functools.partial(loadfile, mode=’w’)

you know the rest.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

introspection

A

standard inspect module

inspect.getfullargspec() accepts a function, returns a tuple with:

  • args - list of argument names
  • varargs - the name of the variable positional argument (usually ‘args’)
  • varkw - name of the variable keyword argument (usually kwargs)
  • defaults - tuple of default values ofr explicit arguments
  • kwonlyargs - list of keyword only argument names
  • kwonlydefaults - dictionary of default values for keyword only arguments
  • annotations - dictionary of argument annotations

def example(a:int, b=1, *c, d, e=2, **f) -> str:

__pass

import inspect

inspect.getfullargspec(example)

FullArgSpec(args=[‘a’, ‘b’], varargs=’c’, varkw=’f’, defaults=(1, ), kwonlyargs=[‘d’,’e’], kwonlydefaults{‘e’:2}, annotations={‘a’: <class>, 'return': <class>})</class></class>

see p.62 to 67 for a full example on using this.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

uses for decorators

and a basic decorator

A
  1. Access control
  2. cleanup of temporary objects
  3. error handling
  4. caching
  5. logging

decorators remove boilerplate code and keep it somewhere handy.

decorators accept a function and return a function.

import functools

def suppress_errors(func):

__@functools.wraps(func)

__def wrapper(*args, **kwargs):

____try:

______return func(*args, **kwargs)

____except Exception:

______pass

____return wrapper

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

allow a decorator to accept arguments prior to being used as a decorator

A

import functools

def suppress_errors(log_func=None):

__def decorator(func):

____@functools.wraps(func)

____def wrapper(*args, **kwargs):

______try:

________return func(*args, **kwargs)

______except Exception:

________if log_func is not None:

__________log_func(str(e))

______return wrapper

____return decorator

use

@suppress_errors()

def some_func():

__return non_existant_variable

call it, no errors!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Decorator with or without arguments

A

import functools

def suppress_errors(func=None, log_func=None)

__def decorator(func):

____@functools.wraps(func)

____def wrapper(*args, **kwargs):

______try:

________return func(*args, **kwargs)

______except Exception as e:

________if log_func is not None:

__________log_func(str(e))

____return wrapper

__if func is None: ## we’re declaring log_func

____return decorator ## with log_func declared

__else:

____return decorator(func) #actually wrapper

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Decorator to create decorators

A

func is not none, this returns

def decorator(declar_dec):

__@functools.wraps(declar_dec)

__def final_dec(func=None, **kwargs):

____def decorated(func):

______@functools.wraps(func)

______def wrapper(*a, **kw):

________return declar_dec(func,a,kw,**kwargs)

______return wrapper

____if func is None:

______return decorated

____else:

______return decorated(func)

__return final_dec

declared decorators must contain 3 arguments

  1. function that will be decorated which should be called if appropriate
  2. a tuple of positional arguments supplied to the decorated function
  3. dictionary of keyword arguments supplied to decorated function

args and kwargs don’t get * and **. They are just placeholders to be put in func, as yet undefined.

@decorator #below passed as declar_dec

def suppress(func, args, kwargs, l_func=None)

__try:

____return func(*args, **kwargs)

__except Exception as e:

____if l_func is not None:

______l_func(string(e))

decorated(example)

@supress

def example():

__return variable_which_does_not_exist

example() ##doesn’t raise an error

def print_logger(message):

__print(message)

@supress(log_func=print_logger)

def example():

__return variable_which_does_not_exist

example()

global name ‘variable which_does_not_exist’ is not defined

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

function annotations

A

after the argument name, a colon signifies that an annotation is coming.

def prepend_rows(rows:”a list of strings”, prefix:”a string to prepend to each row”, ) -> “a new list of strings:

__return [prefix + row for row in rows]

or…

def prepend_rows(rows:list, prefix:str) -> list:

__return [prefix + row for row in rows]

simple. sorta useful. Extended examples are worth studying in the book. Page 78 onward.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

itertools

  • 18 methods
A

count:

count(10) == iterator starting at 10 and going forever.

cycle:

cycle(‘ABCD’) –> A B C D A B C D …

repeat:

repeat(10, 3) –> 10 10 10

chain: returns generator

list(chain(“ABC”, “DEF”)) == [‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’]

chain.from_iterable([‘ABC’, ‘DEF’]) –> A B C D E F

accumulate: p [, func]

accumulate([1,2,3,4,5]) –> 1 3 6 10 15

compress: data, selectors

compress(‘ABCDEF’, [1, 0, 1, 0, 1, 1] –> A C E F

dropwhile: pred, seq

dropwhile(lambda x: x <5, [1,4,6,4,1]) –> 6. 4. 1

filterfalse: pred, seq

filterfalse(lambda x: x%2, range(10)) –> 0 2 4 6 8

groupby: iterable [, keyfunc]

sub-iterators grouped by value of keyfunc

islice: seq, [start,] stop [, step]

seq[start:stop:step]

islice(‘ABCDEFG’, 2, None) –> C D E F G

starmap: func, seq

starmap(pow, [(2,5), (3,2), (10,3)]) –> 32, 9, 1000

takewhile: pred, seq #opposite of dropwhile

takwhile(lambda x: x<5, [1,4,6,4,1] – 1 4

tee: it, n

it1, it2, it3 … itn splits one itererator into n iterators

zip_longest: p, q, …

zip_longest(‘ABCD’, ‘xy’, fillvalue=’-‘) – Ax By C- D-

product: p, q, … [repeat = 1]

cartesion product, equivalent to nested for loop

product(‘ABCD’, repeat=2) –> AA AB AC … DC DD

permutations: p[, r]

r-length tuples all possible orderings, no repeats

combinations: p, r

r-length tuples, sorted, no repeats

combinations_with_replacement: p, r

r-length tuples, sorted, with replacements

How well did you know this?
1
Not at all
2
3
4
5
Perfectly