8

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]
3
  • I don't know if there is a convention, but out of curiosity, why do you want to do this? Why not use foo directly? Commented Jul 21, 2015 at 15:53
  • Note that foo is also a "variable" (I think the term "name" is more appropriate) here, so it really does not matter if you assign or define. Commented Jul 21, 2015 at 15:56
  • @That1Guy the original example I gave was slightly contrived. I have updated with a more realistic example, whereby I have have to dynamically assign a function based on some logic. Commented Jul 21, 2015 at 16:05

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer, but I've just updated my question to add a slightly better example. In your case, what would you call the parameter to another_function?
@Alex what you're getting at is becoming more of a matter of opinion, and people will vote to close this. If the question is, "Is there a convention?" then the answer is "No". But if the question is, "What should I call this?" the question will be closed.
Thanks Aaron, yes I was interested to know if there was a convention.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.