-1

Apologies if this is a straightforward thing, I’m just not having luck getting answers online (and if this isn’t a good place to post).

I’ve been trying to improve my Python, and I’ve been trying to make sense of some code for a Neural Network/Natural Language Processing package. I came across this:

if args.encoder_layers_to_keep:
        args.encoder_layers = len(args.encoder_layers_to_keep.split(","))

I haven’t come across an if statement with an expression like this. There’s no comparison between variables or anything. My only guess is that it returns a true or false value and works with that but I’m really not sure.

For reference, here’s the full script - https://github.com/pytorch/fairseq/blob/master/fairseq/models/transformer.py

I’d appreciate any help with this.

Thanks, Justin

  • 1
    If `args.encoder_layers_to_keep` has a boolean equivalent of `true` it will evaluate to true or if it has an integer value other than `0`, it will again evaluate to true. Otherwise, it will be false. Or empty string -> false while any other string -> true, as stated in the below answer. – muyustan May 10 '20 at 23:44
  • 1
    Does this answer your question? [if statement without a condition](https://stackoverflow.com/questions/43063267/if-statement-without-a-condition) – takendarkk May 10 '20 at 23:48
  • `args` is an object passed as an argument to a method. `encoder_layers_to_keep` is a property of args. Judging by the following line, it is expected to be a string. An empty string, `None` and `False` are examples of [falsy values](https://stackoverflow.com/a/39984051/567595) in python. The nested statement will only be executed if the property is a truthy value such as a non-empty string. – Stuart May 10 '20 at 23:49

1 Answers1

3

Empty sequences (e.g., lists, tuples, strings) evaluate to False. Non-empty sequences evaluate to True.

args.encoder_layers_to_keep seems to be a string variable. An empty string "" evaluates to False, and a non-empty string evaluates to True.

You can prove this to yourself by using the builtin function bool to convert to a boolean. Try bool("") and bool("foobar").

This is suggested in the Python style guide (PEP8):

For sequences, (strings, lists, tuples), use the fact that empty sequences are false:

if not seq:
if seq:

# Wrong:
if len(seq):
if not len(seq):
jkr
  • 17,119
  • 2
  • 42
  • 68
  • Thanks! I’ve been seeing these everywhere yet never in any tutorials or explanations online. So, does it have any other special uses over like `if variable = 0:` or is it just ‘proper notation’ per se? – Justin Cunningham May 11 '20 at 00:01
  • Nope, no special uses over `if variable == 0`. It's a bit of a shortcut, I guess, because you don't have to use `len` (the `len` of an empty sequence is 0). If this was the answer to your question, please select the green arrow to mark it as the answer. – jkr May 11 '20 at 01:56