How to create decorators?
Please go through the code: https://code.sololearn.com/coFLokNQt0Vj/?ref=app everything is in the comments.
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
Sousou it is "cls" as I wrote it in my windows
Sousou thank you! it works and not works (because it's linux) can you explain the line? globals() ["os"] = os
Harsha S it's fine then.
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"
Sousou why is it dangerous?
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.
I didn't very well understand your code but a decorator is required to return a function. So change 'return inner()' to 'return inner'
ａｂｈｉｎａｖ i had changed but forgot to save
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
Bob_Li thank you