-1

I have a lot of conditions to check, but condition evaluation is heavy (e.g. condition requires database access), so I have to check them lazily.

Normally, such check could be written in if clause:

if type in FOOD_PRIZES and Prize.objects.filter(type=type).exists():
    pass

If the number of conditions are increasing then if clause becomes ugly.

I can make list of condition lambdas and use all method, but it looks ugly too:

conditions = [
  lambda: type in FOOD_PRIZES,
  lambda: Prize.objects.filter(type=type).exists()
] 

if all(condition() for condition in conditions):
   pass

Is there a better way to make code shorter? Is there another ways to make conditions lazy?

potykion
  • 351
  • 1
  • 4
  • 9
  • 6
    You could do `if a == b == c == d:` – vaultah Feb 03 '18 at 16:30
  • This doesn't seem to be a python question since you state that the issue is due to query time. In that case, the python code makes no difference; it's a micro optimisation. – roganjosh Feb 03 '18 at 16:32
  • @vaultah I used `a == b` as an example. Condition could be something heavy like Django `exists` method. – potykion Feb 03 '18 at 16:32
  • 4
    Given that your objection is that your solution *"looks ugly"* and you ask for one that *"looks better"*, which is wholly based on your opinion, how do you even expect this to get answered? – jonrsharpe Feb 03 '18 at 16:33
  • 1
    @potykion what do your *actual* conditions look like? – vaultah Feb 03 '18 at 16:36
  • @jonrsharpe OK, is there a way to make code shorter that list of lambdas with `all` call? – potykion Feb 03 '18 at 16:36
  • 3
    Why do you want it to be *shorter*? – jonrsharpe Feb 03 '18 at 16:36
  • @jonrsharpe I like to write less code, but since shorter code does not mean better code, then my question is not about code style. Sorry for the confusion. – potykion Feb 03 '18 at 17:03

1 Answers1

0

Your best bet is to continue what you're doing — but put your fastest conditions to check first.

all() will short-circuit, meaning that as soon as a condition evaluates to False, it will stop processing conditions, saving you the time you would expend by running the other queries.

As for what looks best — that's up to you. But it's far better to have effective, readable code than "attractive" code! And short code isn't always better. Verbosity often makes code more readable to others.

Just be careful. For example, if subsequent conditions are dependent on the first, using all can break. For example, given x='6.5', if isinstance(x, float) and x>5.5 would work but all((isinstance(x, float), x>5.5)) would error.

jpp
  • 159,742
  • 34
  • 281
  • 339
j6m8
  • 2,261
  • 2
  • 26
  • 34