tags:

views:

2311

answers:

2
dir(re.compile(pattern))

does not return pattern as one of the lists's elements. Namely it returns:

['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']

According to the manual, it is supposed to contain

the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes.

It says also that

The list is not necessarily complete.

Is there a way to get the complete list? I always assumed that dir returns a complete list but apparently it does not...

Also: is there a way to list only attributes? Or only methods?

Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)

+4  A: 

For the complete list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the getattr built-in function. As the user can reimplement __getattr__ and suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The dir function return the keys in the __dict__ attribute, i.e. all the attributes accessible if the __getattr__ method is not reimplemented.

For the second question, it does not really make sens. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the inspect module determine the class methods, methods or function.

PierreBdR
inpect.getmembers(re.compile(pattern)) does not yield pattern as a member either, so it probably uses dir internally... This sucks!
Bartosz Radaczyński
I could also use callable to check if they are methods, but that is not the point... The point is I cannot trust dir to return even the list of attributes that are actually publicly visible...
Bartosz Radaczyński
inspect is meant to be "at least as" trustworthy as dir().on the other hand, re is a very complicated module
hop
What do you define by "publicly visible" ? If you mean "can be accessed", then that is a lost cause for the reason given. Otherwise, 'dir' always return the list of attributes accessible with the default implementation of getattr.
PierreBdR
Well, take a look at the other answer. There is some notion of public visibility in ppython, hence the __dir__ in order for the objects to control what is returned. Still, I came across this cause I use dir in the interactive shell like *all the time* :D. Anyway, thans.
Bartosz Radaczyński
+3  A: 

That is why the new __dir__() method has been added in python 2.6

see:

Moe