1

What are some code structuring/programming techniques to avoid this:

  if url.netloc  == "www.youtube.com" or "youtu.be" or "soundcloud.com or //
  "instagram.com" or "vine.co" or ETC ETC
     do XYZ
sirvon
  • 2,547
  • 1
  • 31
  • 55
  • 2
    I do not think that means what you think it means. That is always True – Paul Draper Oct 31 '13 at 08:06
  • 1
    Your code is subtly very incorrect. Assuming `url.netloc` does not equal "www.youtube.com", Python will go on to the next part of the conditional (after the first `or`), and evaluate "youtu.be" as a *boolean*, which will **always** be True. – Jonathon Reinhart Oct 31 '13 at 08:07

2 Answers2

5

Following line

url.netloc == "www.youtube.com" or "youtu.be" or "soundcloud.com" or "instagram.com"

is like following:

(url.netloc == "www.youtube.com") or ("youtu.be") or ("soundcloud.com") or ("instagram.com")

and it always yield True because non-empty string is treated as truth value if used as predicates.

Use in instead as follow:

if url.netloc in ("www.youtube.com", "youtu.be", "soundcloud.com", "instagram.com", ..):

Alternatively use can use or, but it requires you to repeat or url.netloc == multiple times.

falsetru
  • 357,413
  • 63
  • 732
  • 636
1

The simplest, I guess, would be:

xyz_targets = ('www.youtube.com', 'youtu.be', ...)
if url.netloc in xyz_targets:
    doXYZ()

Or even:

actions = {'www.youtube.com': doXYZ,
                   'youtu.be': doXYZ,
                   ...
                   }
actions.get(url.netloc, doNothing)()

Or any variant on a similar idea which parses a config file for building xyz_targets or actions

falsetru
  • 357,413
  • 63
  • 732
  • 636
val
  • 8,459
  • 30
  • 34