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]
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
Functions are only a subset of what in Python are callable objects. callable
is just an object type, such as are str
, list
or dict
. There is no convention for naming any of them and I, particularly, don't see a reason to why this would be any different with callable
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.