When should I use type checking (if ever) in Python?

2024/9/20 9:44:47

I'm starting to learn Python and as a primarily Java developer the biggest issue I am having is understanding when and when not to use type checking. Most people seem to be saying that Python code shouldn't need type checking, but there are many cases when I believe it is necessary. For example, let's say I need to use a method parameter to perform an arithmetic operation, why shouldn't I make sure the argument is a numeric data type?

This issue is not only limited to functions. The same thought process occurs to me for class variables. Why and when should I or shouldn't I use properties (using @property) to check type instead of regularly implemented class variables?

This is a new way of approaching development for me so I would appreciate help understanding.

Answer

It's not Pythonic to check type info, use duck typing instead: if it looks like a duck, walks like a duck and quacks like a duck then it is a duck.

def quack(duck):duck.quack()

this will only run if duck has a callable quack attrubute, it will raise an exception otherwise which can be caught by the caller.

https://en.xdnf.cn/q/72358.html

Related Q&A

Kartograph python script generates SVG with incorrect lat/long coords

I have modified this question to reflect some progress on discovering the problem. I am using the following python code to generate an SVG of the continental USA. The shapefile is irrelevant, as the …

Python multiprocessing blocks indefinately in waiter.acquire()

Can someone explain why this code blocks and cannot complete?Ive followed a couple of examples for multiprocessing and Ive writting some very similar code that does not get blocked. But, obviously, I…

What is the best way to control Twisteds reactor so that it is nonblocking?

Instead of running reactor.run(), Id like to call something else (I dunno, like reactor.runOnce() or something) occasionally while maintaining my own main loop. Is there a best-practice for this with …

Accessing the content of a variable array with ctypes

I use ctypes to access a file reading C function in python. As the read data is huge and unknown in size I use **float in C . int read_file(const char *file,int *n_,int *m_,float **data_) {...}The func…

What is the stack in Python?

What do we call "stack" in Python? Is it the C stack of CPython? I read that Python stackframes are allocated in a heap. But I thought the goal of a stack was... to stack stackframes. What …

Pandas: Resample dataframe column, get discrete feature that corresponds to max value

Sample data:import pandas as pd import numpy as np import datetimedata = {value: [1,2,4,3], names: [joe, bob, joe, bob]} start, end = datetime.datetime(2015, 1, 1), datetime.datetime(2015, 1, 4) test =…

How to filter string in multiple conditions python pandas

I have following dataframeimport pandas as pd data=[5Star,FiveStar,five star,fiv estar] data = pd.DataFrame(data,columns=["columnName"])When I try to filter with one condition it works fine.d…

Is there a way to use a dataclass, with fields with defaults, with __slots__

I would like to put __slots__ on a dataclass with fields with defaults. When I try do that, I get this error: >>> @dataclass ... class C: ... __slots__ = (x, y, ) ... x: int ... y:…

Read remote file using python subprocess and ssh?

How can I read data from a big remote file using subprocess and ssh?

Django - get_queryset() missing 1 required positional argument: request

I was trying to make an API using REST Framework for uploading a file to the server and my codes are below.If you have any other easy method to do the same please post your code.models.pyfrom django.db…