Python Forum
turning my function into a context manager - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: turning my function into a context manager (/thread-22467.html)



turning my function into a context manager - Skaperen - Nov-14-2019

i have a function named "cd()". called with a directory name, it changes the process current working directory to that directory. called with no argument or None, it changes the process current working directory to the user home directory. i'm thinking of adding __enter__() and __exit__() so it can be a context manager on the with statement. on entry, it will save the current working directory before changing to the specified directory. on exit, it will restore the previous directory. i'm sure this has been done before, but i was re-reading PEP 343 again, tonight (a little slower this time).

i'm going through my other functions ("Skaperen's Function Collection") to see what else might be doable (and maybe useful, maybe not).


RE: turning my function into a context manager - Gribouillis - Nov-14-2019

Skapern Wrote:i'm sure this has been done before
It has. Use contextlib.contextmanager and a try..finally statement containing a yield.


RE: turning my function into a context manager - Skaperen - Nov-14-2019

unlike C, in Python, being so late to the party, i am going to be doing many things that have already been done, before. it has always been my nature to develop tools and supplements for developments, and applications for system and network administration. one of my past project was a program on TOPS-20 to submit batch jobs to the IBM S370 model 168 mainframe OS/VS1 system, including ASCII/EBCDIC translation (and back for the job printouts). i also did my own backups of TOPS-20 files to tapes on the mainframe (w/o translation since much of it was in binary). then i wrote a program in ASM/370 to list those tape content (with the appropriate translations). it was fun dealing with 36-bit data on a 32-bit machine. Python could have been helpful if it were around in the early 1980s. at least the TOPS-20 side had C and PCL.