python - Get all user defined classes in a file -
if have file, first.py
, looks -
class person(object): pass class dog(object): pass
and have second file, second.py
. how can classes defined in first.py
in second.py
?
perhaps should mention use-case i'm trying implement similar 1 happens when initializing models in django - when run manage.py sql myapp
command, assume django goes through models in models.py
, generates sql query them.
so i'm trying similar django when takes models defined in models.py
.
how can user defined classes file? (unless there's smarter way django does)
thanks in advance!
if have file first.py, in second.py, have write following code return user-defined classes in first.py:
import first types import * userdefinedclasses = [i in dir(first) if type(getattr(first, i)) typetype]
in simple example, pre-defining first.py, dir(first) return list ['dog', 'person', '__builtins__', '__doc__', '__file__', '__name__', '__package__']
. prune it, have use above compressed loop check type of each object in directory of first.
this return objects in first type "type", practically user-defined classes.
Comments
Post a Comment