[Tutor] Using try, except else inside function definition

Manprit Singh manpritsinghece at gmail.com
Wed Oct 20 21:29:30 EDT 2021


Dear Sir,

I have written the count_words function again, but this time i am not
including try except and else inside function, this seems more good to me

def count_words(filename):
    with open(filename) as fileobj:
        content = fileobj.read()
    return len(content.split())

try:
    filename ="fileread.txt"
    wdcnt = count_words(filename)

except FileNotFoundError:
    print("File not exists")

else:
    print("Number of words in file are", wdcnt)

What do you say? kindly comment

Regards
Manprit Singh

On Thu, Oct 21, 2021 at 1:59 AM Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 20/10/2021 19:29, Manprit Singh wrote:
>
> > def count_words(filename):
> >     try:
> >         with open(filename) as fileobj:
> >             content = fileobj.read()
> >
> >     except FileNotFoundError:
> >         print(f'Sorry the file {filename} not exists')
> >
> >     else:
> >         words = content.split()
> >         cntwd = len(words)
> >         print(f'The file {filename} has {cntwd} words')
> >
> > This is working fine, my question is can we place try, except & else
> blocks
> > inside the function definition as done above.
>
> The fact it is "working fine" tells you that you can.
> And indeed that is perfectly normal.
>
> The only thing I'd say is that the function is called
> count words so I'd expect it to return a value not
> print a message. The printing should be done outside
> the function and the function just return the value
> or raise the exception.
>
> > def indexofelement(seq, ele):
> >     try:
> >         if ele not in seq:
> >             raise ValueError
> >     except ValueError:
> >         return -1
>
> This is kind of pointless. Instead of raising the
> ValueError and immediately catching it just
> return -1. Handling errors is relatively expensive
> so if you don't need to do it its better to just
> return the value directly. However in this case
> you are probably better removing the try/except
> construct and just raise the ValueError with a
> suitable message.
>
> >     else:
> >         for ind, val in enumerate(seq):
> >             if val == ele:
> >                 return ind
>
> > Returning values in this way from the function is ok ?
>
> Its OK but its an old fashioned way of handling
> errors - especially since -1 is a valid index in Python.
> If a user used the index without checking they would
> get a result(albeit a faulty one. If you raise the
> exception instead the user has no choice but be
> aware of it either by handling it or via the stacktrace
> if they ignore it.
>
> Part of the rationale for try/except style error handling
> is to remove the need for checking for magic return values.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list