- Content
You can do this easily enough with a sequence of if... elif... elif... else. For literal values, or constants within a namespace, you can also use a match ... case statement.
For cases where you need to choose from a very large number of possibilities, you can create a dictionary mapping case values to functions to call. For example:
functions = {'a': function_1,
'b': function_2,
'c': self.method_1}
def switch(value):
try:
return functions[value]
except KeyError:
return default_function
# Example:
func = switch("a")
func()
Or you can use getattr(type, name, default)
built-in:
class Methods:
def value_1(self):
...
def value_2(self):
...
def default_function(self):
...
def case(self, value):
return getattr(self, "value_"+str(value), self.default_function)
# Example:
switch = Methods()
func = switch.case(1)
func()
In the 1970s people realized that unrestricted goto could lead to messy “spaghetti” code that was hard to understand and revise. In a high-level language, it is also unneeded as long as there are ways to branch (in Python, with if statements and or, and, and if-else expressions) and loop (with while and for statements, possibly containing continue and break).
One can also use exceptions to provide a “structured goto” that works even across function calls. Many feel that exceptions can conveniently emulate all reasonable uses of the “go” or “goto” constructs of C, Fortran, and other languages. For example:
class label(Exception): pass # declare a label
try:
...
if condition: raise label() # goto label
...
except label: # where to goto
pass
...
Sometimes you want program does a function for a time and stop after that. Other Python implements like Stackless-Python have it, but in CPython we dont have it, so we try to implement it:
import time
class Timeout:
def __init__(self, seconds):
self.seconds = seconds
self.die_after = time.time() + seconds
def __enter__(self):
return self
def __exit__(self, *_):
pass
@property
def timed_out(self):
return time.time() >= self.die_after
with Timeout(1) as t:
while not t.timed_out:
print("...")
time.sleep(0.2)
In linux you can use
signal.alarm
.
See other implements in stackoverflow.
Sometimes you want loop waits for other thread, LoopQueue
helps you:
import _thread
from queue import Queue
class LoopQueue(Queue):
def __iter__(self):
return self
def __next__(self):
return self.get()
q = LoopQueue()
def thread_1():
for i in range(10):
q.put(i)
q.put(StopIteration) # notify for exit loop
_thread.start_new_thread(thread_1, ())
for item in q: # Loop will wait for queue
if item is StopIteration: # Capture exit notify
break
print("Item:", item)
- A sequence object that points to the memory of another object.
- Each element can reference a single or multiple consecutive bytes, depending on format.
- Order and number of elements can be changed with slicing.
- Casting only works between char and other types and uses system's sizes.
- Byte order is always determined by the system.
Immutable if bytes, otherwise mutable.
Call By Reference in python with array.array
and memoryview
:
import array
def change_array(m: memoryview):
m[0] = 4
m[1] = 3
arr = array.array("i", [1, 2, 3, 4, 5])
print(arr)
# array('i', [1, 2, 3, 4, 5])
change_array(memoryview(arr))
print(arr)
# array('i', [4, 3, 3, 4, 5])