-1

New to python but can't figure out why this isn't allowed:

Pylance gives

For line 2 "{" was not closed

For line 4 [ was not closed

For line 5 Parsing failed: 'invalid syntax

    drop_down_fields = [
            {
                "checked": 
                [
                    if config_data.selected_options is not None:
                        i for i in config_data.selected_options if i in all_options
                    else:
                        config_data.selected_options
                ],
                "items": all_options,
                "name": CONF_SELECTION_A,
                "enabled": True,
            },
            {....other list items like the one above

If I don't put the if/else in for 'checked' and just have the 'i for i...' line it works but config_data.selected_options can be None so trying to avoid that exception ('nonetype' object is not iterable).

The situation is that selected_options may contains values from a previous execution that no longer exist in all_options. So I want to keep the selected_options minus those that don't exist in all_options. Those will just get dropped. If there hasn't been a previous execution then selected_options can be None which is fine and in which case nothing will be 'checked'.

Trying to avoid creating another list object outside the drop_down_fields assignment.

Update:

Changed it to an expression of:

    "checked": 
                    [
                        config_data.selected_options if config_data.selected_options is None
                            else i for i in config_data.selected_options if i in all_options
                        
                    ],

No formatting errors but during runtime it's back to the 'nonetype' error due to, I assume, iterating selected_options even though it's None

Update 2: I needed to wrap the else content in {}. No erroring but still looping through the select_options list that is 'None'

justaguy
  • 1
  • 1
  • 2
    You're trying to embed statements in an expression. Python doesn't allow this. Replace the `if`-`else` with an expression, not a statement. – Tom Karzes Dec 05 '22 at 04:44
  • Thanks! That may have done it once I got my formatting right. Testing now. – justaguy Dec 05 '22 at 05:03
  • Back to nonetype error during runtime. Edits above – justaguy Dec 05 '22 at 05:28
  • you might be able to use a ternary there instead `A if B else C`, but if you find you're packing a lot of logic into a small space, there's almost-certainly a better way to get what you're after – ti7 Dec 05 '22 at 05:42
  • I did the ternary expression but it seems to still be looping through the selected_options list even though it's None – justaguy Dec 05 '22 at 05:52

1 Answers1

0

Maybe you can do

"checked":  None if config_data.selected_options is None
                else i for i in config_data.selected_options if i in all_options
                        
                    ,
Cshitiz Dhingra
  • 155
  • 1
  • 11