0

I've been reading the learn python3 the hard way book and in a exercise about python symbols he refers to a 'as' symbol and in the description it says "Part of the with-as statement" and the example format is "with X as Y: pass" but i couldn't find anything about such a thing online so I'm asking here.

Does anyone know anything about it? and as a refrence it's exercise 37

Arian
  • 11
  • 4
  • `with` is called a context manager. Most commonly used for files. `with open('some_file', 'w') as opened_file: opened_file.write('Hola!')` You'll see it everywhere really. it is not the only place where `as` is used however, you also use it in imports. `import numpy as np` and so on – Paritosh Singh Dec 12 '18 at 16:10
  • The key here is the `with` statement. See here for an explanation: https://stackoverflow.com/a/1369553/141789. `as` just gives you a handle with which to access the object referenced by the with. – Karl Dec 12 '18 at 16:14

1 Answers1

0

The With x as y construct in python in called a context manager.

Context managers are used to properly manage resources. For example, if one is used to open a file, a context manager will ensure the file is closed.

with open('my_file.txt', 'r') as file:
    for line in file:
        print('{}'.format(line))

This is equivalent to:

file = open('my_file.txt') as file
for line in file:
    print('{}.format(line))

file.close()

As you can see, the call to the close function is not necessary when you use a context manager.Its easy to forget to close the file, and this can lead to your system crashing if too many files are open. (There is a maximum number allowed by the operating system.)

See this link for more information and examples.

Nick
  • 3,454
  • 6
  • 33
  • 56