Am 13.05.2022 um 23:23 schrieb Paul Bryan:
On Sat, 2022-05-14 at 00:47 +0800, bryangan41 wrote:

May I know (1) why can the name start with a number?

The name of an attribute must be an identifier. An identifier cannot
begin with a decimal number.

I'm not sure about the first statement. Feeding

[print("locals:", locals()) or c for c in "ab"]

to the REPL, the result is

locals: {'.0': <str_iterator object at 0x0000000002D2B160>, 'c': 'a'}
locals: {'.0': <str_iterator object at 0x0000000002D2B160>, 'c': 'b'}
['a', 'b']

i.e. there is a variable of name .0 in the local namespace within the list comprehension, and .0 is definitely not an identifier.

I came across this while investigating another problem with list comprehensions, and I think the original post was about list comprehensions.

There also can be non-identifier names in the global namespace and as attributes, e.g. using the REPL again:

globals()["42"] = "The Answer"
globals()

outputs (see last entry)

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '42': 'The Answer'}

and

class Cls:
    def __init__(self, lst):
        for i, e in enumerate(lst):
            self.__dict__[str(i)] = e

obj = Cls([31, 42, 53])
getattr(obj, "1")

works and outputs

42

(2) where in the doc is it?!

https://docs.python.org/3/reference/lexical_analysis.html#identifiers

That refers to identifiers, i.e. names that are recognised as such by the lexer, i.e. that can be written directly in Python source code.

As shown above, names that are not identifiers can be used in several namespaces and as attributes. It's just a bit harder to use non-identifier names than identifiers.
Whether it's a good idea to use them at all is a different question.

I think the OP wondered about the .0 in the local namespace within list comprehensions. Unfortunately I cannot say much about that.

Paul

Ralf M.
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to