Note that there are some explanatory texts on larger screens.

plurals
  1. POvalidating argument types for different functions using a single interface (without using inspect)
    primarykey
    data
    text
    <p>I wish to check the types of the arguments for each function in the module (without making use of inspect module). The easiest solution I have done myself is to implement the check in each function separately.</p> <pre><code>def func1( num1, num2 ): # the two params must be integers if isinstance( num1, int ) and isinstance( num2, int ): # ...function code... pass else: return def func2( float1 ): # The only param must be float if isinstance( float1, float ): # ...function code... pass else: return def func3( str1 ): # string if isinstance( str1, str ): # ...function code... print 'fdfd' pass else: return # and, so on ... </code></pre> <p>But, want to do it at the module level, rather than doing it for each function. Each function can have different arguments. Please note that this is not function overloading. I was thinking of either writing a decorator or a metaclass. Here are the problems that I faced in both the approaches:-</p> <ol> <li>Using a common decorator for all the functions:<br> In this method, I am not able to access the actual variables defined inside each function, so scrapped this idea. Here is a closure (to be used as decorator) that I was planning to write :</li> </ol> <blockquote> <pre><code>def dec( funcName ): def typeChecker(): i = __import__( __name__ ) for m in map( lambda x: i.__getattribute__( x ), dir( i ) ): if '__call__' in dir( m ): #Identifying a real function or callable which can be treated as function ## Now, that the function is identified, what should I do here to type-check the arguments?? return typeChecker </code></pre> </blockquote> <p>Please provide some insights here as to how I can make this work.</p> <p>2.Using a metaclass for creating function<br> I was just wondering if I could access the arguments being sent to a function using a metaclass and then, validate each of the argument, and then, return a brand new class which would be responsible for creating the function object. But, do not know how to do it. Is it a good way of solving this problem?</p> <p>1 very good suggestion Martijn Peters has given - To use annotations. Is there something in Python 2.7 that we can use?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload