The dir function and packages
In Python, the dir()
function is a built-in function that returns a list of all valid attributes and methods of the object that is passed as its argument.
When called with no arguments, dir()
returns a list of names in the current local scope. If an object is passed as an argument, dir()
returns a list of all valid attributes and methods of that object.
For example, let’s say we have a module named example
with a function named foo
:
# example.py
def foo():
print("Hello, World!")
We can use the dir()
function to list all the attributes and methods available in the example
module:
import example print(dir(example))
Output:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'foo']
Here, we can see that the example
module has attributes such as __name__
, __doc__
, __file__
, etc., as well as the foo
function.
Packages in Python are a way of organizing related modules into a single namespace or directory hierarchy. A package is simply a directory that contains an __init__.py
file, which can be empty or contain initialization code for the package.
For example, let’s say we have a package named mypackage
, which contains two modules: module1
and module2
.
mypackage/ __init__.py module1.py module2.py
We can import the module1
module from the mypackage
package using the following syntax:
import mypackage.module1
We can also use the from ... import
syntax to import specific attributes or functions from a module:
from mypackage.module1 import function1
In this way, packages allow us to organize our code into logical groups, making it easier to manage and reuse.
Apply for Python Certification!
https://www.vskills.in/certification/certified-python-developer