Viewing the names associated with an object

We already know that the built-in function dir returns the set of names associated with an object. For example, if we pass a list as an argument:

a = list([2, 4, 6])
print(dir(a))

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

...we get, among other things, the methods associated with our list: append, clear, copy, etc.

However, the result obtained does not greatly favor the identification of the attributes and methods that we may be looking for, since both private names (those that begin with a double underline) and those marked as "for internal use" (those that begin with an underline) are returned.

To obtain only the set of names that interest us, we could create a function that accepts the name of the object and returns only those names that do not start with an underscore symbol:

def names(obj):
    for n in dir(obj):
        if not n.startswith("_"):
            print(n)

Now, if we execute our function passing the variable "a":

names(a)

append
clear
copy
count
extend
index
insert
pop
remove
reverse
sort

...we get the searched names.

It may be even more practical to create this function using a lambda function and a list comprehension:

names = lambda obj: print([n for n in dir(obj) if not n.startswith("_")])

As can be seen, the function (which we assign to the names variable) receives a single input argument ("obj") and, in the list comprehension, we execute the dir function passing the object in question as an argument and we go through the returned names filtering those that do not start with the underlined character. The final list obtained is printed using the print function obtaining a compact output.

Now, if we pass the variable "a " to our names function:

names(a)

['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

...we get the list of searched names.

Categoría
Submitted by admin on Mon, 01/11/2021 - 15:02