Home > OS >  Check if function passed as argument to class __init__ returns right type
Check if function passed as argument to class __init__ returns right type

Time:11-16

I am trying to set up a class to generalize some numerical simulations, the core of the problem is the following:

Imagine I have a function that returns a numpy.ndarray type, like

def new_fun():
    return numpy.zeros((2,2,2,2))

and then I have a class declaration like:

class NewClass:
    def __init__(self,function):
        self.function  = function 

My Goal: I would like to check upon class initialization if the argument passed to __init__ is a function and returns the right type, for instance something like:

class NewClass:
    def __init__(self,function):
        if type(function) is types.FunctionType:
        #from here is pseudocode
           if return_type(function) is numpy.ndarray:
              self.function  = function 

Important is: given the type of application,the passed function must not be executed to get information about is return type, it could take a while.

CodePudding user response:

Check if it's callable

def __init__(self, fn):
    assert callable(fn)

It's not practical to know what some functions will return, but you can use type hints around this

from typing import Callable
...

    def __init__(self, fn: Callable[[None], numpy.ndarray]):
        if not callable(fn):
            raise TypeError("expected a callable function, but got {type(fn)}")

A great benefit of Python is that it's easy to read and write - in most cases, it's not practical or helpful to prevent users from misusing your API, but you should strive to help them use it properly with a good docstring, comments, and type hinting

  • Related