Python Forum
To correct inline or not to correct inline
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
To correct inline or not to correct inline
#1
This is an opinion question.

When I code, I generally use assert statements, @property, or casting to check, error out, and/or correct improper parameters passed in. However, some feel this is bloat and I should just let bad parameters error out to force the calling developer to correct her/his code.

Which is the more pythonic method? Fix it or let it crash?

I.e.
def testMethod(intParam, stringCharParam):
    try: 
        intParam = int(intParam)
        if  ((intParam < 1) or (intParam > 10)):
            raise ValueError()
    except: 
        raise ValueError("The parameter intParam must be an integer between 1 and 10. [intParam = {}]".format(str(intParam)) )
    log.debug("intParam = {}".format(str(intParam)))

    stringCharParam = ''.join(c for c in str(stringCharParam) if re.match("[a-zA-Z]", c))
    assert len(stringCharParam) > 0 , "The parameter stringCharParam must be a string containing only characters (I.e. A-Z,a-z ). [stringCharParam = {}]".format(str(stringCharParam))
    log.debug("stringCharParam  = {}".format(stringCharParam ))

    print(intParam, stringCharParam)
Reply
#2
Here's how I would do it:

def testMethod(intParam, stringCharParam):
    intParam = int(intParam)   # keep it simple, let int() raise it's own exception.
    if  ((intParam < 1) or (intParam > 10)):
        raise ValueError('Integer parameter must be between 1 and 10.')  # make your exceptions specific
    log.debug("intParam = {}".format(intParam))   # str() not needed, format handles that
 
    if not str(stringCharParam).isalpha():  # testing each character with a regex is total overkill
        raise ValueError('stringCharParam must be all letters.')   # assertion errors are rather vague, be specific
    log.debug("stringCharParam  = {}".format(stringCharParam ))
 
    print(intParam, stringCharParam)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Thanks for the code review and the example code (I'll offer an upvote tomorrow when my points reset :D )

What are your thoughts on the
stringCharParam = ''.join(c for c in str(stringCharParam) if re.match("[a-zA-Z]", c))
# or perhaps better ...
stringCharParam = ''.join(c for c in str(stringCharParam) if c.isalpha())
This would strip out all non-alpha chars and let the method continue, albeit with data different from what was entered. Some have felt this is bad, because if bad data comes in - the script "should" halt. It could also be bad, because the altered parameter may or may not hold the original intent.

I.e.
If the user enters "abc, " (abc comma space) by accident - then the corrections would reflect the correctly intended data (abc).

But if the user had entered "c2t0d0" (a Solaris disk path), the corrected value of "ctd" would continue processing sanely, but may result in completely incorrect results.
Reply
#4
Messing with user input is tricky. Simple things, like capitalizing words is generally okay. Assuming things when the user expects the assumptions in generally okay, like expanding abbreviations. Stripping out the non-alphabetic characters seems to go too far.

How often are you going to get correct output having stripped characters vs. getting incorrect output? If it's a low probability of correct output, I would kick it back to the user rather than create a bunch of errors.

If stripping is the way to go, I might go with strCharParam = ''.join(re.findall('[A-Za-z]*', str(strCharParam))). I'm also a big fan of compiling regular expressions once and then reusing them.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question [SOLVED] Correct way to convert file from cp-1252 to utf-8? Winfried 8 913 Feb-29-2024, 12:30 AM
Last Post: Winfried
  Selecting correct xlrd version Kithsiri 4 566 Feb-27-2024, 07:09 AM
Last Post: Kithsiri
  encode/decode to show correct country letters in a CTk combobox janeik 2 732 Sep-02-2023, 09:46 AM
Last Post: janeik
  Graph is not appearing in correct frame? garynewport 2 1,091 Jan-11-2023, 11:55 AM
Last Post: garynewport
  Looping a question until correct feedback is given TylerTrunzo 9 1,872 Oct-31-2022, 12:19 PM
Last Post: rob101
  Take inline argument value SM_13 2 1,115 Jul-06-2022, 11:12 AM
Last Post: snippsat
  Correct the algorithm of image filter code saoko 6 2,029 May-08-2022, 05:06 PM
Last Post: saoko
  The formula in the function is not giving the correct value quest 1 1,244 Mar-30-2022, 03:20 AM
Last Post: quest
  Cannot correct this Led_Zeppelin 1 2,056 Oct-19-2021, 05:05 PM
Last Post: ndc85430
  how can I correct the Bad Request error on my curl request tomtom 8 5,090 Oct-03-2021, 06:32 AM
Last Post: tomtom

Forum Jump:

User Panel Messages

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