Bits N Bytes Banner

MAY 17 2021

Attribute Names dir()


Affiliate Link:

Get Method and Attribute Names with dir()

There is a nice little function in Python named “dir()”. One great feature of this function is that it can produce a list of attributes associated with an object. For example if you want to see the methods on the python pickle object you can do the following:

import pickle dir(pickle)

You can see in the output below all the associated attributes (ie - methods, etc.). This is a great little trick when you are deep in the weeds of your code and need a quick reference. You can also use it to test items to see if a specific method exists.

For example:

if “dump” in dir(pickle): print(“The dump method exists in this object.”)

This is extremely useful if you want to test a dynamic object to determine if a method, or attribute exists.

OUTPUT BELOW:

['ADDITEMS',

'APPEND',

'APPENDS',

'BINBYTES',

'BINBYTES8',

'BINFLOAT',

'BINGET',

'BININT',

'BININT1',

'BININT2',

'BINPERSID',

'BINPUT',

'BINSTRING',

'BINUNICODE',

'BINUNICODE8',

'BUILD',

'BYTEARRAY8',

'DEFAULT_PROTOCOL',

'DICT',

'DUP',

'EMPTY_DICT',

'EMPTY_LIST',

'EMPTY_SET',

'EMPTY_TUPLE',

'EXT1',

'EXT2',

'EXT4',

'FALSE',

'FLOAT',

'FRAME',

'FROZENSET',

'FunctionType',

'GET',

'GLOBAL',

'HIGHEST_PROTOCOL',

'INST',

'INT',

'LIST',

'LONG',

'LONG1',

'LONG4',

'LONG_BINGET',

'LONG_BINPUT',

'MARK',

'MEMOIZE',

'NEWFALSE',

'NEWOBJ',

'NEWOBJ_EX',

'NEWTRUE',

'NEXT_BUFFER',

'NONE',

'OBJ',

'PERSID',

'POP',

'POP_MARK',

'PROTO',

'PUT',

'PickleBuffer',

'PickleError',

'Pickler',

'PicklingError',

'PyStringMap',

'READONLY_BUFFER',

'REDUCE',

'SETITEM',

'SETITEMS',

'SHORT_BINBYTES',

'SHORT_BINSTRING',

'SHORT_BINUNICODE',

'STACK_GLOBAL',

'STOP',

'STRING',

'TRUE',

'TUPLE',

'TUPLE1',

'TUPLE2',

'TUPLE3',

'UNICODE',

'Unpickler',

'UnpicklingError',

'_Framer',

'HAVEPICKLE_BUFFER',

'_Pickler',

'_Stop',

'_Unframer',

'_Unpickler',

'all',

'builtins',

'cached',

'doc',

'file',

'loader',

'name',

'package',

'spec',

'compatpickle',

'_dump',

'_dumps',

'extensioncache',

'extensionregistry',

'_getattribute',

'invertedregistry',

'_load',

'_loads',

'_test',

'_tuplesize2code',

'bytes_types',

'codecs',

'compatible_formats',

'decode_long',

'dispatch_table',

'dump',

'dumps',

'encode_long',

'format_version',

'io',

'islice',

'load',

'loads',

'maxsize',

'pack',

'partial',

're',

'sys',

'unpack',

'whichmodule']