On 8/13/2019 5:49 PM, Andrew Barnert via Python-ideas wrote:
But I think the lazy-import-decimal-on-first-dump-with-use_decimal solves that, and solves it even better than __json__, even besides the fact that it’s a better API than exposing “dump raw text into any JSON, and it’s up to you to get it right”.
No import time if you’re not using it, just setting a global to None. Even if you are using it, the cost of importing it from the sys.modules cache is pretty tiny. (After all, you won’t have any Decimal objects without having imported decimal, unless you do some nasty tricks—at which point monkeypatching json to fake the import isn’t any nastier.)
dataclasses does something similar: it wants to know if something is a typing.ClassVar, but it doesn't want to import typing to find out. So it has:
typing = sys.modules.get('typing') if typing: if (_is_classvar(a_type, typing) or (isinstance(f.type, str) and _is_type(f.type, cls, typing, typing.ClassVar, _is_classvar))):
If typing hasn't been imported, it knows that a_type can't be typing.ClassVar.
So, this pattern isn't unheard of.