How to implement python decorators to reuse code from a function?

Asked

Viewed 37 times

0

Guys I’m trying to learn about decorators to help automate some repetitive routines.

Initially, I have several functions that read files and transform each line of them into a Pyhton list depending on what the file contents, for example: There are users file containing username and full name: jcalo-José Carlos mxferr-Max Ferreira ... In the end the result should be a list of tuples [("jcalo", "José Carlos), ("mxferr", "Max Ferreira")]. There is also a file with list of products products bread milk Expected result ["bread", "milk"]

The common procedure is to read the files and generate the list. Based on this, I have already made the following code, with read_list with common steps in reading each file:

def read_list(funcao):
def warapper_function(*args, **kwargs)
if intens_delimiter == '\n':
lista = open("file", 'r').readlines()
else:
lista = open('file', r)
lista = list(servers).split(servers_delimiter)
lista.close()
lista = list(map(lambda x : x.strip(), servers))
lista = [x for x in servers if x != ""]
return lista
return warapper_function

@read_list
def read_produtos_list():
file = "produtos.txt"

@read_list
def read_users_list():
file = "usuários.txt"

Does anyone know how I keep writing the code to use the decorators? My goal is to take advantage of the code to read the file and generate the list and modify the functions to get the correct return according to the file type to be read.

  • 3

    This problem does not seem to be solved with decorator; you could simply take the file name as a function parameter and reuse the code. The decorators serve as a kind of Proxy in calling the decorated function in order to change its behavior. It does not seem to be your case.

  • Got it, I thought I could add an if to depend on the parameters passed in the function they assume different behavior. Thanks!

  • I strongly recommend that you read this article (I wrote today, by coincidence), where I explain everything you need to know about Python decorators

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.