What are python namespaces? Flashcards

(4 cards)

1
Q

general summary

A

Namespaces in Python are mechanisms for managing and organizing the names of defined objects, such as functions, classes, and variables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Key Characteristics

A

Allocations: Namespaces are allocated dynamically and self-contained to manage the objects defined in a particular scope.

Structure: They are structured like dictionaries and are fundamental to Python’s object-oriented nature.

Accessibility: They are not directly accessible and need specific mechanisms like the built-in locals() and globals() functions or the .__dict__ attribute to be viewed or modified.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Types of Namespaces in Python

A

Built-in Namespaces: These contain the names of all built-in functions and exceptions like len() and BaseException. They are always present and don’t need to be imported.

Global Namespaces: These are created when a module is imported or when the Python interpreter starts and persists until the interpreter terminates. It contains names from various modules and any objects created at the top level of a script.

Local or Function-Specific Namespaces: These namespaces are generated when a function is called and discarded when the function terminates. They hold names of local variables, parameters, and any nested functions.

Class-Specific Namespaces: These are created when a class is defined. They store attributes linked with the class and its instances.

Instance-Specific Namespaces: These namespaces store instance attributes and are specific to a particular class object.

Decorator Namespaces: Introduced with decorators, they handle namespace management related to decorators and the objects on which they are defined.

Module-Specific Namespaces: Objects such as the module’s file name, functions, classes, and attributes defined in the module make up a module’s namespace.

Unbound Local Namespace: Introduced in Python 3, this namespace allows for the differentiation between variables that are assigned values within a function vs. those defined on a broader scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Namespace example

A
# Global Namespace
my_global_var = 10

def my_function():
    # Local Namespace
    my_local_var = 20
    print(my_local_var)
    
    # Accessing Global Namespace
    print(my_global_var)

class MyClass:
    # Class Specific Namespace
    class_var = 30

    def \_\_init\_\_(self):
        # Instance Specific Namespace
        self.instance_var = 40

Module Specific Namespace
module_var = 50

Built-in Namespace
print(len("Hello, World!"))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly