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