learning python. learning defining functions . need help
Steven D'Aprano
steve at pearwood.info
Fri Jul 22 21:44:56 EDT 2016
On Sat, 23 Jul 2016 01:21 am, justin walters wrote:
> That should illustrate why. This is because simply typing '{}' could be
> interpreted as
> either a dict or a set.
No. {} is always an empty dict. That is a language guarantee. Any
programming language where {} is not an empty disk is not valid Python.
> My interpreter defaults 'type({})' to 'dict', but it's best to not
> take the risk.
Are you concerned that type([]) might not be list? Or type("") might not be
str? Or that type(0) might not be int?
> You could also replace that line with:
>
> if stock is None or type(stock) != dict:
Generally speaking, the right way to test whether something is an instance
of a type is to use the isinstance() function:
if stock is None or not isinstance(stock, dict): ...
That will work correctly even if stock belongs to a subclass of dict.
--
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list