What is the difference between dir(x) and dir(x.__class__)? The latter returns a different list of attributes, but that overlaps with the former.
For example, SQLAlchemy’s sqlalchemy.create_engine() function creates a new Engine instance. When I call dir(engine) (assuming engine is the var pointing to the appropriate instance) I get the following list returned:
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', '_connection_cls', '_echo',
'_execute_clauseelement', '_execute_compiled', '_execute_default',
'_execution_options', '_has_events', '_run_visitor', '_should_log_debug',
'_should_log_info', 'connect', 'contextual_connect', 'create', 'dialect',
'dispatch', 'dispose', 'driver', 'drop', 'echo', 'engine', 'execute', 'func',
'has_table', 'logger', 'logging_name', 'name', 'pool', 'raw_connection',
'reflecttable', 'run_callable', 'scalar', 'table_names', 'text', 'transaction',
'update_execution_options', 'url']
Calling dir(engine.__class__) results in the following:
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', '_connection_cls',
'_execute_clauseelement', '_execute_compiled', '_execute_default',
'_execution_options', '_has_events', '_run_visitor', '_should_log_debug',
'_should_log_info', 'connect', 'contextual_connect', 'create', 'dispatch',
'dispose', 'driver', 'drop', 'echo', 'execute', 'func', 'has_table',
'logging_name', 'name', 'raw_connection', 'reflecttable', 'run_callable',
'scalar', 'table_names', 'text', 'transaction', 'update_execution_options']
There’s overlap between these two results, but also differences and I haven’t found anything especially useful in the documentation that explains the difference and why.
Roughly,
dir(instance)lists the instance attributes, the class attributes and the attributes of all base classes.dir(instance.__class__)only lists the class attributes, the attributes of all base classes.An important thing to keep in mind when using
dir()is this note from the documentation: