Reading Time: 1 minutes
Using dir() in Python
The dir(object) function returns a list of all the methods and associated with the mentioned object. Everything in Python is an object, be it variables, classes, functions etc. The parent data types are also objects, so if you pass 'str' to this function, it will list every method(function) and attribute associated with it. And to gain what all do these related objects do, you can use the builtin help() function.
>>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> help(str.replace) Help on method_descriptor: replace(...) S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
The dir() function without any argument gives you all the objects in the current scope i.e. the variables you have declared after you opened the interpreter.
>>> dir() ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'c', 'coordinates', 'd', 'dimension', 'n', 'newSetOfAnimals', 'primes', 'set2', 'set3', 'setOfAnimals', 't']