Comparing types

Rick Johnson rantingrickjohnson at gmail.com
Sun Feb 17 23:13:07 CET 2013


On Sunday, February 17, 2013 12:34:57 AM UTC-6, Jason Friedman wrote:
> [...]
> py> my_pattern = re.compile(s)
> py> type(my_pattern)
> <class '_sre.SRE_Pattern'>
> py> isinstance(my_pattern, _sre.SRE_Pattern)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name '_sre' is not defined

Both Steven and Terry provided answers to you question however you not still understand why the line "isinstance(my_pattern, _sre.SRE_Pattern)" threw a NameError. 

Maybe you expected '_sre.SRE_Pattern' to be imported as a consequence of importing the "re" module? Hmm, not so. And you can even check these things yourself by using the global function: "dir".

py> dir()
['__builtins__', '__doc__', '__name__', '__package__']
py> import re
py> dir()
['__builtins__', '__doc__', '__name__', '__package__', 're']

As you can see only "re" is available after import, and Python does not look /inside/ namespaces (except the __builtin__ namespace) to resolve names without a dotted path. But even /if/ Python /did/ look inside the "re" namespace, it would not find the a reference to the module named "_sre" anyway! Observe:
    
py> dir(re)
['DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', '_alphanum', '_cache', '_cache_repl', '_compile', '_compile_repl', '_expand', '_pattern_type', '_pickle', '_subx', 'compile', 'copy_reg', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'sys', 'template']
py> '_sre' in dir(re)
False

And if you look in the modules "_sre.py", "sre_parse.py", and "sre_constants.py you cannot find the symbol "SRE_Pattern" anywhere -- almost seems like magic huh? Heck the only "_sre.py" file i could find was waaaay down here:

 ...\Lib\site-packages\isapi\test\build\bdist.win32\winexe\temp\_sre.py

What were they doing, trying to bury it deeper than Jimmy Hoffa? Maybe one of my fellow Pythonistas would like to explain that mess?



More information about the Python-list mailing list