PCAP-31-03 practice question 19 of 25

A Python module named pymod.py contains a variable named pyvar. Which of the following snippets will let you access the variable? (Select two answers)

Full set: 147 questions
Answer options
A: import pyvar from pymod pyvar = 1
B: from pymod import pyvar = 1
C: from pymod import pyvar pyvar ()
D: import pymod pymod.pyvar = 1 Correct answer
Correct Answer:
D. import pymod pymod.pyvar = 1
Explanation

A reliable way to reach a variable defined inside another module is to import that module and then refer to the attribute through the module object, e.g. import pymod pymod.pyvar = 1 The statement creates/overwrites the attribute named pyvar inside the already-imported module namespace, hence the variable is accessible. None of the other snippets use syntactically correct import statements.

Why Incorrect

A. “import pyvar from pymod” reverses the required order in the from-import statement—syntax error.
B. Assignment (= 1) cannot appear within a from-import statement—syntax error.
C. Calling pyvar() assumes it is callable; the specification only states it is a variable, so the call may fail.

References

1. Python Language Reference, “import statement” grammar, §8.

2. Python 3.11 Docs, “The import system”, §1 example of attribute access.

Scroll to Top