'complex' function with string argument.

Steven D'Aprano steve at pearwood.info
Tue Mar 18 05:08:11 CET 2014


On Mon, 17 Mar 2014 21:22:18 +0200, Marko Rauhamaa wrote:

> Chris Angelico <rosuav at gmail.com>:
> 
>> On Tue, Mar 18, 2014 at 5:15 AM, Marko Rauhamaa <marko at pacujo.net>
>> wrote:
>>> Is "-2.0" a literal?
>>>
>>> What's the outcome of
>>>
>>>    -2.0.__str__()
>>
>> If you mean (-2.0).__str__(), then it returns '-2.0', but that proves
>> nothing.
> 
> The point is, you don't need to "philosophize" about complex literals
> when even negative numbers don't have literals in Python.

But Python *does* have complex (well, imaginary to be precise) literals. 
The j suffix to a number makes it complex:

py> type(2j)
<class 'complex'>


Complex numbers with both a real and imaginary component are not treated 
as literals:

py> import ast
py> ast.dump(ast.parse("2j"))
'Module(body=[Expr(value=Num(n=2j))])'
py> ast.dump(ast.parse("1+2j"))
'Module(body=[Expr(value=BinOp(left=Num(n=1), op=Add(), 
right=Num(n=2j)))])'


and in recent versions, the peephole optimizer optimizes them:

py> from dis import dis
py> dis("1+2j")
  1           0 LOAD_CONST               2 ((1+2j)) 
              3 RETURN_VALUE         



-- 
Steven



More information about the Python-list mailing list