Equivalent to the "console.dir ()" function in Python

0

Is there a function in the Python language (v3.6) to display attributes and methods of an object, such as console.dir() in JavaScript?

I'd like to get output similar to console.dir in web browsers. The dir function of Python has a "messy" middle return, where a text denoting an array is returned, which does not tell what method it is and what it is, except that this return is in the same text style, and I I would like each line to contain only one method / attribute, making it easier to understand and not get lost.

Exemplifying: In a scenario where an object manages / represents employees:

Fictitious Attributes and Methods:

  • Resign: method
  • Hire: method
  • Officials: attribute

As the dir function of Python returns:

['demitir', 'contratar', 'funcionarios']

How I would like it to return (more or less):

 {
   'demitir':'function...',
   'contratar':'function...',
   'funcionarios': 20
 }

I'm open to suggestions from third-party libraries / resources. I do not need it to be native, I just need it to work more or less as I described it. Thank you.

    
asked by anonymous 21.11.2017 / 01:11

1 answer

1

So I think what you need is the inspect module. In this module there is the getmembers function that returns a list of name / value pairs of all members of an object. To check what it is, you can map this list to get its name and type.

import inspect

class Foo(object):
    def __init__(self):
        self.x = 1
        self.y = 2

    def method(self):
        pass

foo = Foo()

members = ((name, type(value).__name__) for name, value in inspect.getmembers(foo))

for member in members:
    print(member)

See working at Ideone | Repl.it

The output generated is:

('__class__', 'type')
('__delattr__', 'method-wrapper')
('__dict__', 'dict')
('__dir__', 'builtin_function_or_method')
('__doc__', 'NoneType')
('__eq__', 'method-wrapper')
('__format__', 'builtin_function_or_method')
('__ge__', 'method-wrapper')
('__getattribute__', 'method-wrapper')
('__gt__', 'method-wrapper')
('__hash__', 'method-wrapper')
('__init__', 'method')
('__init_subclass__', 'builtin_function_or_method')
('__le__', 'method-wrapper')
('__lt__', 'method-wrapper')
('__module__', 'str')
('__ne__', 'method-wrapper')
('__new__', 'builtin_function_or_method')
('__reduce__', 'builtin_function_or_method')
('__reduce_ex__', 'builtin_function_or_method')
('__repr__', 'method-wrapper')
('__setattr__', 'method-wrapper')
('__sizeof__', 'builtin_function_or_method')
('__str__', 'method-wrapper')
('__subclasshook__', 'builtin_function_or_method')
('__weakref__', 'NoneType')
('method', 'method')
('x', 'int')
('y', 'int')

Notice that the __init__ and method methods are of type method , indicating that they are methods and the attributes have the respective types, int , str , dict , etc.

    
21.11.2017 / 01:59