Dynamically creating properties?

DevPlayer devplayer at gmail.com
Thu Oct 27 19:00:57 EDT 2011


Personally I like to use this function instead of a "try: except:"
because try-except will allow names like __metaclass__.

Remember, setattr(obj, attr_name, value) allows attr_name to be any
valid str().
For example: '!@kdafk11', or '1_1', '1e-20', '0.0', '*one', '\n%%',
etc.

def isvalid_named_reference( astring ):
    # "varible name" is really a named_reference
    # import string   # would be cleaner

    valid_first_char =
'_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    valid_rest =
'_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

    # I think it's ok here for the rare type-check
    # as unicode named-references are not allowed
    if type(astring) is not str: return False

    if len(astring) == 0: return False

    if astring[0] not in valid_first_char: return False

    for c in astring[1:]:
        if c not in valid_rest: return False

    # Python keywords not allowed as named references (variable names)
    for astr in ['and', 'assert', 'break', 'class', 'continue',
                'def', 'del', 'elif', 'else', 'except', 'exec',
                'finally', 'for', 'from', 'global', 'if',
                'import', 'in', 'is', 'lambda', 'not', 'or',
                'pass', 'print', 'raise', 'return', 'try',
                'while', 'yield',]:
        if astring == astr: return False

    # valid names but bad idea
    if astring == '__builtins__': return None
    if astring == '__metaclass__': return None
    for astr in dir(__builtins__):
        if astring == astr: return None # use None as a warning

    # there might be more like __slots__, and other
    # module level effecting special names like '__metaclass__'

    return True

Also when using dynamically created "varible names" to check if your
objects have an attribute with that name already.



More information about the Python-list mailing list