Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with def, try, except
#1
Environment CentOS 7 fully patched. Python 3.6.

I have the following bit of code that is failing validation. The validation script runs all of my definitions with bogus data to make sure they are valid and the following bit is failing.

def get_panos_major_version(ver):
    try:
        return (".".join((ver).split(".",2)[:2])
    except:
        return 0
The purpose of this function is to take a version number of the format #.#.# and return the begining 2 numbers and the dot for use in a Mkao tamplate. This works fine from a shell:

ver="8.10.2"
".".join(ver.split(".",2)[:2])
'8.10'
I am still very new to python so I am not sure if I am missing a basic principal or if I am doing something else wrong.
Reply
#2
You have an unnecessary parenthesis on this line:
return (".".join((ver).split(".",2)[:2])
Should be:
return ".".join((ver).split(".",2)[:2])
That said, why are you even catching the exception? An exception being raised seems like exactly what you want if someone calls the function with the wrong format.

Also, for what it is worth 0 is usually a successful return value not a failure. If you must return a fail value then I suggest -1.
Reply


Forum Jump:

User Panel Messages

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