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