+ 1

How to create decorators?

Please go through the code: https://code.sololearn.com/coFLokNQt0Vj/?ref=app everything is in the comments.

31st Dec 2021, 9:24 AM
Harsha S
Harsha S - avatar
14 Respuestas
0
Hmm.. I found 2 ways to make your code work, also it should be "os.system('clear')" in linux(Sololearn) not 'cls'; - 1st method: When defining cls function add os argument then in decorator inner func call cls(os) after importing it - 2nd method: (a bit hacky) After importing os add this line: globals()["os"] = os * I think the problem that it imports os and stores it locally just in the decorator
31st Dec 2021, 11:29 AM
Sousou
Sousou - avatar
+ 2
Sousou it is "cls" as I wrote it in my windows
31st Dec 2021, 11:31 AM
Harsha S
Harsha S - avatar
+ 2
Sousou thank you! it works and not works (because it's linux) can you explain the line? globals() ["os"] = os
31st Dec 2021, 11:33 AM
Harsha S
Harsha S - avatar
+ 1
Oma Falk abhinav Louis this question seems lonely without an answer
31st Dec 2021, 11:08 AM
Harsha S
Harsha S - avatar
+ 1
Harsha S it's fine then.
31st Dec 2021, 11:32 AM
Sousou
Sousou - avatar
+ 1
Harsha S np :) globals is a function that returns global variables in dict, but it's a bit dangerous to use it, you can use it to access global variables, edit them, add, remove, etc.. You can try: print(globals()) it's like: vars and locals I used it to make os module as a global variable named "os"
31st Dec 2021, 11:39 AM
Sousou
Sousou - avatar
+ 1
Sousou why is it dangerous?
31st Dec 2021, 11:42 AM
Harsha S
Harsha S - avatar
+ 1
Harsha S 🤔 Not sure.. maybe, because you can access and change global variables everywhere in your code, but I think it's not dangerous while it's a module.
31st Dec 2021, 11:51 AM
Sousou
Sousou - avatar
+ 1
I didn't very well understand your code but a decorator is required to return a function. So change 'return inner()' to 'return inner'
31st Dec 2021, 12:07 PM
abhinav
abhinav - avatar
+ 1
abhinav i had changed but forgot to save
31st Dec 2021, 12:13 PM
Harsha S
Harsha S - avatar
+ 1
It is hacky, using decorator to do the import. And as suggested by Sousou you have to declare os as a global in your decorator, so not very elegant. And 'cls' is specific to Windows, so I changed it to 'clear' to make it work when I tried it in Pydroid on my Android phone. Also Sololearn could not cleanly do the clear console command and produced some strange characters instead. But you hack does work. i called the decorated cls() first, then cls2() with the normal import os below to compare the result. Modifications are commented with capital letters. Here is your code with modifications. You should change 'clear' back to 'cls' if you try it on Windows. https://code.sololearn.com/cfphbxKMZvOQ/?ref=app
1st Jan 2022, 2:22 PM
Bob_Li
Bob_Li - avatar
0
?!
31st Dec 2021, 6:12 PM
Reza Mardani
Reza Mardani - avatar
- 1
Bob_Li thank you
1st Jan 2022, 3:54 PM
Harsha S
Harsha S - avatar
- 2
idk
31st Dec 2021, 10:32 PM
game
game - avatar