Alex Alex - 4 months ago 10
Python Question

Python naming convention for variables that are functions

Does Python have a naming convention for variables that are functions? I couldn't see anything specific for this in PEP-8 (other than naming variables).

Since functions are first-class objects in Python, is using a

_fn
suffix, or something similar, a recognized convention?

EDIT: Updated with more realistic example

Example:

def foo_a():
print 'a'

def foo_b():
print 'b'

funcs = {'a': foo_a, 'b': foo_b}

# dynamically select function based on some key
key = 'a'
foo_fn = funcs[key]

Answer

Does Python have a naming convention for variables that are functions?

No it does not, functions are first class objects in Python. Pass the function name as you would access it for calling.

For example:

def foo():
    pass

foo() # calling

another_function(foo) # passing foo

One of the hardest things in programming is getting naming right, however. I would certainly use a more descriptive name, probably one that is a verb. For example:

def do_nothing():
    pass

EDIT: Same deal, but there's nothing to stop you from using _fn as a suffix if it makes your code clearer:

def foo_a():
    print 'a'

def foo_b():
    print 'b'

funcs = {'a': foo_a, 'b': foo_b}

# dynamically select function based on some key
key = 'a'
foo_fn = funcs[key]

foo_fn() # calling
another_function(foo_fn) # passing