|
Original |
Translation |
|
67
|
if mydict.has_key(key): value = mydict[key] else: mydict[key] = getvalue(key) value = mydict[key]
|
|
|
68
|
For this specific case, you could also use ``value = dict.setdefault(key, getvalue(key))``, but only if the ``getvalue()`` call is cheap enough because it is evaluated in all cases.
|
|
|
69
|
Why isn't there a switch or case statement in Python?
|
|
|
70
|
You can do this easily enough with a sequence of ``if... elif... elif... else``. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests. See :pep:`275` for complete details and the current status.
|
|
|
71
|
|
72
|
def function_1(...): ... functions = {'a': function_1, 'b': function_2, 'c': self.method_1, ...} func = functions[value] func()
|
|
|
73
|
For calling methods on objects, you can simplify yet further by using the :func:`getattr` built-in to retrieve methods with a particular name::
|
|
|
74
|
def visit_a(self, ...): ... ... def dispatch(self, value): method_name = 'visit_' + str(value) method = getattr(self, method_name) method()
|
|
|
75
|
It's suggested that you use a prefix for the method names, such as ``visit_`` in this example. Without such a prefix, if values are coming from an untrusted source, an attacker would be able to call any method on your object.
|
|
|
76
|
Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?
|
|