0

Which is more pythonic?

A

def my_function(arg, p=0):
    while arg:
        # do something
         value = arg.pop()
        # save value with a name which uses p for indexing
    p+=1

or B

def my_function(arg):
    p = 0
    while arg:
        # do something
        value = arg.pop()
        # save value with a name which uses p for indexing
    p+=1

A part of me think its silly to include p as an argument to the function incase someone sets it to a weird a value. But at the same time I don't like having p=0 clutter up a function which is already very complicated.

3
  • Maybe not relevent to your question but "which is already very complicated" is a red flag if you want to do things in the pythonic way as your question suggests. Commented Jul 24, 2014 at 14:14
  • Some more detail would be useful. Looking at this code, it's not clear that p needs to be initialized to 0 at all before the loop runs; you could just initialize it to 1 after the loop. Commented Jul 24, 2014 at 14:39
  • If you're supposed to be indexing the items in arg, you can do for p, value in enumerate(arg). Commented Jul 24, 2014 at 14:42

2 Answers 2

5

Don't clutter up function parameters with locals. If it is not a parameter the caller should use, don't add it to your function signature.

In other words, you don't want anyone using help(my_function) and be surprised at what p might be for.


This isn't a hard and fast rule, of course; some critical-path functions can be made faster by using locals, so sometimes you'll see something like:

some_global = expensive_function()

def foo(bar, baz, _some_local=some_global):
    # code using _some_local instead of some_global

to make use of faster local name lookups. The _ at the start of the argument then tells you that the name is really an internal implementation detail you should not rely on.

Sign up to request clarification or add additional context in comments.

Comments

2

It depends on if p always has to start at 0 or not. If it does, then definitely go with option B. Don't give users an opportunity to mess with your code if it's not necessary.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.