Writing Functions in Python
Shayne Miel
Software Architect @ Duo Security
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
def my_function(): print('Hello')
x = my_function
type(x)
<type 'function'>
x()
Hello
PrintyMcPrintface = print
PrintyMcPrintface('Python is awesome!')
Python is awesome!
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!
def my_function(): return 42 x = my_function
my_function()
42
my_function
<function my_function at 0x7f475332a730>
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
def foo():
x = [3, 6, 9]
def bar(y):
print(y)
for value in x:
bar(x)
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)
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