Check existence type in Python module

What would be the most Pythonic way of determining if an object type exists in a particular module?

For example, suppose I want to match dates, times, and datetime classes from the datetime module.

import datetime
mylist = [obj1, obj2, obj3, ...]
for obj in mylist:
    if type(obj) in [datetime.datetime, datetime.time, datetime.date]:
        #Do thing

It seems foolish to create an appropriate instance of three for each cycle. Is there an easier way to say "if type (obj) in some module"?

+4
source share
1 answer

isinstance() can check several types:

isinstance(object, classinfo)

true, object classinfo (, ) . , false. classinfo ( , ), true, . classinfo , TypeError.

if isinstance(obj, (datetime.datetime, datetime.time, datetime.date)):
+3

Source: https://habr.com/ru/post/1625686/


All Articles