Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 476
Alex Avatar asked Jul 21 '15 15:07

Alex


People also ask

What is the naming convention for variables and functions?

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.

How do you name a variable in a function Python?

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.

What is the naming convention for functions?

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.

Can functions and variables have the same name Python?

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.


1 Answers

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
like image 107
Russia Must Remove Putin Avatar answered Nov 01 '22 10:11

Russia Must Remove Putin