Hi

Everything in Python is treated as an object, so

i=5
i.imag

makes sense, i.e. the variable i has some associated methods. But why doesn't the following example work?

5.imag #error

One would think that it should work, since the integer "5" is an object just like the list "[1,2]":

[1,2].pop() #no error

Best,
Niles.

Dani AI

Generated

Short answer: this is a lexer / parser quirk, not a statement that numbers lack attributes. is right that numbers are objects; is also right that wrapping the literal or converting it avoids the error. The underlying cause is that the Python tokenizer will greedily include a dot in a numeric literal when it can, so the interpreter sometimes never sees a separate attribute-access dot token.

Concretely, tokenization happens before attribute lookup. If the dot immediately follows digits and can form part of a valid floating literal, the dot becomes part of that numeric token. The parser then sees a number token followed directly by a name token (no DOT token between them) and rejects the input as invalid syntax. Putting the literal inside parentheses or otherwise ensuring the dot is a separate token prevents the lexer from consuming it, so attribute access parses normally. Adding whitespace between the number and the dot also forces a separate DOT token, but that style is awkward.

Practical guidance: prefer clear code (use parentheses, explicit conversions, or avoid attribute access on bare numeric literals in-line). Remember this is a language-grammar rule rather than an implementation bug, so it is consistent across Python implementations that follow the language reference. For details see the Python language reference on lexical analysis and on attribute references:

Python reference: Lexical analysis
Python reference: Attribute references

Recommended Answers

All 2 Replies

Interesting syntax point, however the:

(5).imag

does work as does

int(5).imag

I thought it is because the constant could be floating point number, and it makes sense that:

5.4.imag

is not valid syntax, but actually it is accepted by interpreter.

Ah, I see. OK, so it makes sense afterall. Thanks!

Best,
Niles.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.