Nuh Yamin
Nuh Yamin

Reputation: 353

How to print(dir(module)) using a variable in Python?

import PyQt5
from PyQt5.QtWidgets import *

print(dir(PyQt5.QtWidgets))

That above code runs perfectly. But when I use a variable it gives an error.

qw="QtWidgets"
print(dir(PyQt5.qw))

AttributeError: module 'PyQt5' has no attribute 'qw'. Is there anyway I can do that? The reason I use variable is because I want a user input to choose what modules to print(dir()).

Upvotes: 0

Views: 48

Answers (1)

Alex Taylor
Alex Taylor

Reputation: 8823

The getattr built-in function will let you look up an attribute by name:

qw = "QtWidgets"
print(dir(getattr(PyQt5, qw)))

Upvotes: 1

Related Questions