Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8447543
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T10:12:13+00:00 2026-06-10T10:12:13+00:00

I’m trying to perform good input validity checking on my python code, but I

  • 0

I’m trying to perform good input validity checking on my python code, but I also want it to be succinct. That is, the solution I don’t want to go with is this one:

def some_func(int_arg, str_arg, other_arg):
    try:
        int_arg = int(int_arg)
    except TypeError, ValueError
        logging.error("int_arg must respond to int()")
        raise TypeError
    try:
        if str_arg is not None:
            str_arg = str(str_arg) 
    except TypeError
        logging.error("Okay, I'm pretty sure this isn't possible, bad example")
        raise TypeError
    if other_arg not in (VALUE1, VALUE2, VALUE3):
        logging.error("other arg must be VALUE1, VALUE2, or VALUE3")
        raise TypeError

This is just too much code and to much space to spend on just checking 3 arguments.

My current approach is this:

def some_func(int_arg, str_arg, other_arg):
    try:
        int_arg = int(int_arg)  #int_arg must be an integer
        str_arg is None or str_arg = str(str_arg)  #str_arg is optional, but must be a string if provided
        assert other_arg in (VALUE1, VALUE2, VALUE3)
    catch TypeError, ValueError, AssertionError:
        logging.error("Bad arguments given to some_func")
        throw TypeError

I lose the specificity of my log message, but this is much more succinct and honestly more readable in my opinion.

One thing specifically I’m wondering about is the use of the assert statement. I’ve read that it’s discouraged to use assertions as a way of checking input-validity, but I was wondering if this was a legitimate way to use it.
If not, is there a similar way to perform this check (or do this validation in general) that’s still pretty succinct?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T10:12:15+00:00Added an answer on June 10, 2026 at 10:12 am

    You could invent a decorator that would validate the arguments for you.

    This is how the syntax could look like:

    @validate(0, int)
    @validate(1, str, logMessage='second argument must respond to str()')
    @validate(2, customValidationFunction)
    def some_func(int_arg, str_arg, other_arg):
        # the control gets here only after args are validated correctly
        return int_arg * str_arg
    

    This is a naive implementation of the validation decorator factory.

    def validate(narg, conv, logMessage = None):
        def decorate(func):
            def funcDecorated(*args):
                newArgs = list(args)
                try:
                    newArgs[narg] = conv(newArgs[narg])
                except Exception, e:
                    # wrong argument! do some logging here and re-raise
                    raise Exception("Invalid argument #{}: {}".format(narg, e))
                else:
                    return func(*newArgs)
    
            return funcDecorated
        return decorate
    

    Yes, there’s a bit of function nesting here, but it all makes sense. Let me explain:

    • A decorator is something that takes one function and returns another
    • We want validate(narg, converter) to be a function that takes some settings and returns a specific decorator (decorate) which behaves according to these settings
    • decorate is then used to decorate a given function (func) that takes some positional arguments by creating a new function funcDecorated that takes the same arguments as func (*args) and is written in terms of input function func as well as the initial settings narg, conv.

    The actual validation happens inside funcDecorated, which…

    • takes the input argument list,
    • replaces n-th argument by validating and/or converting it (whatever conv does),
    • calls the input func with the altered argument list.

    To do this for several arguments, we apply validate multiple times with different arguments. (It’s possible to rewrite it to only decorate once, but it looks more clear this way IMO.)

    See it in action: http://ideone.com/vjgIS


    Note that conv can act either…

    • as a validation function (return whatever it receives, but throw if it’s invalid)
    • as a conversion function (return the converted value, throw if can’t convert)

    Note that this implementation doesn’t handle keyword arguments.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a French site that I want to parse, but am running into
I want to count how many characters a certain string has in PHP, but
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I want to construct a data frame in an Rcpp function, but when I
I'm trying to create an if statement in PHP that prevents a single post
I need to clean up various Word 'smart' characters in user input, including but
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.