Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

Thomas Passin list1 at tompassin.net
Sat Feb 25 09:10:06 EST 2023


On 2/25/2023 1:13 AM, Peter J. Holzer wrote:
> On 2023-02-24 18:19:52 -0500, Thomas Passin wrote:
>> On 2/24/2023 2:47 PM, dn via Python-list wrote:
>>> On 25/02/2023 08.12, Peter J. Holzer wrote:
>>>> On 2023-02-24 16:12:10 +1300, dn via Python-list wrote:
>>>>> In some ways, providing this information seems appropriate.
>>>>> Curiously, this does not even occur during an assert exception -
>>>>> despite the value/relationship being the whole point of using
>>>>> the command!
>>>>>
>>>>>       x = 1
>>>>>       assert x == 2
>>>>>
>>>>> AssertionError (and that's it)
>>
>> Sometimes you can use a second parameter to assert if you know what kind of
>> error to expect:
>>
>>>>> a = [1,2,3]
>>>>> b = [4,5]
>>>>> assert len(a) == len(b), f'len(a): {len(a)} != len(b): {len(b)}'
>> Traceback (most recent call last):
>>    File "<stdin>", line 1, in <module>
>> AssertionError: len(a): 3 != len(b): 2
> 
> Yup. That's very useful (but I tend to forget that).
> 
> 
>> With type errors, assert may actually give you the information needed:
>>
>>>>> c = {"a": a, "b": 2}
>>>>> assert a > c
>> Traceback (most recent call last):
>>    File "<stdin>", line 1, in <module>
>> TypeError: '>' not supported between instances of 'list' and 'dict'
> 
> Actually in this case it isn't assert which gives you the information,
> it's evaluating the expression itself. You get the same error with just
>      a > c
> on a line by its own.

In some cases.  For my example with an explanatory string, you wouldn't 
want to write code like that after an ordinary line of code, at least 
not very often.  The assert statement allows it syntactically.



More information about the Python-list mailing list