Hi all, Question: How to get the value of a dict ?
There is a lot of answer.
a) use the __getitem__ method
[code]
>>> values = {'key1' : 'value1', 'key2' : 'value2'}
>>> values['key1']
'value1'
>>> values['key2']
'value2'
>>> values['key3']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'key3'
[/code]
With the __getitem__ method aka [], if the key doesn't exist in the dict,
an exception will be raised by the interpreter, and we have to handle this
exception.
Description from the official documentation of Python [1]
"""
Called to implement evaluation of self[key]. For sequence types, the accepted
keys should be
integers and slice objects. Note that the special interpretation of negative
indexes (if the class
wishes to emulate a sequence type) is up to the __getitem__() method. If key is
of an inappropriate type,
TypeError may be raised; if of a value outside the set of indexes for the
sequence
(after any special interpretation of negative values), IndexError should be
raised.
For mapping types, if key is missing (not in the container), KeyError should be
raised.
"""
b) use the get method
>>> values = {'key1' : 'value1', 'key2' : 'value2'}
>>> values.get('key1')
'value1'
>>> values.get('key2')
'value2'
>>> values.get('key3')
>>>
With the get method, there is no raised exception if the key doesn't exist
in the dict but can return a default value if default is given
with the second argument of the get method.
Description from the official documentation of Python [2]
"""
Return the value for key if key is in the dictionary, else default. If default
is not given, it defaults to None, so that this method never raises a KeyError.
"""
[1]
http://docs.python.org/reference/datamodel.html?highlight=getitem#object.__getitem__
[2] http://docs.python.org/library/stdtypes.html?highlight=dict#dict.get
3) DON'T USE eval to get the value of a key in a dict.
Here is a refactored code in purchase/purchase.py file (fixed in 5.0 and 6.0).
I don't understand why we try to use an eval instead of a simple .get or []
call.
=== modified file 'purchase/purchase.py'
--- purchase/purchase.py 2010-08-30 07:18:24 +0000
+++ purchase/purchase.py 2010-09-03 09:35:33 +0000
@@ -145,6 +145,17 @@
res[purchase.id] = False
return res
+ STATE_SELECTION = [
+ ('draft', 'Request for Quotation'),
+ ('wait', 'Waiting'),
+ ('confirmed', 'Waiting Supplier Ack'),
+ ('approved', 'Approved'),
+ ('except_picking', 'Shipping Exception'),
+ ('except_invoice', 'Invoice Exception'),
+ ('done', 'Done'),
+ ('cancel', 'Cancelled')
+ ]
+
_columns = {
'name': fields.char('Order Reference', size=64, required=True,
select=True, help="unique number of the purchase order,computed automatically
when the purchase order is created"),
'origin': fields.char('Source Document', size=64,
@@ -164,7 +175,7 @@
'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse',
states={'confirmed':[('readonly',True)],
'approved':[('readonly',True)],'done':[('readonly',True)]}),
'location_id': fields.many2one('stock.location', 'Destination',
required=True, domain=[('usage','<>','view')]),
'pricelist_id':fields.many2one('product.pricelist', 'Pricelist',
required=True, states={'confirmed':[('readonly',True)],
'approved':[('readonly',True)],'done':[('readonly',True)]}, help="The
pricelist sets the currency used for this purchase order. It also computes the
supplier price for the selected products/quantities."),
- 'state': fields.selection([('draft', 'Request for Quotation'),
('wait', 'Waiting'), ('confirmed', 'Waiting Supplier Ack'), ('approved',
'Approved'),('except_picking', 'Shipping Exception'),
('except_invoice', 'Invoice Exception'), ('done', 'Done'), ('cancel',
'Cancelled')], 'State', readonly=True, help="The state of the purchase order or
the quotation request. A quotation is a purchase
order in a 'Draft' state. Then the order has to be confirmed by the user, the
state switch to 'Confirmed'. Then the supplier must confirm the order to change
the state to 'Approved'. When the purchase
order is paid and received, the state becomes 'Done'. If a cancel action occurs
in the invoice or in the reception of goods, the state becomes in exception.",
select=True),
+ 'state': fields.selection(STATE_SELECTION, 'State', readonly=True,
help="The state of the purchase order or the quotation request. A quotation is
a purchase order in a 'Draft' state. Then the
order has to be confirmed by the user, the state switch to 'Confirmed'. Then
the supplier must confirm the order to change the state to 'Approved'. When the
purchase order is paid and received, the
state becomes 'Done'. If a cancel action occurs in the invoice or in the
reception of goods, the state becomes in exception.", select=True),
'order_line': fields.one2many('purchase.order.line', 'order_id',
'Order Lines',
states={'approved':[('readonly',True)],'done':[('readonly',True)]}),
'validator' : fields.many2one('res.users', 'Validated by',
readonly=True),
'notes': fields.text('Notes'),
@@ -220,8 +231,7 @@
if s['state'] in ['draft','cancel']:
unlink_ids.append(s['id'])
else:
- state_dict =
{'wait':'Waiting','confirmed':'Confirmed','approved':'Approved','except_picking':
'Shipping Exception','except_invoice': 'Invoice Exception','done': 'Done'}
- raise osv.except_osv(_('Invalid action !'), _('Cannot delete
Purchase Order(s) which are in %s State!') %_(eval(s['state'],state_dict)))
+ raise osv.except_osv(_('Invalid action !'), _('Cannot delete
Purchase Order(s) which are in %s State!') %
_(dict(purchase_order.STATE_SELECTION).get(s['state'])))
# TODO: temporary fix in 5.0, to remove in 5.2 when subflows support
# automatically sending subflow.delete upon deletion
Regards,
Stéphane
--
Stephane Wirtel - "As OpenERP is OpenSource, please feel free to contribute."
Quality/Release Manager
Technical Project Manager
OpenERP S.A.
Chaussee de Namur, 40
B-1367 Grand-Rosière
Tel: +32.81.81.37.00
Web: http://www.openerp.com
Planet: http://www.openerp.com/planet/
Blog: http://stephane-wirtel-at-tiny.blogspot.com
<<attachment: stw.vcf>>
_______________________________________________ Mailing list: https://launchpad.net/~openerp-dev Post to : [email protected] Unsubscribe : https://launchpad.net/~openerp-dev More help : https://help.launchpad.net/ListHelp

