New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adding the document-new entry Context Managers and files #4541
base: main
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hey @Maet22, thanks for contributing to Codecademy!
I've listed all the modifications that you need to make in your entry below:
--- | ||
Title: 'Context Managers and Files' | ||
Description: 'This document introduces context managers and in particular how they can be used to work with files. It details the two approaches, class-based and decorator-based, thanks to which the user can customize this experience to fit the needs of a given use case.' | ||
Subjects: | ||
- 'Computer Science' | ||
- 'Data Science' | ||
Tags: | ||
- 'Best Practices' | ||
- 'Classes' | ||
- 'Decorators' | ||
- 'Files' | ||
CatalogContent: | ||
- 'learn-python-3' | ||
- 'paths/computer-science' | ||
--- |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
--- | |
Title: 'Context Managers and Files' | |
Description: 'This document introduces context managers and in particular how they can be used to work with files. It details the two approaches, class-based and decorator-based, thanks to which the user can customize this experience to fit the needs of a given use case.' | |
Subjects: | |
- 'Computer Science' | |
- 'Data Science' | |
Tags: | |
- 'Best Practices' | |
- 'Classes' | |
- 'Decorators' | |
- 'Files' | |
CatalogContent: | |
- 'learn-python-3' | |
- 'paths/computer-science' | |
--- | |
--- | |
Title: 'Context Managers' | |
Description: 'Context managers allow users to perform operations within a certain overarching context.' | |
Subjects: | |
- 'Computer Science' | |
- 'Data Science' | |
Tags: | |
- 'Best Practices' | |
- 'Classes' | |
- 'Decorators' | |
- 'Files' | |
CatalogContent: | |
- 'learn-python-3' | |
- 'paths/computer-science' | |
--- |
## Definition of a context managers | ||
|
||
One might want to perform some operation within a certain overarching context, be it in the form of a time counter or a database connection or the use of a [file](https://www.codecademy.com/resources/docs/python/files). This is what **context managers** allow to do by implementing a **runtime context**, within which can be perform the wanted code and that closes automatically just after, sparing to the user the hassle of doing so. Regardless of the many different use cases a context manager can be used for, the **context manager protocol** always articulates those four functionalities: open the resource, implement the runtime context, handle the possible [exceptions](https://www.codecademy.com/resources/docs/python/errors), close the resource. The user input finds its place once the runtime context is started. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
## Definition of a context managers | |
One might want to perform some operation within a certain overarching context, be it in the form of a time counter or a database connection or the use of a [file](https://www.codecademy.com/resources/docs/python/files). This is what **context managers** allow to do by implementing a **runtime context**, within which can be perform the wanted code and that closes automatically just after, sparing to the user the hassle of doing so. Regardless of the many different use cases a context manager can be used for, the **context manager protocol** always articulates those four functionalities: open the resource, implement the runtime context, handle the possible [exceptions](https://www.codecademy.com/resources/docs/python/errors), close the resource. The user input finds its place once the runtime context is started. | |
## Definition | |
**Context managers** allow users to perform operations within a certain overarching context, be it in the form of a time counter or a database connection or the use of a file. They manage to do it by implementing a **runtime context**. In this context, the specified operation is first performed and then, the context automatically gets closed. This prevents the users from the hassle of closing it manually. | |
Regardless of the many different use cases that context managers can be used for, the **context manager protocol** always articulates four functionalities: | |
- Opening the resource | |
- Implementing the runtime context | |
- Handling the possible [exceptions](https://www.codecademy.com/resources/docs/python/errors) | |
- Closing the resource | |
Once the runtime context is started, the user input finds its place. |
## Manipulate files with context managers | ||
|
||
The `open()` function is the standard context manager to open, perform operations on and close files. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
## Manipulate files with context managers | |
The `open()` function is the standard context manager to open, perform operations on and close files. | |
## File Manipulation | |
The `open()` function is the standard context manager for opening, performing operations on and closing files: |
# this code will print the first four lines of the poem "L'albatros" | ||
with open('albatros.txt','r') as poem: | ||
for i in range(4): | ||
print(poem.readline()) | ||
|
||
# this code will however create an error as we are already outside of the indented block and therefore no longer within the context that had been setup | ||
print(albatros.readline()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
# this code will print the first four lines of the poem "L'albatros" | |
with open('albatros.txt','r') as poem: | |
for i in range(4): | |
print(poem.readline()) | |
# this code will however create an error as we are already outside of the indented block and therefore no longer within the context that had been setup | |
print(albatros.readline()) | |
# Printing the first four lines of the poem "L'albatros" | |
with open('albatros.txt', 'r') as poem: | |
for i in range(4): | |
print(poem.readline()) |
print(albatros.readline()) | ||
``` | ||
|
||
Output: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Output: | |
The above code produces the following output: |
print('Letter printed!') | ||
``` | ||
|
||
Result: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Result: | |
Here is the output: |
|
||
Result: | ||
|
||
```md |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
```md | |
```shell |
### Decorator-based approach | ||
|
||
In this approach, rather than a class is defined a [generator](https://www.codecademy.com/resources/docs/python/generators) function (i.e. a function performing a _yield_ and not a _return_). This function should be _decorated_ using `@contextmanager` from the built-in module `contextlib`: | ||
|
||
```py | ||
from contextlib import contextmanager | ||
``` | ||
|
||
A decorator-based context manager is also using the user input in the form of parameters provided at the instantiation. It follows the syntax _try-except-finally_, _try_ being the part where the _yield_ statement is and the core operations are done, _except_ the exceptions handling part, and _finally_ the part where the resources are closed, essentially. | ||
|
||
The below code shows an implementation of a decorator-based context manager thanks to which interview proposals are sent to pre-selected candidates. It is also possible (but not mandatory) to introduce some personalized elements in the indented block. If doing so this element will be placed just before the timeslot proposal. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
### Decorator-based approach | |
In this approach, rather than a class is defined a [generator](https://www.codecademy.com/resources/docs/python/generators) function (i.e. a function performing a _yield_ and not a _return_). This function should be _decorated_ using `@contextmanager` from the built-in module `contextlib`: | |
```py | |
from contextlib import contextmanager | |
``` | |
A decorator-based context manager is also using the user input in the form of parameters provided at the instantiation. It follows the syntax _try-except-finally_, _try_ being the part where the _yield_ statement is and the core operations are done, _except_ the exceptions handling part, and _finally_ the part where the resources are closed, essentially. | |
The below code shows an implementation of a decorator-based context manager thanks to which interview proposals are sent to pre-selected candidates. It is also possible (but not mandatory) to introduce some personalized elements in the indented block. If doing so this element will be placed just before the timeslot proposal. | |
### Decorator-Based Approach | |
In decorator-based approach, a [generator](https://www.codecademy.com/resources/docs/python/generators) function (i.e., a function performing a `_yield_ ` and not a `_return_`) is defined rather than a class. This function is _decorated_ using `@contextmanager` from the built-in module `contextlib`: | |
```pseudo | |
from contextlib import contextmanager | |
``` | |
A decorator-based context manager also uses the user input in the form of parameters provided at the instantiation. It follows the syntax `_try-except-finally_`, where `_try_` being the part where the `_yield_` statement is and the core operations are done, `_except_` being the part where the exceptions are handled and `_finally_` being the part where the resources are closed. | |
The below code shows an implementation of a decorator-based context manager thanks to which interview proposals are sent to pre-selected candidates. It is also possible (but not mandatory) to introduce some personalized elements in the indented block. Doing so places this element just before the timeslot proposal: |
for a wealth management software. ') | ||
``` | ||
|
||
Result: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Result: | |
The output for the above code is as follows: |
|
||
Result: | ||
|
||
```md |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
```md | |
```shell |
Description
Adding an entry that explains the concept of context managers and introduces the ways to use concept managers with files.
Issue Solved
It was not related to an existing issue.
Type of Change
Checklist
main
branch.Issues Solved
section.