1

Say I have a function:

def foo(x): if x % 2: do_something_with(x) return x 

And I want to make the doing of something opt-outable:

def foo(x, maybe_do_something_with_x=True): if maybe_do_something_with_x: if x % 2: do_something_with(x) return x 

That variable name is awful, but I'm not quite able to come up with something more concise.

What is the general practice?

6
  • 3
    Whilst not a duplicate of this question, it's worth highlighting it. What to call the flag is a minor issue compared with the whole (bad) idea of introducing a flag in the first place. Just don't do it. Commented Mar 27, 2019 at 11:17
  • The context is that I have some auto updating of a field in a django model .save(), and I'd like to be able to not have it happen if for whatever reason I'm in the shell putting out fires, and don't want the updating to happen. Commented Mar 27, 2019 at 11:21
  • I'm not really sure I understood context correctly, but overriding django base save doesn't sound like something you want to do especially to disable something. Could you ask a question about your original problem, possibly on SO, so we could help the best way possible ? Commented Mar 27, 2019 at 12:22
  • Overriding of those methods is exactly what you're meant to do. I've added automatic updating of a field in .save(), and have added the flag in question to the arguments to bypass the updating should one need to. Commented Mar 27, 2019 at 13:09
  • Ok, I understand better now. For some reason I thought you wanted to disable an update in django. Well my answer is the best I can provide you. Commented Mar 27, 2019 at 15:44

1 Answer 1

0

That variable name is awful, but I'm not quite able to come up with something more concise.

Long names aren't necessarily a problem as long as they explain well what is this variable. You could call it enable_x to stress the fact its a boolean that will enable a particular treatment. But using booleans to force an execution path should be avoided whenever possible.

What is the general practice ?

To avoid this kind of flag entirely. The most elegant design is to refactor using classes and overrides :

class A: def foo(x): start_of_foo(x) bar(x) remaining_of_foo(x) def bar(x): pass class B(A): def bar(x): do_something_with(x) 

Then you can use B() or A() based on situation

Alternatively, if you are reluctant to use a class for this :

def foo(x, mybar=bar): start_of_foo(x) mybar(x) remaining_of_foo(x) def bar(x): pass def specific_bar(x): do_something_with(x) 
1
  • Worth noting that the library in question uses flags such as these in the method I'm overriding. I like the idea of subclassing though. Commented Mar 27, 2019 at 12:02

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.