Python Forum
Context Manager (with) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Context Manager (with) (/thread-11707.html)



Context Manager (with) - wyattbiker - Jul-22-2018

So a Context Manager with statement class must have __enter__() and __exit__() .

For example file objects with will automatically close the file.

with open("/Users/user/tmp/workData.txt", "w") as work_data:
    for value in h:
        str_value = str(value)
        work_data.write(str_value)
        work_data.write("\n")
#1) How does one know if a class object supports the Context Manager. What should I be looking for in the docs?

#2) How do you overwrite it (as in file objects for example?)

Thanks


RE: Context Manager (with) - Larz60+ - Jul-22-2018

you might want to look at the examples here:
to determine if something uses context manager, you can use:
assuming method in class:
def uses_context_manager(self, mymethod)
    istrue = False
    istrue = hasattr(mymethod, '__exit__'):
    return istrue



RE: Context Manager (with) - buran - Jul-23-2018

check also contextlib - https://docs.python.org/3/library/contextlib.html
with @conextlib.contetxmanager decorator you can define a factory function for with statement context managers, without needing to create a class or separate __enter__() and __exit__() methods.


RE: Context Manager (with) - snippsat - Jul-23-2018

(Jul-22-2018, 08:08 PM)wyattbiker Wrote: #1) How does one know if a class object supports the Context Manager. What should I be looking for in the docs?
I supporter pretty much every everywhere as it's just syntax sugar,
and with open() for files was added 12-year ago in Python 2.5.
Quote:#2) How do you overwrite it (as in file objects for example?)
Not sure if i know you mean,but not much not difference,it's the io that is in bottom which control all.
# The new way(added 12-year ago)
with open('foo.txt', 'w', encoding='utf-8') as f:
    pass

# Old way
other_f = open('bar.txt', 'w', encoding='utf-8')
Test it:
>>> f
<_io.TextIOWrapper name='foo.txt' mode='w' encoding='utf-8'>
>>> other_f
<_io.TextIOWrapper name='bar.txt' mode='w' encoding='utf-8'>

>>> type(f)
<class '_io.TextIOWrapper'>
>>> type(other_f)
<class '_io.TextIOWrapper'>

>>> f = 'overwrite'
>>> other_f = 'me to'
>>> f
'overwrite'
>>> other_f
'me to'