Module Namespace Cleanup

I’ve noticed that many open-source Python modules follow the following “sanitization” practice…

"""module

A sample Python module.
"""

from typing import Optional

def printmessage(message: Optional[str] = None):
    """
    Prints a message! If none are provided, a default is used.
    """
    if message:
        print(message)
    else:
        print("Hello, world!")

When users call import module, they have access to the printmessage function, and the Optional variable imported from typing. But we don’t actually need the Optional field after printmessage is defined, since the keyword-arguments are initialized when the function is initialized.

Is there anything wrong with calling del Optional at the end of this module file? I don’t see folks do this very often, but I feel like there are lots of examples (like this short example above) where variables need to be imported into the module namespace, but are only needed on module initialization.

There’s nothing wrong with it, but there’s also not much right with it either. :slight_smile: It’s mostly busywork without a real benefit, but if you really want your namespaces to be tidy, you can do that. I think you’ll get bored quickly.

1 Like

At least in the case of imports only needed for static typing purposes, if you’re using from __future__ import annotations, you can just do:

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from typing import ...
    # Other (non-runtime) typing imports here

Other than that, such cleanup is not usually done, unless there is a specific motivated reasoning for it (e.g. in QtPy, since we’re a compat layer between different Qt versions and API bindings, we do use del on imported module names we don’t want to expose publicly).

You can also use non-from imports and just refer to things by their fully qualified name, which both keeps your externally exposed namespace cleaner, and also can be a bit more explicit within your module itself. And you could do things like using as to import names as private (_) variables, which is again occasionally done if there’s a motivated reason for it, but can also decrease readability and increase potential for confusion inside your module.

1 Like