2

The Python docs (Python2 and Python3) state that identifiers must not start with a digit. From my understanding this is solely a compiler constraint (see also this question). So is there anything wrong about starting dynamically created identifiers with a digit? For example:

type('3Tuple', (object,), {})
setattr(some_object, '123', 123)

Edit

Admittedly the second example (using setattr) from above might be less relevant, as one could introspect the object via dir, discovers the attribute '123' but cannot retrieve it via some_object.123.

So I'll elaborate a bit more on the first example (which appears more relevant to me).
The user should be provided with fixed length tuples and because the tuple length is arbitrary and not known in advance a proxy function for retrieving such tuples is used (could also be a class implementing __call__ or __getattr__):

def NTuple(number_of_elements):
    # Add methods here.
    return type('{0}Tuple'.format(number_of_elements),
                (object,),
                {'number_of_elements': number_of_elements})

The typical use case involves referencing instances of those dynamically create classes, not the classes themselves, as for example:

limits = NTuple(3)(1, 2, 3)

But still the class name provides some useful information (as opposed to just using 'Tuple'):

>>> limits.__class__.__name__
'3Tuple'

Also those class names will not be relevant for any code at compile time, hence it doesn't introduce any obstacles for the programmer/user.

Community
  • 1
  • 1
a_guest
  • 34,165
  • 12
  • 64
  • 118
  • 3
    I don't suppose there's anything "wrong" with doing that, but given that the rest of the language is not really amenable to actually using objects/classes so defined, you're going to have to use back-door oddities (like the examples you gave for defining them) any time you actually want to do something with them. Seems generally not useful, unless you are trying to obfuscate something for more or less valid reasons... – twalberg Mar 13 '17 at 19:42
  • @twalberg I added an extended example which doesn't interfere with any language concepts that are relevant at compile time. Admittedly the `setattr` example has limited relevance (see my edit) but creating classes dynamically is not unusual (and I won't consider it a "back-door oddity"). Because those classes are not referenced explicitly (only their instances are referenced) there are also no troubles in finding an identifier that matches the class name somehow; the class (and its name) is only referenced through its instances via `obj.__class__.__name__`. – a_guest Mar 13 '17 at 23:27

0 Answers0