locals() — Python Technical Interview Questions & Answers
locals()
locals()
- locals() is built into Python. You do not import it. Freshers only need one honest call and the printed result — not a long definition.
- Output: True. locals() inside f sees x.
- Wrong type often raises TypeError. Empty values matter for bool/all/any. Don’t mix locals up with a similar name (sorted vs sort, int vs float).
Technical Interview Tip: Call locals() once and say what prints.
Code Examples for locals()
Example
# locals()
def f():
x = 1
print("x" in locals())
f()
Output: True. locals() inside f sees x.
How to Explain locals() to an Interviewer
Explain locals() as if you are teaching a junior — definition, then one tiny script.
locals() is built-in — no import. One call + exact output.
What does the example print, and why?
True
What mistake do freshers make with locals()?
Wrong type → TypeError.