Search code examples
pythontokenizestandard-librarynumber-literal

Determine the Kind (int, float) of Number a Python numeric literal represents?


In case anyone is interested, this is a followup to Regular expression to match a Python integer literal.

The tokenize module is useful for breaking apart a Python expression, but tokenize.NUMBER is not very expressive, as it represents all kinds of number literals, for example, 1, 1l (in Python 2), 0xf2, 1e-10, 1.1, 0b101, 0o17, and 1j are all considered NUMBER (and also all the previous with uppercase letters). Is there a function in the standard library that tells me what kind of the above I have? I particularly care about if I have an integer or a float (complex is also considered float), but further expressiveness would be OK too :). Basically, I don't want to try to catch all possible number literals myself, as I already managed to do it wrong once.


Solution

  • Possibly ast.literal_eval?

    type(ast.literal_eval(s))