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.
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
The following code exemplifies the use of
dir() with an object argument of class
class Car: speed = 100 color = 'black' porsche = Car() print(dir(porsche))
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
'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.
dir() -> names defined in the local scope/namespace. dir(object) -> names defined for the object.
|Arguments||The object for which the names should be returned.|
|Return Value||Returns 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,
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).
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']
There are two different use cases for the
- 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.
dir() returns all names in a given scope.
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!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. 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?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming 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.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.