Discussion:
Checking That Two Args Are Of Same Type (Posting On Python-List Prohibited)
(too old to reply)
Lawrence D'Oliveiro
2024-06-23 01:17:35 UTC
Permalink
Consider a function taking two args “a” and “b”, which can be of str,
bytes or bytearray type, just so long as both are of the same type.
One easy way to test this is

if sum(isinstance(a, t) and isinstance(b, t) for t in (str, bytes, bytearray)) != 1 :
raise TypeError("args must both be str or bytes")
#end if

Actually, both “and’ and “or” will work.
Keith Thompson
2024-06-23 05:56:32 UTC
Permalink
Lawrence D'Oliveiro <***@nz.invalid> writes:
[snip]

Just curious, why do you add "Posting On Python-List Prohibited" to your
subject lines?
--
Keith Thompson (The_Other_Keith) Keith.S.Thompson+***@gmail.com
void Void(void) { Void(); } /* The recursive call of the void */
Paul Rubin
2024-06-23 07:00:29 UTC
Permalink
Post by Lawrence D'Oliveiro
Consider a function taking two args “a” and “b”, which can be of str,
bytes or bytearray type, just so long as both are of the same type.
One easy way to test this is
if type(a)==type(b) and type(a) in (str, bytes, bytearray): ...
Lawrence D'Oliveiro
2024-06-23 07:13:26 UTC
Permalink
Post by Paul Rubin
Post by Lawrence D'Oliveiro
Consider a function taking two args “a” and “b”, which can be of str,
bytes or bytearray type, just so long as both are of the same type.
One easy way to test this is
if type(a)==type(b) and type(a) in (str, bytes, bytearray): ...
Better to use isinstance instead of direct type comparison.
Lawrence D'Oliveiro
2024-06-23 22:55:29 UTC
Permalink
Post by Lawrence D'Oliveiro
Actually, both “and’ and “or” will work.
No it won’t. It’ll fail in the case where one or the other arg is of an
entirely different type.

Loading...