Python In The Middle Of The Night Cos I Can't Sleep

Python In The Middle Of The Night Cos I Can't Sleep

When I was little, my dad used to take me to the woods to stargaze.

We would look for Venus.

Those were the most magical nights of my life.

The place where we used to look for stars is now surrounded by wind farms.

And I don't think it's a coincidence.

Wind farms are the great, great, great love of my life.

Renewable energy is the great love of my life.

I have done everything to be in renewable energy.

I have done everything to stay in renewable energy.

When I lost my job in February, I didn't even miss a beat. I had to be dragged to the pub at the end of the day. I was online and applying. I taught myself beginner's Python in 10 days. I taught myself Django.

Over the past 8 months I have given everything I can.

I have given everything I can until I have nothing more to give. And then I have given some more.

I have navigated recovery from a seizure disorder. I dare to say it's going better - so so much better - although I do not even dare to blink yet. I can feel the triggers and I can feel my body reacts less. I still get tired. I still have to stop and sit down in random places - although not even that random, small walls, no more street floors.

It's better. I have given everything I can this year. I have worked nearly every waking minute.

I have taught myself Python, problem solving.

I have taught myself everything I could. I have navigated errors and debugging. I have made my big jump. And if it's not enough then it's not enough. I forgive myself. I have done everything I can do. I have navigated the immense challenge of being neurodivergent in the workplace every day. And I have done so in a rather unstructured company.

Sometimes you have nothing more to give.

I don't even know what I have left anymore.

Class Based Context Managers

  • We need context managers to protect our computer's resources.
  • The with statement makes sure we close files so that we don't leave them open.
There are two approaches for creating context managers. One of them is a class-based approach.

A pink white and gold image with flowers and text explaining that I have done the full context management quiz and lesson

All we have to do is to define the __enter__ and __exit__ methods inside of a class.

The __enter__ method in context managers

The __enter__ method takes care of opening resources like files.

This method also takes care of the runtime context. This means everything that happens under the __with__ block. Basically the execution of the code.

The __exit__ method in context managers

This takes care of the "breakdown of the context manager". This can mean closing open resources that are no longer in use.

Here is an example of a class based context manager that I wrote

Here is some code:

class PoemFiles:
  def __init__(self):
    print('Creating Poems!')
  
  def __enter__(self):
    print('Opening poem file')

  def __exit__(self, *exc):
    print('Closing poem file')

with PoemFiles() as manager:
  print('Hope is the thing with feathers')
Thank you

Next part

Okay so now the course is getting me to write my own context manager but it is the way the with as method is actually used. This is cool and quite funky.

I wrotre my own context manager.... 

Soooo cool wow.
class PoemFiles:
  def __init__(self, poem_file, mode):
    print('Starting up a poem context manager')
    self.file = poem_file
    self.mode = mode
  
  def __enter__(self):
    print('Opening poem file')
    self.opened_poem_file = open(self.file, self.mode)
    return self.opened_poem_file
  
  def __exit__(self, *exc):
    print('Closing poem file')
    self.opened_poem_file.close()

with PoemFiles('poem.txt', 'w') as open_poem_file:
  open_poem_file.write('Hope is the thing with feathers')

Handling exceptions

Have just found out that the *exc argument in the __exit__ method is to do with handling exceptions.

It is responsible for safely closing a file if an error occurs, for example.

As well as self, the  __exit__ method needs 3 other arguments.
  • The type of error 
  • An exception value: the actual value of the error
  • A traceback: a report detailing the sequence of steps that caused the error and all the details needed to fix the error
So it's like exception type, exception value, and traceback...

Okay wrote some cool code.

Some more information then

If we want to throw an error when an error occurs, we can either return False at the end of the  __exit__ method, after the .close() method, or do nothing.

Or if we want to suppress the error, we can return True.

It is important to close the file before any potential exceptions get raised so that the file gets closed for sure.

Contextlib

This is basically just another module that let us create our own custom context managers.

Here is what I wrote.
from contextlib import contextmanager

@contextmanager
def poem_files(file, mode):
  print('Opening File')
  open_poem_file = open(file, mode)
  try:
    yield open_poem_file
  finally:
    print('Closing File')
    open_poem_file.close()

with poem_files('poem.txt', 'a') as opened_file:
 print('Inside yield')
 opened_file.write('Rose is beautiful, Just like you.')
And now some error handling...

Errors in contextlib

These are dealt with in an except block, rather than in an __exit__() method. We can either do nothing with our errors and allow our programs to crash, or handle them with an except block and allow the program to keep running!

Here's an error handler that I wrote in contextlib:
from contextlib import contextmanager
 
@contextmanager
def poem_files(file, mode):
  print('Opening File')
  open_poem_file = open(file, mode)
  try:
    yield open_poem_file

  except AttributeError as e:
    print(e)


  finally:
    print('Closing File')
    open_poem_file.close()

with poem_files('poem.txt', 'a') as opened_file:
 print('Inside yield')
 opened_file.sign('Buzz is big city. big city is buzz.')

Nested context managers

Omg I am so tired. I just want to sleeeeeeep. I have been exhausted for hours.

But I want to finish, this course, finally!!! 

This lesson makes sense.

For example you can read multiple files within the same with statement. There are two different types of syntax for doing this as well, also.

In summary...
  • Context managers are a type of resource manager in python invoked by the with statement
Effortlessly got 100% on my quiz... yay.

A score of 100% on a context management quiz.

P.S. I lied. I got super tired after the first lesson.
I would've been ready to sleep. But oops. 

Oh well... Nevermind.



Comments

Popular posts from this blog

Hello World

Yosemite

Where To Hide A Star