Is there a way in Python to check whether an entry to os.environ is a variable or a shell function?

bash, environment-variables, python, shell

Solution

This feature is bash-specific, so a test for an exported shell function needs to do what Bash does. Experimentation and source code show that Bash recognizes an environment variable as a shell function at startup by the presence of a `() {` prefix in its value — if the prefix is missing, or even slightly altered, the variable is treated as an ordinary data variable.

Therefore, the equivalent Python check would look like this:

def is_env_shell_func(name):
    return os.environ[name].startswith('() {')

Problem

With the `os` module in Python we can easily access environment variables through the dict `os.environ`. However, I found out that `os.environ` does not just hold variables, but also globally defined shell functions (e.g. from the `module` software package). Is it possible from within Python to find out whether a given entry in `os.environ` actually is a function and not a variable? Please note that a shell-agnostic solution is preferred, but I could settle for a Bash-specific solution as well.

Original source

Related problems