Instantiate all objects in a module?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Donald Westfield

    #1

    Instantiate all objects in a module?

    I have my own module, called mystuff.py, which is to be imported for an
    app.

    The number of classes in the module will vary, so I need a subroutine that
    will instantiate all of them as objects, and assign a variable to each,
    regardless of what names the classes are.

    Then I need to be able to delete these objects from memory completely at
    times.

    Can someone recommend a subroutine for this?
  • John Machin

    #2
    Re: Instantiate all objects in a module?

    Donald Westfield wrote:
    I have my own module, called mystuff.py, which is to be imported for an
    app.
    >
    The number of classes in the module will vary, so I need a subroutine that
    will instantiate all of them as objects, and assign a variable to each,
    regardless of what names the classes are.
    Perhaps if you could explain what you mean by "instantiat e all of them
    as objects" .... suppose there are two classes, named Foo and Bar, in
    the module; do you want to class objects (Foo and Bar), or do you want
    one instance of each class (Foo() and Bar())?

    Then what do you mean "assign a variable to each"? Do you mean "bind a
    name to each"?

    Perhaps it would help if you explained what this magic function should
    return, or what effect it should have on the environment, and gave
    examples of what you'd write after invoking the magic, like

    magic_class_gad get(mystuff)
    obj1 = class1()
    obj2 = class2()
    obj3 = ....
    obj1.some_metho d()
    .....

    The big problem is that you don't know until you import the module how
    many classes there are in it ....

    Maybe you need something like this:

    class_list = magic_class_gad get(mystuff)
    obj_list = [cls() for cls in class_list]
    # Note: assumption is that each class's __init__ method has the same
    signature.
    for obj in obj_list:
    obj.some_method ()
    ....
    del obj_list
    del class_list
    del mystuff

    In that case you can get the class_list by doing this:
    import types
    class_list = [v for v in mystuff.__dict_ _.values() if isinstance(v,
    types.TypeType)]

    Alternatively, forget about the implementation details for the moment
    -- come up a level and tell us what you are trying to achieve, what are
    the similarites/differences between the classes, why/how does the
    number vary, ...
    Then I need to be able to delete these objects from memory completely at
    times.
    (a) Why? (b) The del statement is your friend.
    >
    Can someone recommend a subroutine for this?
    It is highly unlikely that there is an existing function to do this.

    HTH,
    John

    Comment

    Working...