Reputation:
I need help understanding a practice exam problem for a CS class in python. The problem deals with the python namespace. Here is the question:
Which of the following are true in Python?
i. Every function has access to the names in the builtin namespace.
ii. Every invocation of a function creates a new namespace nested within the calling function’s namespace.
iii. Invoking function G from function F adds the name G to F’s namespace
iv. The namespace of an imported module is always added to the builtin namespace.
a. i only
b. ii and iii only
c. i and iv only (answer)
d. i, ii and iii only
e. None of the above
Can someone please explain why the second and third cases are false. Or point me to some resources that explain the namespace. Thank-you.
Upvotes: 0
Views: 341
Reputation: 715
For 2: The new function's namespace isn't within the calling function's namespace: it's completely separate. An inner function has no access to the variables used in the outer one. The invocation makes a new namespace, but it's not nested within that of the calling function.
I didn't know 3, but it makes sense. The function is invoked and the name isn't added to the namespace because it's unnecessary. It's not added to the function namespace because it's already in the global namespace (or a class definition) and the function can normally be assumed to have appropriate access to it as needed. And the reference would be useless once the function returned, so there's no point in adding it to the namespace in the first place.
Namespace is essentially a matter of who can see what. So a piece of code only knows definitions for things in the namespaces it has access to. A function has access to its own personal namespace (other functions can't see this) and the global scope/namespace (everything can see this). Think of it like file directories on your computer. You can have two files that are named the same as long as they're in different directories, and namespaces are handy for most of the same reasons that directories are. Namespaces help force you to organize your code and keep it more modular instead of making hugely intricate dependencies between distant areas of code, and typically saves you from having to keep track of all variable names across potentially millions of lines of code.
Upvotes: 1