Level 1 : What is the purpose of the __enter__ and __exit__ methods in a Python class?

Author: IndraD | Tags: context-manager | 1859+ Python FAQs | Share
iterable | lambdas | iterator | version-check | implementation | identifier | expand-tab | int | assignment-operators | complex-number | encapsulation | indexing:-loc-vs-iloc | parameter | data-structures | mathematical-function | logical-operators | factorial-function | min-function | bitwise-operator | loop | else | default-mutable-argument | binary-operation | list-mutation | multithreading | multiprocessing | list-method | multiple-inheritance | memory | immutability | datatype | list-methods-and-slicing | string-method | single-inheritance | center | match | lambda-functions | conversion | statement | touples | conditional-statements | regex | id-function | class-and-inheritance | difference-between-threads-and-processes | boolean-and-non-boolean | module | init | built-in-function | split | string | installation | multiple-except-blocks | software-design | using-the-threading-module | recursion | memory-management | dictionary | mathematics | list-comprehension | heap-memory | data-structure | expression | oops | assert | anchors-(^,-$) | max-min | interpreter | docstring | comparison | decorator | multiple-inheritance | sorted | thread-safe-data-structures-(queue.queue) | invalid-list | loop-control-statements | list,-set,-and-dictionary-comprehensions | join | context-manager | raise | set | else-statement | thread-synchronization | lambda | typeerror | using-join()-and-is_alive()-methods | reading-and-writing-large-files-efficiently | virtual-environment | class-and-object | operators | type_conversion | generators | debugging | goto-function | sets | library | data-type | print | syntax-error | matrix | rollback | error-handling | introduction-to-python | inherit | reading-and-writing-files | escape-operator | staticmethod | call | generator | control-flow | data-types | precedence-and-associativity | operator-and | file | string-iteration | sum() | python-syntax-and-structure | operator-overloading | control-statement | zfill-function | exception | append | mysql | reading:-read(),-readline(),-readlines() | key-value-pairs | version | using-assertions-(assertequal,-assertraises) | recurssion | tuple | def | tuples | mutable | descriptors | formal-and-actual-parameter | functions | datetime.date,-datetime.time,-datetime.datetime | range | matrix-list-comprehension | math-copysign | aggregating-data-with-functools.reduce() | compute | magic-method | data-type | head-and-tail | time-series-with-pandas | shallow-copy | sys | filter | copy | managing-directories-with-os-and-shutil | using-else-and-finally | list-comprehension | functional-programming | python-django | conditional-statement | binary | string-slicing | boolean-masking | membership-operators-(in,-not-in) | constructor | introduction-to-threads | opening-files-(open()) | arithmetic-expression | name-mangling | namedtuple | control-flow | inheritance | class-and-instance-variable | syntaxerror | yield | method-overloading | filtering-and-indexing | namespace | async | nested-loop | type-conversion-and-casting | file-handling | creating-and-starting-threads | string-formatting | parsing-with-strptime | access-modifier | python-history | import-method | collection | objects | tuple-unpacking | working-with-dates-and-times | complex | literal-characters-and-special-characters | comprehension | static-method | directory-operations | thread | built-in-modules | benefit | loop-control | global | data_structure | python_version | array | built-in | higher-order-function | pseudocode | data-type-conversions | error-handling | dicts | threading | datetime | function-and-scope | formatting-with-strftime | handling-missing-values-(fillna,-dropna) | dictionary-methods | operations | stack | logical-operator | virtual-environment | filter-function | file-handling | exception-handling | while-loop | string-concatenation | indexing | random-function | lambda-function | operator | feature | unit-testing | working-with-file-paths | list-operation | swapping | function | python | while-else-loop | round | operand | odd-number | enumerate() | pandas | numpy | matplotlib | data-structures-in-python | strings | default-arguments | using-os-and-pathlib-modules | operator-or | condition | bitwise | conditional-statement | pass | input-function | dictionary-comprehensions | file_handling | bitwise-operator | walking-through-directories-using-os.walk() | using-map()-for-transformations | indentation | polymorphism | why-use-multiprocessing-over-threading?-(gil) | __init_subclass__ | methods | pep | boolean | exception-handling | package-management | list-vs-tuple | string-formatting | basic | using-yield-in-functions | python-repl | list-indexing | global-variable | input-function | keyword | application | joining-and-merging-dataframes | __future__ | map-function | slicing | list-join | type-conversion | for | precedence | defining-functions | syntax-error | writing:-write(),-writelines() | immutable-data-type | arithmetic-operation | working-with-temporary-files-using-tempfile | sys-module | comment | logical-operator | oop | loops | string-manipulation | exponentiation | overriding-methods | return-statement | dataframe-and-series-objects | decimal | collections | math | sorting | method | python-module | lists | identity-operator | asyncio | error | print-statement | counter-function | classes | logical-operation | destructor | frozenset | fabs-function | introduction-to-multiprocessing | asyncio-module | sorting-and-ranking | pickling--unpickling | creating-custom-modules | min-max-function | iterators | data-structure | list-slicing | booleans | object-attribute | syntax | identity-operators-(is,-is-not) | slice | floating-point-precision | while-loops | mapping-function | numeric | random | integer | format | function-argument | while-and-for-loop | zip-function | class | update | regular-expression | counter | list-comprehensions | input | global-variable | intering | functional-programming | dictionaries | identity-operator | global-keyword | generators-in-python | postfix | floats | python-operators | overflow | string-methods | encoding | list | raise-statement | gil | integers | quantifiers-(*,-+,-?,-{}) | deep-copy | with-statement | class-decorators | type-conversion | arbitrary-arguments-(*args,-**kwargs) | turtle | design-principle | scientific-notation | built-in-function | tuple-methods | assignment-operator | choice | advanced-file-operations | variable | command-line-parsing | sum-function | attribute | __all__-attribute | test-discovery | set-operation | round-function | using-lists-as-stacks | string-slicing | regular-expressions | zip | string-method | working-with-binary-files-(rb,-wb) ...