Binding the names in a module in a class instance

Neal Norwitz nnorwitz at gmail.com
Mon May 23 09:09:39 EDT 2005


Jacob H wrote:
> Hello all,
>
> I would like to be able to take a module full of class instances,
> functions, etc and bind all its names to a separate container class
in
> a different module. I have come up with the following way to do it..

[snip]

> I feel uneasy about this method. I foresee bad namespace clashes.
> What's a better way? :)

Perhaps this is more like what you are looking for:

    import stuff      # stuff we want to copy
    import everything # initially empty module where to store stuff

    # loop over each attribute name in stuff
    for attr in dir(stuff):
        # skip over __special__ attributes, probably don't want them
        if attr.startswith('__') and attr.endswith('__'):
            continue

        value = getattr(stuff, attr)
        setattr(everything, attr, value)

You can add more checking for clashes or whatever by looking at the
attribute name (attr) which is a string.

hth,
n




More information about the Python-list mailing list