Binding the names in a module in a class instance

Discussion in 'Python' started by Jacob H, May 23, 2005.

  1. Jacob H

    Jacob H Guest

    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..

    (module "globals")

    class Container:
    pass
    container = Container()

    (module "all_the_stuff")

    ....define a bunch of stuff...

    (module "main")

    exec open("all_the_stuff.py").read() in globals.container.__dict__

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

    Thanks in advance,
    Jacob
     
    Jacob H, May 23, 2005
    #1
    1. Advertising

  2. Jacob H

    Neal Norwitz Guest

    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
     
    Neal Norwitz, May 23, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ares Lagae
    Replies:
    8
    Views:
    460
    Ares Lagae
    Sep 24, 2004
  2. Sridhar R
    Replies:
    14
    Views:
    1,453
    =?iso-8859-1?Q?Fran=E7ois?= Pinard
    Feb 10, 2004
  3. gentlestone
    Replies:
    6
    Views:
    995
    Bruno Desthuilliers
    Oct 6, 2009
  4. Martin P. Hellwig
    Replies:
    1
    Views:
    387
    Martin P. Hellwig
    Mar 26, 2010
  5. Chris Gardner
    Replies:
    5
    Views:
    123
    Rick DeNatale
    Feb 27, 2009
Loading...

Share This Page