Python Forum
could open() fail w/o an exception?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
could open() fail w/o an exception?
#1
is there any known circumstance, situation, or case, in which open() or at least open(some_file_name,'w') could fail without raising an exception? IOW, when calling open() in write mode in a function which is given the filename for the defined purpose of writing, should that function test the return value for something untrue or at least not a file type?

or is it OK to assume any open failure will always raise an exception that the function can ignore and let its caller handle?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
I think it's better to assume that every error will raise an exception and let the error propagate. The other possibility is that one day the call silently returns a value that is not a file ready for writing. If this ever happens, the exploiting code will receive an error when it tries to write in the "file object". This unlikely scenario is almost impossible to anticipate correctly, so the best thing to do is to ignore it until it actually happens.

Skaperen Wrote:could open() fail w/o an exception?
Anything can happen:

>>> def spam(*args, **kwargs):
...     class Spam:
...         def __enter__(self):
...             return self
...         def __exit__(self, *args, **kwargs):
...             print("Hohoho!")
...         def write(self, *args):
...             print('Hahaha!')
...             return 3
...         read = close = write
...     return Spam()
... 
>>> import builtins
>>> builtins.open = spam
>>> 
>>> with open('foo.txt', 'w') as ofile:
...     ofile.write('Hello world.')
... 
Hahaha!
3
Hohoho!
>>> 
Reply
#3
when i am writing classes and functions to be used when coding other Python scripts (aside from those specifically intended to work with exceptions or errors in some way) i should just let all error propagate up to the caller to handle, unless i can identify a specific reason to handle it. the higher up an exception is handled, the better. is this a pythonic philosophy?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
Skaperen Wrote:unless i can identify a specific reason to handle it. the higher up an exception is handled, the better. is this a pythonic philosophy?
I wouldn't swear it's pythonic, but I would largely agree with this philosophy. You can also ease the task of the client code by transmuting the exception. For example suppose you're writing a library mylib and there is a function open_resource(). This function's code uses lower level functions that may for example raise IndexError in certain circumstances. The problem is that IndexError is not semantically related to the task of opening the resource. You can transmute the exception like so
# mylib.py
class MyLibError(RuntimeError):
    pass

class ResourceUnavailable(MyLibError):
    pass

def open_resource(*args):
    try:
        ...
    except IndexError as exc:
        raise ResourceUnavailable from exc
It means that you don't handle the exception but you let the exploiting code write for example
def bacon():
    try:
        r = open_resource(spam)
    except ResourceUnavailable:
        ...
Reply
#5
so, let the exception make sense to the code that could be handling it, rather than depending on someone reading the traceback.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#6
Skaperen Wrote:let the exception make sense to the code that could be handling it, rather than depending on someone reading the traceback.
In fact both are useful. The advantage of the raise ... from ... syntax is that you can raise a sensible exception and still keep the information of the low level details of the event that generated the exception.

Encapsulating errors also happens in real life. For example, if your car won't start, that may be a sensible information for you as a driver, but if you're an auto mechanic, you'll be interested in the low level information that a fuse is blown. There are several significant levels.
Reply
#7
that actually happened to me, except it wasn't a fuse. it was corrosion in the switch contact of the transmission the was part of the loop that powered the relay that fed power to the starter motor. it was supposed to allow power to the relay when in park or neutral. and, this only happened if it rained the day before but the mechanics could find nothing wrong. it started OK and i drove it home. 3 mornings later, i try to go to work and it did the same thing. turns out all i needed to do was shift it out of park and back into park and that would rub the corrosion off enough to let it start. it was the tow truck driver that figured it out and the mechanics looked and found it was corroded. they ordered a replacement switch that came from out of the country despite it being made in the USA (Jeep Cherokee). so for the next couple weeks, i knew what to do to get it started. i found that all i really needed to do was just jiggle the transmission lever in place a couple times to get it to start. and i found that it would only take sitting for about 20 minutes in park to corrode, again, and all this only if it rained the previous day.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020