Python 3 convert a numeric constant string to its number value

149 Views Asked by At

I am using an xml attribute to store regular expression flags, for example:

<regexSettings flags="re.IGNORECASE"/>

I want to convert the string "re.IGNORECASE" to its numeric equivalent, which is 2. Is there a convenient way to do this with Python 3, or should I just use a number for the attribute value? I would prefer to use the constant, since it is self-documenting. Thank you.

1

There are 1 best solutions below

0
On

Split on ".", use the first element as a lookup in a map, use getattr() to navigate the namespace structure, and verify that the final result is the appropriate type.

import re

modulemap = {
  're': re,
   ...
}

 ...