Functions as objects

Writing Functions in Python

Shayne Miel

Software Architect @ Duo Security

Functions are just another type of object

Python objects:

def x():
  pass

x = [1, 2, 3]
x = {'foo': 42}
x = pandas.DataFrame()
x = 'This is a sentence.'
x = 3
x = 71.2
import x
Writing Functions in Python

Functions as variables

def my_function():
  print('Hello')

x = my_function
type(x)
<type 'function'>
x()
Hello
PrintyMcPrintface = print

PrintyMcPrintface('Python is awesome!')
Python is awesome!
Writing Functions in Python

Lists and dictionaries of functions

list_of_functions = [my_function, open, print]

list_of_functions[2]('I am printing with an element of a list!')
I am printing with an element of a list!
dict_of_functions = {
  'func1': my_function,
  'func2': open,
  'func3': print
}

dict_of_functions['func3']('I am printing with a value of a dict!')
I am printing with a value of a dict!
Writing Functions in Python

Referencing a function

def my_function():
  return 42

x = my_function

my_function()
42
my_function
<function my_function at 0x7f475332a730>
Writing Functions in Python

Functions as arguments

def has_docstring(func):
  """Check to see if the function 
  `func` has a docstring.

  Args:
    func (callable): A function.

  Returns:
    bool
  """
  return func.__doc__ is not None
def no():
  return 42

def yes():
  """Return the value 42
  """
  return 42
has_docstring(no)
False
has_docstring(yes)
True
Writing Functions in Python

Defining a function inside another function

def foo():
  x = [3, 6, 9]

  def bar(y):
    print(y)

  for value in x:
    bar(x)
Writing Functions in Python

Defining a function inside another function

def foo(x, y):
  if x > 4 and x < 10 and y > 4 and y < 10:
    print(x * y)
def foo(x, y):
  def in_range(v):
    return v > 4 and v < 10

  if in_range(x) and in_range(y):
    print(x * y)
Writing Functions in Python

Functions as return values

def get_function():
  def print_me(s):
    print(s)
  # returns the function 'print_me'
  return print_me
new_func = get_function()
new_func('This is a sentence.')
This is a sentence.
Writing Functions in Python

Let's practice!

Writing Functions in Python

Preparing Video For Download...