{"id":122714,"date":"2021-01-01T10:56:03","date_gmt":"2021-01-01T10:56:03","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=19945"},"modified":"2021-01-01T10:56:03","modified_gmt":"2021-01-01T10:56:03","slug":"python-dir-a-simple-guide-with-video","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2021\/01\/01\/python-dir-a-simple-guide-with-video\/","title":{"rendered":"Python dir() \u2014 A Simple Guide with Video"},"content":{"rendered":"<p class=\"has-pale-cyan-blue-background-color has-background\">If used <strong><em>without argument<\/em><\/strong>, Python&#8217;s built-in <code>dir()<\/code> function returns the function and variable <strong><em>names defined in the local scope<\/em><\/strong>&#8212;the namespace of your current module. If used <strong><em>with an object argument<\/em><\/strong>, <code>dir(object)<\/code> returns a list of attribute and method <em><strong>names defined in the object&#8217;s scope<\/strong><\/em>. Thus, <code>dir()<\/code> returns all names in a given scope. <\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"576\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2021\/01\/dir-1024x576.jpg\" alt=\"Python dir() Visual Explanation\" class=\"wp-image-19981\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2021\/01\/dir-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2021\/01\/dir-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2021\/01\/dir-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2021\/01\/dir-150x84.jpg 150w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<h2>Usage<\/h2>\n<p>Learn by example! Here are some examples of how to use the <code>dir()<\/code> <a href=\"https:\/\/blog.finxter.com\/python-built-in-functions\/\" title=\"Python Built-In Functions\">built-in function<\/a>. <\/p>\n<p>Here&#8217;s the use <strong><em>without an argument<\/em><\/strong>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">alice = 22\nbob = 42\nprint(dir())\n<\/pre>\n<p>It prints the implicitly and explicitly defined names in your module where you run this code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'alice', 'bob']<\/pre>\n<p>The last two values in the list are the names <code>'alice'<\/code> and <code>'bob'<\/code>. <\/p>\n<p>The following code exemplifies the use of <code>dir()<\/code><strong><em> with an object argument<\/em><\/strong> of <a href=\"https:\/\/blog.finxter.com\/a-simple-example-for-python-objects-and-classes-video\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"A Simple Example for Python Objects and Classes [+Video]\">class <\/a><code>Car<\/code>. <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Car: speed = 100 color = 'black' porsche = Car()\nprint(dir(porsche))\n<\/pre>\n<p>The class <code>Car<\/code> has two <a href=\"https:\/\/blog.finxter.com\/python-attributes\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Class and Instance Attributes in Python \u2014 Every Coder Must Know the Difference! [+Video Guide]\">attributes<\/a>. If you print the names of the <code>porsche<\/code> instance of the <code>Car<\/code> class, you obtain the following output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">['__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']<\/pre>\n<p>The final two attributes are <code>'color'<\/code> and <code>'speed'<\/code>, the ones you defined. There are many other names in the <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" title=\"The Ultimate Guide to Python Lists\">list <\/a>with the<a href=\"https:\/\/blog.finxter.com\/underscore-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"The Single and Double Underscore in Python [\u201c_\u201d vs \u201c__\u201d]\"> double underscore<\/a> (called <strong><em>dunder<\/em><\/strong>). These are the attribute and method names already defined implicitly by the <a href=\"https:\/\/python.org\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/python.org\/\">Python environment<\/a> for any object. For example, <a href=\"https:\/\/blog.finxter.com\/how-to-convert-a-string-representation-of-a-dictionary-to-a-dictionary\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Convert a String Representation of a Dictionary to a Dictionary?\"><code>__str__<\/code> gives the default string representation<\/a> of a given object. <\/p>\n<h2>Video dir()<\/h2>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"Python dir() \u2014 A Simple Guide with Video\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/DZyICkSIPRI?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<h2>Syntax dir()<\/h2>\n<pre class=\"wp-block-preformatted\"><strong>Syntax: <\/strong>\n<code>dir() -> names defined in the local scope\/namespace. dir(object) -> names defined for the object. <\/code><\/pre>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><strong>Arguments<\/strong><\/td>\n<td><code>object<\/code><\/td>\n<td>The object for which the names should be returned.<\/td>\n<\/tr>\n<tr>\n<td><strong>Return Value<\/strong><\/td>\n<td><code>list<\/code><\/td>\n<td>Returns all names defined in the namespace of the specified object. If no object argument is given, it returns the names defined in the <a href=\"https:\/\/blog.finxter.com\/python-namespaces-made-simple\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Namespaces Made Simple \u2014 With Harry Potter Examples\">local namespace<\/a> of the module in which you run the code. <\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<h2>Interactive Shell Exercise: Understanding dir()<\/h2>\n<p>Consider the following interactive code:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/672bc93879\" width=\"100%\" height=\"356\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: <\/em>Guess the output before running the code. Do both cars, <code>porsche<\/code> and <code>tesla<\/code>, generate the same output?<\/p>\n<hr class=\"wp-block-separator\"\/>\n<p><strong>But before we move on, I&#8217;m excited to present you my brand-new Python book <a rel=\"noreferrer noopener\" href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" title=\"https:\/\/amzn.to\/2WAYeJE\">Python One-Liners<\/a><\/strong> (Amazon Link).<\/p>\n<p>If you like one-liners, you&#8217;ll LOVE the book. It&#8217;ll teach you everything there is to know about a <strong>single line of Python code.<\/strong> But it&#8217;s also an <strong>introduction to computer science<\/strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!<\/em><\/strong><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noopener noreferrer\"><img decoding=\"async\" loading=\"lazy\" width=\"215\" height=\"283\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/02\/image-1.png\" alt=\"\" class=\"wp-image-5969\"\/><\/a><\/figure>\n<\/div>\n<p>The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). <\/p>\n<p>Link: <a href=\"https:\/\/nostarch.com\/pythononeliners\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/nostarch.com\/pythononeliners<\/a><\/p>\n<hr class=\"wp-block-separator\"\/>\n<h2>Using dir() on Modules<\/h2>\n<p>You can also use Python&#8217;s built-in <code>dir()<\/code> method on modules. For example, after importing the <a href=\"https:\/\/blog.finxter.com\/python-random-module\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python\u2019s Random Module \u2013 Everything You Need to Know to Get Started\">random module<\/a>, you can pass it into the <code>dir(random)<\/code> function. This gives you all the names and functions defined in the module. <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import random\nprint(\"The random module contains the following names: \")\nprint(dir(random))<\/pre>\n<p>The output is the following:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">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']<\/pre>\n<p>This way, you can quickly explore the contents of a module and which functions you may want to use in your own code!<\/p>\n<h2>Overwriting dir() with __dir__()<\/h2>\n<p>To customize the return value of the <code>dir()<\/code> function on a custom class, you can overwrite the <code>__dir__()<\/code> 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. <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Car: speed = 100 color = 'gold' def __dir__(self): return ['porsche', 'tesla', 'bmw'] tesla = Car()\nprint(dir(tesla))\n<\/pre>\n<p>The output is the nonsensical list of &#8220;names&#8221;:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">['bmw', 'porsche', 'tesla']<\/pre>\n<h2>Summary<\/h2>\n<p>There are two different use cases for the <code>dir()<\/code> function. <\/p>\n<ul>\n<li>If used <strong><em>without argument<\/em><\/strong>, Python&#8217;s built-in <code>dir()<\/code> function returns the function and variable <strong><em>names defined in the local scope<\/em><\/strong>&#8212;the namespace of your current module. <\/li>\n<li>If used <strong><em>with an object argument<\/em><\/strong>, <code>dir(object)<\/code> returns a list of attribute and method <em><strong>names defined in the object&#8217;s scope<\/strong><\/em>. <\/li>\n<\/ul>\n<p>Thus, <code>dir()<\/code> returns all names in a given scope.<\/p>\n<p><strong>Source<\/strong>: <a href=\"https:\/\/docs.python.org\/3\/library\/functions.html#dir\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/docs.python.org\/3\/library\/functions.html#dir\">Documentation<\/a><\/p>\n<hr class=\"wp-block-separator\"\/>\n<p>I hope you enjoyed the article! To improve your Python education, you may want to join the popular free <a href=\"https:\/\/blog.finxter.com\/email-academy\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Email Academy\">Finxter Email Academy<\/a>:<\/p>\n<p>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!<\/p>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?<\/p>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n<\/p>\n<\/p>\n<p>The post <a href=\"https:\/\/blog.finxter.com\/python-dir-a-simple-guide-with-video\/\">Python dir() \u2014 A Simple Guide with Video<\/a> first appeared on <a href=\"https:\/\/blog.finxter.com\">Finxter<\/a>. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>If used without argument, Python&#8217;s built-in dir() function returns the function and variable names defined in the local scope&#8212;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&#8217;s scope. Thus, dir() returns all names in a given scope. Usage Learn [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-122714","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/122714","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=122714"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/122714\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=122714"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=122714"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=122714"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}