Reputation: 1157
I need to examine a python module to find simple data as well as "user defined objects". Here, I mean objects (or functions or classes) that are not builtin, but defined with a class/def statement or dynamically loaded/generated.
Note there are similar questions, but they ask about "new style user defined classes". I've seen the inspect
module - I couldn't see how it could help.
I can import a module and 'walk' it, but I don't know an easy way to identify an attribute as a simple type. eg - how do I tell 0. is a builtin type? here:
>>> a=0.
>>> dir(a)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__'...
>>> type(a)
<class 'float'>
Do I have to know the classes of all the standard objects to determine if an attribute of a module/object is "user defined"?
Upvotes: 10
Views: 2214
Reputation: 821
Your question looks for a 2-way option, when in reality it's a 3-way. An object could be:
str
, int
, set
, tuple
, list
, dict
...;pip
;__module __
starts with your package folder name.Here's my limited check for builtins:
is_builtin = lambda obj: obj.__class__.__module__.startswith('builtins')
This is limited because it assumes you will use it on objects and not classes or modules. Your user-defined modules will always report as builtin because they are instances of <class 'type'>
. So, I guess you/I should add a check for being a type and raising something.
And this is how I check that an object is house-made:
is_project = lambda obj: getattr(obj, '__module__', '').startswith('project_folder')
This assumes that your project folder is called project_folder
, of course.
Two notes:
As far as I can see, Python won't put much in way of distinguishing between your own code and library code. For the Snake, it's all about builtin ✕ the World.
Without further ado, here's my library check:
is_library = lambda obj: not (is_project(obj) or is_builtin(obj))
Library is a no man's land, so I test by negative.
Upvotes: 1
Reputation: 1784
Try checking if the types module is builtin, usually works for me.
For example:
a = 1.2
type(a).__module__ == "__builtin__"
Upvotes: 7