Jan-13-2020, 11:33 PM
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?
Feel like you're not getting the answers you want? Checkout the help/rules for things like what to include/not include in a post, how to use code tags, how to ask smart questions, and more.
Pro-tip - there's an inverse correlation between the number of lines of code posted and my enthusiasm for helping with a question :)
Pro-tip - there's an inverse correlation between the number of lines of code posted and my enthusiasm for helping with a question :)