True/False

Erik Max Francis max at alcyone.com
Tue Apr 22 18:50:22 EDT 2003


Roy Smith wrote:

> I'm not 100% sure testing for the presense of 'True' in dir(sys) is
> the
> right test, but it's better than testing for an absolute version
> number.

I don't think it's the right test at all, since True (and False) aren't
in sys at all, they're in the builtins:

Python 2.3a2 (#1, Feb 19 2003, 20:06:49) 
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.True
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'module' object has no attribute 'True'
>>> __builtins__.True
True

Note that your general approach (correcting __builtins__ for sys) is the
same as those others that have been suggested, it's just that you're
doing a manual check in a module rather than just trying to use the name
and see if you get a NameError.

So there's (at least) three approaches of trying to get safe True/False
compatibility:

1.  Unconditionally defined True/False; this might generate warnings
("Hey, you're rebinding a constant!") at some unspecified point in the
future.

2.  Do an explicit test for the version number.

3.  Check for the existence of the names True and/or False (either by
looking in a module or testing by name and catching an error if it's not
there).

Of these, I think the third is the most elegant and least likely to muck
up.

> A better test might be looking for 'BoolType' in dir(types), ...

It's actually called BooleanType (which I only just noticed now; I've
never had the occasion to use it).  I'm not sure why.

[same session, still 2.3a2]
>>> import types
>>> types.BoolType
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'module' object has no attribute 'BoolType'
>>> dir(types)
['BooleanType', 'BufferType', 'BuiltinFunctionType',
'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType',
'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType',
'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType',
'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType',
'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType',
'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType',
'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType',
'XRangeType', '__builtins__', '__doc__', '__file__', '__name__']

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ There are defeats more triumphant than victories.
\__/ Montaigne
    Discord / http://www.alcyone.com/pyos/discord/
 Convert dates from Gregorian to Discordian.




More information about the Python-list mailing list