python - Usage of unary operators applied to ternary operator arguments (eg *operator argument applied to string) -


here's doing:

def func(a,b=1,*args):     print('a:',a,'b:',b,'args:',*args if args else 'no args') func(1,2) 

here's expected:

#a:1 b: 2 args: no args 

here's got:

#a:1 b: 2 args: n o  r g s  

the * operator unpacking 'no args' string. here's should have been doing:

#produces expected result:  def func(a,b=1,*args):     print('a:',a,'b:',b,'args:',*args if args else ['no args']) 

so * operator gets applied entire ternary statement. not seem happen - operator:

def func(a,b=1,*args):     print('a:',a,'b:',b,'negative args[0]:', -args[0] if args else 1000000) func(1,2) #expected result: #a:1 b: 2 negative args[0]: -1000000 #actual result: #a:1 b: 2 negative args[0]: 1000000 

the negative - operator not apply entire ternary statement, whereas * operator does. why? special * operator?

you found right way write code in your own answer:

def func(a,b=1,*args):     print('a:',a,'b:',b,'args:',*args if args else ['no args']) 

but doesn't answer question of "what special * operator".

the first thing notice * isn't operator @ all, it's part of function call syntax. in loose conversation (including within actual documentation), it's called "the splat operator", isn't of answer. (and same true conditional expressions, aren't operator expressions, it's still called "the ternary operator" or "the if-else operator".)

but, more importantly, if want treat both * , … if … else … (loosely) operators, have consider operator precedence. ternary operator binds more tightly splat operator, while doesn't bind more tightly negation operator.

so, it's asking "what special / operator" when write 2 / 3 * 5 , 2 - 3 * 5. - applies entire 3 * 5, / applies 3 because of operator precedence.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -