[Zope] Why is it so hard to do simple things?

Paul Winkler pw_lists@slinkp.com
Wed, 8 May 2002 07:26:20 -0700


On Tue, May 07, 2002 at 11:44:52PM -0400, Chris McDonough wrote:
> button_value = context.REQUEST.get('perm_or_temp', 'P')

quick note to John A:
the above works with dictionaries and dictionary-like objects.
somedict.get('keyname', 'default result')
... will return the value indexed by 'keyname', or the default
result you provide. The default is None by default.

With other kinds of objects you can use the built-in getattr function
in the same way:

getattr(myobject, 'attrname', 'default result')

When learning python, I *highly* recommend having a window open
with an interactive python session going. If you're not sure
what something does, try it out - "ask the interpreter", as
we say. It's often faster than looking something up in
a book or manual. And you can find out all sorts of things
using the dir() builtin function, and looking at the __doc__
attributes of classes, functions, and methods.

Example:

$ python
Python 1.5.2 (#1, Aug 25 2000, 09:33:37)  [GCC 2.96 20000731 (experimental)] on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> dir()
['__builtins__', '__doc__', '__name__']
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'FloatingPointError', 'IOError', 'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplementedError', 'OSError', 'OverflowError', 'RuntimeError', 'StandardError', 'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply', 'buffer', 'callable', 'chr', 'cmp', 'coerce', 'compile', 'complex', 'delattr', 'dir', 'divmod', 'eval', 'execfile', 'exit', 'filter', 'float', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'len', 'list', 'locals', 'long', 'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round', 'setattr', 'slice', 'str', 'tuple', 'type', 'vars', 'xrange']
>>> print getattr.__doc__
getattr(object, name[, default]) -> value

Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
>>> print round.__doc__
round(number[, ndigits]) -> floating point number

Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number.  Precision may be negative.
>>>

--
Paul Winkler

"Welcome to Muppet Labs, where the future is made - today!"