registering objects?

Alex Martelli aleax at aleax.it
Mon Jan 7 10:04:24 EST 2002


"Lewis Bergman" <lbergman at abi.tconline.net> wrote in message
news:mailman.1010405828.16971.python-list at python.org...
    ...
> # a List of classes to loop through
> importedClass = [NixUser, icradiusUser]
> for name in importedClass:
>     for method in dir(name):
>     # only register methods that don't start with a "_"
>     if re.match("^[_]", method) is None:
>         server.register_function(name.method)

I would change this to:

importedClasses = [NixUser, icradiusUser]
for a_class in importedClasses:
    for attribute_name in dir(a_class):
        if attribute_name[0] != '_':
            attribute_value = getattr(a_class, attribute_name)
            if callable(attribute_value):
                server.register_function(attribute_value)

Choice of variable names is of course always debatable, but
I would not e.g. call "name" a loop variable that is not a
name at all, but rather a class object.

To check if the first character of a string is not '_', it's
easier to test directly than to use a regular expression.  If
I did want to used a re, I would omit the leading ^ (the match
method matches from the start anyway) and the brackets (as you
are matching just a character, no need to define a set).

The most important modification is the call to builtin function
getattr to get the attribute value from the attribute name.

The further check using built-in function callable ensures
that we do only use methods, not other (data) attributes that a
class might also well possess.


Note that, in Python 2.1, this will not register any methods
that the listed classes may get by inheritance.  In Python 2.2
it will, because dir(someclass) now also returns the names of
inherited attributes.


Alex






More information about the Python-list mailing list