duck-typing

Duck Typing Annotations in Python3

Duck Typing Annotations in Python3 Question: I am trying to add a type annotation to a function input argument that is a dataclass with attributes that overlap with another dataclass, which actually gets passed in as an input argument. Consider the following code: from dataclasses import dataclass from typing import TypeVar @dataclass class Foo: a: …

Total answers: 1

How to add a dataclass field without annotating the type?

How to add a dataclass field without annotating the type? Question: When there is a field in a dataclass for which the type can be anything, how can you omit the annotation? @dataclass class Favs: fav_number: int = 80085 fav_duck = object() fav_word: str = ‘potato’ It seems the code above doesn’t actually create a …

Total answers: 4

What is the right way to treat Python argparse.Namespace() as a dictionary?

What is the right way to treat Python argparse.Namespace() as a dictionary? Question: If I want to use the results of argparse.ArgumentParser(), which is a Namespace object, with a method that expects a dictionary or mapping-like object (see collections.Mapping), what is the right way to do it? C:>python Python 2.7.3 (default, Apr 10 2012, 23:31:26) …

Total answers: 4

How to identify numpy types in python?

How to identify numpy types in python? Question: How can one reliably determine if an object has a numpy type? I realize that this question goes against the philosophy of duck typing, but idea is to make sure a function (which uses scipy and numpy) never returns a numpy type unless it is called with …

Total answers: 6

How to handle "duck typing" in Python?

How to handle "duck typing" in Python? Question: I usually want to keep my code as generic as possible. I’m currently writing a simple library and being able to use different types with my library feels extra important this time. One way to go is to force people to subclass an “interface” class. To me, …

Total answers: 5

How can I tell if a python variable is a string or a list?

How can I tell if a python variable is a string or a list? Question: I have a routine that takes a list of strings as a parameter, but I’d like to support passing in a single string and converting it to a list of one string. For example: def func( files ): for f …

Total answers: 8