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]
Function and Class Naming conventions An important aspect of naming is to ensure your classes, functions, and variables can be distinguished from each other. For example, one could use Camelcase and Pascalcase for functions and classes respectively, while reserving Snakecase or Hungarian notation for variable names.
Use getattr() to Assign a Function Into a Variable in Python The function getattr() returns a value of an attribute from an object or module. This function has two required arguments, the first argument is the name of the object or module, and the second is a string value that contains the name of the attribute.
Naming Convention for Functions So, similar to variables, the camel case approach is the recommended way to declare function names. In addition to that, you should use descriptive nouns and verbs as prefixes. For example, if we declare a function to retrieve a name, the function name should be getName.
Bottom line: you can't have two things simultaneously with the same name, be it a function, an integer, or any other object in Python. Just use a different name.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With