effbiae
effbiae

Reputation: 1157

How to check if a python class or object is user defined (not a builtin)?

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

Answers (2)

Ricardo
Ricardo

Reputation: 821

Intro

Your question looks for a 2-way option, when in reality it's a 3-way. An object could be:

  • builtin: part of the core language, such as str, int, set, tuple, list, dict...;
  • library: part of the things you happily install with pip;
  • user-defined: things whose __module __ starts with your package folder name.

Action

Built-in

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.

User-defined

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.

"Pipable" library

Two notes:

  1. I literally just made up the word "pipable". It's mine and I demand credit for using it.
  2. Seriously, though: where is the check for library, then?

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

maor10
maor10

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

Related Questions