Python dir() — A Simple Guide with Video

If used without argument, Python’s built-in dir() function returns the function and variable names defined in the local scope—the namespace of your current module. If used with an object argument, dir(object) returns a list of attribute and method names defined in the object’s scope. Thus, dir() returns all names in a given scope.

Python dir() Visual Explanation

Usage

Learn by example! Here are some examples of how to use the dir() built-in function.

Here’s the use without an argument:

alice = 22
bob = 42
print(dir())

It prints the implicitly and explicitly defined names in your module where you run this code:

['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'alice', 'bob']

The last two values in the list are the names 'alice' and 'bob'.

The following code exemplifies the use of dir() with an object argument of class Car.

class Car:
    speed = 100
    color = 'black'


porsche = Car()
print(dir(porsche))

The class Car has two attributes. If you print the names of the porsche instance of the Car class, you obtain the following output:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'color', 'speed']

The final two attributes are 'color' and 'speed', the ones you defined. There are many other names in the list with the double underscore (called dunder). These are the attribute and method names already defined implicitly by the Python environment for any object. For example, __str__ gives the default string representation of a given object.

Video dir()

Syntax dir()

Syntax: 
dir() -> names defined in the local scope/namespace.  
dir(object) -> names defined for the object. 
ArgumentsobjectThe object for which the names should be returned.
Return ValuelistReturns all names defined in the namespace of the specified object. If no object argument is given, it returns the names defined in the local namespace of the module in which you run the code.

Interactive Shell Exercise: Understanding dir()

Consider the following interactive code:

Exercise: Guess the output before running the code. Do both cars, porsche and tesla, generate the same output?


But before we move on, I’m excited to present you my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners


Using dir() on Modules

You can also use Python’s built-in dir() method on modules. For example, after importing the random module, you can pass it into the dir(random) function. This gives you all the names and functions defined in the module.

import random
print("The random module contains the following names: ")
print(dir(random))

The output is the following:

The random module contains the following names: 
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_itertools', '_log', '_os', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

This way, you can quickly explore the contents of a module and which functions you may want to use in your own code!

Overwriting dir() with __dir__()

To customize the return value of the dir() function on a custom class, you can overwrite the __dir__() method and return the values to be returned. This way, you can hide names from the user or filter out only relevant names of your object.

class Car:
    speed = 100
    color = 'gold'

    def __dir__(self):
        return ['porsche', 'tesla', 'bmw']

tesla = Car()
print(dir(tesla))

The output is the nonsensical list of “names”:

['bmw', 'porsche', 'tesla']

Summary

There are two different use cases for the dir() function.

  • If used without argument, Python’s built-in dir() function returns the function and variable names defined in the local scope—the namespace of your current module.
  • If used with an object argument, dir(object) returns a list of attribute and method names defined in the object’s scope.

Thus, dir() returns all names in a given scope.

Source: Documentation


I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!