Kelketek
Kelketek

Reputation: 2446

Check for type in Python as wildcard

Normally, type checking is frowned upon in Python and for good reason-- you should know what sort of data is being passed to your function if your code is well designed.

However, I'm dealing with implementing an old programming language, and part of this has some unique challenges pertaining to input validation and compatibility.

This is a function which is used to do some basic type checking before a function is actually run:

    def argcheck(stack, funcname, arglist, exceptlist):
        """This function checks if arguments are valid and then passes back a list of them in order if they are.
        stack should contain the stack.
        funcname should contain the display name of the function for the exception.
        arglist should contain a list of lists of valid types to be checked against.
        exceptlist contains the information the exception should contain if the item does not match."""
        returnlist=[]
        count=0
        for xtype in arglist:
            if stack[-1] in xtype:
                returnlist.append(stack[-1])
                stack.pop()
            else:
                raise Exception(funcname, exceptlist[count])

Occasionally, I need something to match any type. How can I make a list of all types, or place an item in a list that returns true if anything attempts to match to it?

Upvotes: 0

Views: 1029

Answers (1)

agf
agf

Reputation: 176750

Use an empty list to match any type, and change the matching condition to be True if xtype is empty:

def argcheck(stack, funcname, arglist, exceptlist):
    returnlist=[]
    count=0
    for xtype in arglist:
        if not xtype or stack[-1] in xtype:
            returnlist.append(stack[-1])
            stack.pop()
        else:
            raise Exception(funcname, exceptlist[count])

Upvotes: 1

Related Questions