Skip to content
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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

Maet22
Copy link

@Maet22 Maet22 commented Apr 17, 2024

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

  • Adding a new entry

Checklist

  • All writings are my own.
  • My entry follows the Codecademy Docs style guide.
  • My changes generate no new warnings.
  • I have performed a self-review of my own writing and code.
  • I have checked my entry and corrected any misspellings.
  • I have made corresponding changes to the documentation if needed.
  • I have confirmed my changes are not being pushed from my forked main branch.
  • I have confirmed that I'm pushing from a new branch named after the changes I'm making.
  • I have linked any issues that are relevant to this PR in the Issues Solved section.

@Sriparno08 Sriparno08 self-assigned this May 7, 2024
@Sriparno08 Sriparno08 added python Python entries new entry New entry or entries status: under review Issue or PR is currently being reviewed labels May 7, 2024
Copy link
Collaborator

@Sriparno08 Sriparno08 left a 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:

Comment on lines +1 to +15
---
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'
---
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
---
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'
---

Comment on lines +17 to +19
## 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.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
## 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.

Comment on lines +21 to +23
## Manipulate files with context managers

The `open()` function is the standard context manager to open, perform operations on and close files.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
## 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:

Comment on lines +26 to +32
# 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())
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# 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:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Output:
The above code produces the following output:

print('Letter printed!')
```

Result:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Result:
Here is the output:


Result:

```md
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```md
```shell

Comment on lines +98 to +108
### 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.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
### 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:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Result:
The output for the above code is as follows:


Result:

```md
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```md
```shell

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants