dir()Advanced Examples

Lists the names (attributes and methods) of an object or current scope

dir() protocol implementation

Implementing the protocol that dir() uses under the hood.

python
# dir() - implementing the protocol
class Custom:
    def __dir__(self):
        return "custom result"

obj = Custom()
print(dir(obj))

Understanding the dunder methods that dir() calls helps you customize behavior for your own classes.

Edge cases with dir()

Handling unusual inputs and edge cases.

python
# dir() edge cases
print("Edge case handling for dir()")

# Type checking
print(type(42))

Knowing these edge cases prevents subtle bugs in production.

Want to try these examples interactively?

Open Advanced Playground