Welcome, guest | Sign In | My Account | Store | Cart

Ensure that a name exists in a target namespace. If it does not, make it available in the target namespace using the given definition. The target should be a namespace dictionary (presumably for a module, see the discussion below otherwise). The default target is __builtins__ (specificially, __builtins__.__dict__).

Python, 34 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def EnsureDefinition(name, definition, target=__builtins__.__dict__):
    """
    EnsureDefinition(name, definition, target)

    Ensure that a name exists in the given target namespace (a dictionary). If 
    it does exist, do nothing. If it doesn't, execute the definition in the 
    target.
    """
    print 'Checking for %s in target...' % name,
    if target.has_key(name):
        print 'found.'
    else:
        print 'not found! Defining with %s' % definition
        exec definition in target

EnsureDefinition('False','False = 0')
EnsureDefinition('True','True = not False')
EnsureDefinition('bool','''
def bool(x):
    if x:
        return True
    else:
        return False
'''

# Output for Python version < 2.2.1:
#
# Checking for False in target... not found! Defining with False = 0
# Checking for True in target... not found! Defining with True = not False
# Checking for bool in target... not found! Defining with def bool(x):
#     if x:
#         return True
#     else:
#         return False

This technique is particularly useful where you would normally require a certain version of Python because of some feature that your program needs. Typically, you're only doing so because of one or two particular features (depending on the size of your program of course). This little function helps prevent you from having to do that where simple definitions are concerned. The signature example above is the set of simple definitions for boolean values that are useful for most all programs but non-existent before Python 2.2.1.

It should be noted that if your target is just a dictionary that is not really a namespace (for a module), then you will probably find that it has been filled with all of the names from __builtins__. This is discussed in the Python documentation at http://www.python.org/doc/current/ref/exec.html.

Created by Steven Cummings on Mon, 6 Jan 2003 (PSF)
Python recipes (4591)
Steven Cummings's recipes (2)
Python Cookbook Edition 2 (117)

Required Modules

  • (none specified)

Other Information and Tasks