Python Forum
Type hinting - return type based on parameter
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Type hinting - return type based on parameter
#1
I've had the pleasure of writing some Python at work recently, but I was stumped by something. I want something like this:
def get_from_dict(d: dict, key: str, value_type = int) -> type(value_type):
    value = d.get(key)
    if value is None:
        raise RuntimeError(f"Tried to fetch {key} from dictionary {d} but dictionary did not have the key.")

    return value_type(value)
My workaround was to hard-code it as int because that's my use case, but while I was writing the code, I wanted to make it more generic. I doubt this is possible, at least in the current state of Python's type hinting, but does anyone happen to have any ideas?
Reply
#2
You always can define a custom decorator, e.g.

import inspect
from functools import wraps
from typing import Any

def set_rettype_as_var(variable_name):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs_inner):
            return f(*args, **kwargs_inner)
        
        desired_type = Any
        signature = inspect.getfullargspec(f)
        if signature.kwonlydefaults and variable_name in signature.kwonlydefaults:
            desired_type = type(signature.kwonlydefaults.get(variable_name))
            # probably, you can take into account signature.annotations ... 
            
        if signature.args and variable_name in signature.args:
            if signature.defaults is not None:
                desired_type = type(signature.defaults[signature.args.index(variable_name)])
            else:
                desired_type = signature.annotations.get(variable_name, Any)
            
        # maybe you will need to define some other conditions .... 
        
        wrapper.__annotations__['return'] = desired_type
        return wrapper
    return decorator
@set_rettype_as_var('x')
def a(x:float):
    pass
a.__annotations__
Error:
{'x': float, 'return': float}
Reply
#3
That's not quite what I'm looking for. The return type is specified at function definition, when I want it to depend on the type of the value of the argument, not a fix parameter type.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question How to get a removable disc type in drive Daring_T 12 970 Feb-11-2024, 08:55 AM
Last Post: Gribouillis
  all of attributes and methods related to a special type akbarza 4 425 Jan-19-2024, 01:11 PM
Last Post: perfringo
  Precision with Decimal Type charlesrkiss 9 635 Jan-18-2024, 06:30 PM
Last Post: charlesrkiss
  How to detect this type of images AtharvaZ 0 311 Jan-02-2024, 03:11 PM
Last Post: AtharvaZ
  problem with help(type(self)) in Idle akbarza 1 432 Dec-26-2023, 12:31 PM
Last Post: Gribouillis
  Static type checking with PyPy pitosalas 1 391 Dec-14-2023, 09:29 PM
Last Post: deanhystad
  How does sqlite3 module determine value type mirlos 2 894 Dec-12-2023, 09:37 AM
Last Post: mirlos
  mypy, type aliases and type variables tomciodev 1 656 Oct-18-2023, 10:08 AM
Last Post: Larz60+
  ValueError: Unknown label type: 'continuous-multioutput' hobbyist 7 1,191 Sep-13-2023, 05:41 PM
Last Post: deanhystad
  determine parameter type in definition function akbarza 1 550 Aug-24-2023, 01:46 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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