[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Like c enumeration in python3 [ERRATA]

On 23/03/20 3:32 PM, Paulo da Silva wrote:
> ?s 02:18 de 23/03/20, Paulo da Silva escreveu:
>> Hi!


>> Suppose a class C.
>> I want something like this:
>> class C:
>> 	KA=0
>> 	KB=1
> 	KC=2
>> 	...
>> 	Kn=n
>> 	def __init__ ...
>> 		...
>> These constants come from an enum in a .h (header of C file).
>> They are many and may change from time to time.
>> Is there a way to somehow define them from inside __init__ giving for
>> example a list of names as strings?
>> There is an additional problem: C is not recognized inside __init__!

Please read the PSL docs carefully, because Python's enums seem to 
differ from those in other languages - sometimes in significant ways, 
and sometimes in a subtle manner!

I have been asking similar questions recently - particularly wanting to 
(also) use the "strings", because of the effort of upgrading many 
modules of code at the same time (the manual, or was it the PEP(?) 
refers to the need to upgrade the PSL to use enums, and to the effort 
that might cost - I suggest there has been little/v.slow take-up, but 
then keeping the PSL updated is a subject of a great many conversations, 

Python's enums cannot be changed. Once set, C.KA cannot be changed to 1 
(for example). We may not add element Km (where m>n) at some later 
occasion after class definition-time (in fact the __new__() constructor 
is 're-wired' in order to prohibit its use post-definition). It is not 
permitted to sub-class an existing enum class, eg C(), perhaps to 
enlarge it with more members, if the 'super class' contains "members".

There is usually no need for an __init__. Plus, I've had a distinct lack 
of satisfaction playing with that - but YMMV!

Sub-classing, and even attempting to use the meta-class seems to be a 
major challenge (see StackOverflow).

It is possible to list the elements using the built-in iterator:

	for c in C: print( c )

or iterator-conversion:

	list( C )

and/or accessing the class's 'data-dict' directly:

	for name, value in C.__members__.items():
Regards =dn