Well, I will contribute with the little experience I have, because I have seen in very few cases this type of design, due to the little need of it (as already mentioned by Jefferson).
At first, Python basically already has a built-in command function, which is as follows (Example extracted from stack overflow - Here ):
def greet(who):
print "Hello %s" % who
greet_command = lambda: greet("World")
greet_command()
However, I have seen applications using the "Command" Pattern on occasions of:
- Commands need to perform more than just execute
a basic/invoked function;
- Greater readability in some large cases.
It is obvious, however, that the cases of commands are often cases of a single method and of simple/direct execution, leaving any approach different from the first unnecessary code block.
Stackoverflow’s own post in English performs a good example, as in cases where you need to perform actions and eventually reverse them:
Class ComandoGenerico():
def __init__(self, destino, origem):
self.origem = origem
self.destino = destino
#primeira alteração
os.rename(self.origem, self.destino)
#função para desfazer o comando inicial
def desfazer(self):
os.rename(self.destino, self.origem) #reverte para a condição inicial do comando
pilha = []
pilha.append(ComandoGenerico("oi.csv", "tudo_bem.csv")) #Arquivo renomeado para "tudo_bem.csv"
pilha.append((ComandoGenerico("tudo_bem.csv", "okay.csv")) #Arquivo renomeado para "okay.csv"
pilha.pop().desfazer() #Comando desfeito - Arquivo renomeado para "tudo_bem.csv"
pilha.pop().desfazer() #Comando desfeito - Arquivo renomeado para "oi.csv"
If language itself already does, why reinvent? If I’m not mistaken
iterator
is a design pattern that there is not much sense to use in Python given the existence of generators. Do not forget that design pattern is an institutionalized and repeatable standardized gambiarra. And like all gambiarra, it has a specific purpose, usually to offer something that is not native to language– Jefferson Quesado