python - Convert numeric value in module to its variable name -
in python 2.7, what's best / easiest / "pythonic" way convert integer value name of module-scoped constant value?
bonus points if there's way scope search variable names beginning magic prefix.
in other words:
evt_foo =0x0001 evt_bar =0x0002 evt_spam=0x0004 evt_eggs=0x0008 def getevtname( val ): """ should return 'evt_foo' when given number 0x1 """ pass
i know create dictionary reverse-lookup, i'd think there's better way in python. suggestions?
you can use globals()
function name if global object :
>>> evt_foo =0x0001 >>> evt_bar =0x0002 >>> evt_spam=0x0004 >>> evt_eggs=0x0008 >>> >>> def getevtname( val ): ... return next((i i,j in globals().iteritems() if j==val , i.startswith(something)),none) ... >>> getevtname(0x0001) 'evt_foo'
Comments
Post a Comment