Dynamic list name from a string

DevPlayer devplayer at gmail.com
Tue Dec 28 23:32:31 EST 2010


# dynamic_named_obj.py
# comp.lang.python
# 2010-12 Dec-28
# Topic: Dynamic list name from a string Options
# attempts to answer OP's question
# DevPlayer  - not a solution I'd use


# TO Original Poster OP:

# Start from the bottom OPTION, the one you requested.
# Work your way up and see how it gets simpler and
# simpler to do what you want. Dynamically named
# references start to look pointless.

# I hope I addressed your question and hopefully shown
# you the right direction and right reasons to avoid
# using dynamically made named references.
# But I could be wrong in your case.


import time

class DataStore(object):
    """A namespace similar to a module global scope."""

#def concatenate( one, two):
#    """Function to concatonate two lists."""
#    return list( one + two)

# =========
class Animal(object):
    """A base class for no real reason."""
    def __init__(self, name):
        self.name = name
        self.date = time.clock()

# ---------
class Bear(Animal):
    def __init__(self, name):
        super(Bear, self).__init__(name)

class BearCub(Bear):
    def __init__(self, name):
        super(BearCub, self).__init__(name)

# ---------
class Doe(Animal):
    def __init__(self, name):
        super(Doe, self).__init__(name)

class Fawn(Doe):
    def __init__(self, name):
        super(Fawn, self).__init__(name)


# An alternate namespace instead of module global
ns = DataStore()

OPTION = "BETTER YET"

if OPTION == "BETTER YET":
    # don't name your lists, just make the global_list and use it
    # no intermediary lists needed really.

    ns.Animals = [
        # ---------- 1st set of classes
        Bear("bob"),
        Bear("bill"),
        BearCub("obo"),
        BearCub("Bill jr."),

        # ---------- 2nd set of classes
        Doe("DoeADear"),
        Doe("AFemaleDear"),
        Fawn("Ray"),
        Fawn("Adropof"),
        ]

    for animal in ns.Animals:
        kind = animal.__class__.__name__
        name = animal.name
        date = animal.date
        print kind, name, date

    # make a sorted, by date, list of bears
    old_bears = [obj for obj in ns.Animals if type(obj) is Bear]
    old_bears.sort(None, key=lambda animal: animal.date)
    ns.bears = old_bears

    # or sort all animals by date
    animals = [obj for obj in ns.Animals]
    animals.sort(None, key=lambda animal: animal.date)

    # then get just bears
    bears = [obj for obj in animals if type(obj) is Bear]


elif OPTION == "BETTER":
    # don't name your lists, trust in checking if objects have
attributes
    # that matter

    ns.Animals = {
        # ---------- 1st set of classes
        "bob": Bear("bob"),
        "Bill": Bear("bill"),
        "obo": BearCub("obo"),
        "Bill jr.": BearCub("Bill jr."),

        # ---------- 2nd set of classes
        "DoeADear": Doe("DoeADear"),
        "AFemaleDear": Doe("AFemaleDear"),
        "Ray": Fawn("Ray"),
        "Adropof": Fawn("Adropof"),
        }

    print ns.Animals['bob'].date

    # make a sorted list of objects based on an attribute -like date
    # sort by date for just bears
    # http://wiki.python.org/moin/HowTo/Sorting
    # look at Operator Module Functions too

    # make a sorted, by date, list of bears
    old_bears = [obj for obj in ns.Animals.values() if type(obj) is
Bear]
    old_bears.sort(None, key=lambda animal: animal.date)
    ns.bears = old_bears

    # or sort all animals by date
    animals = [obj for obj in ns.Animals.values()]
    animals.sort(None, key=lambda animal: animal.date)

    # then get just bears
    bears = [obj for obj in animals if type(obj) is Bear]


elif OPTION == "SOSO1":
    # alternative to dynamically named references (object attributes)
    # Each item in global_dict is a sub dict

    ns.Animals = {}
    # ---------- 1st set of classes
    ns.Animals[ Bear ] =  {"bob": Bear("bob"), "Bill": Bear("Bill")}
    ns.Animals[ BearCub ] = {"obo": BearCub("obo"), "Bill jr.":
Bearcub("Bill jr.")}
    # ---------- 2nd set of classes
    ns.Animals[ Doe ] = {"DoeADear": Doe("DoeADear"), "AFemaleDear":
Doe("AFemaleDear")}
    ns.Animals[ Fawn ] = {"Ray": Fawn("Ray"), "Adropof":
Fawn("Adropof")}

    print ns.Animals[Bear]["bob"].date
    print ns.Animals[BearCub]["Bill jr."].date

elif OPTION == "SOSO2":
    # alternative to dynamically named references (object attributes)
    # don't use names at all -
    # Each item in a dict is a list of objects
    # use class itself as key (not class name)

    ns.Animals = {}
    # ---------- 1st set of classes
    ns.Animals[ Bear ] =  [Bear("bob"), Bear("Bill")]
    ns.Animals[ BearCub ] = [BearCub("obo"), Bearcub("Bill jr.")]
    # ---------- 2nd set of classes
    ns.Animals[ Doe ] = [Doe("DoeADear"), Doe("AFemaleDear")]
    ns.Animals[ Fawn ] = [Fawn("Ray"), Fawn("Adropof")]

    print ns.Animals[Bear][0].date

elif OPTION == "SOSO3":
    # alternative to dynamically named references (object attributes)
    # use class __name__ as key

    ns.Animals = {}
    # ---------- 1st set of classes
    ns.Animals[ Bear.__name__ ] =  [Bear("bob"), Bear("Bill")]
    ns.Animals[ BearCub.__name__ ] = [BearCub("obo"), Bearcub("Bill
jr.")]
    # ---------- 2nd set of classes
    ns.Animals[ Doe.__name__ ] = [Doe("DoeADear"), Doe("AFemaleDear")]
    ns.Animals[ Fawn.__name__ ] = [Fawn("Ray"), Fawn("Adropof")]


else: #OPTION LAST

    # What OP was requesting

    # ---------- 1st set of classes
    ref_name = Bear.__name__ + "_list"
    setattr(ns, ref_name,
        {"bob":Bear("bob"), "bill": Bear("Bill")})

    ref_name = BearCub.__name__ + "_list"
    setattr(ns, ref_name,
        {"obo":Bear("obo"), "Bill jr.": Bear("Bill jr.")})


    # ---------- 2nd set of classes
    ref_name = Doe.__name__ + "_list"
    setattr(ns, ref_name,
        {"DoeADear":Bear("DoeADear"), "AFemaleDear":
Bear("AFemaleDear")})

    ref_name = Doe.__name__ + "_list"
    setattr(ns, ref_name,
        {"Ray":Bear("Ray"), "Adropof": Bear("Adropof")})


    # bet that didn't look as appealing as you thought it might
    # Now thing of all the times you'll use those dynamically
    # generated reference names (variables).

    # Do you really need to access "unknown" named references?


    # ----------

    # concatenate all instances of all Animal subclasses into one big
dict
    # ns.globalDict = {item[0]:item[1] for item in ns.__dict__.items()
if "_list" in item[0]}
    # ns.globalDict = {}

    # make a list of lists (where each list contains instances of a
certain class)
    # alist_of_lists = [key for key in ns.__dict__ if "_list" in key]

    # using reduce because OP didn't know how many sub-lists will be
added
    # a = ['one', 'two', 'three',]
    # b = [1, 2, 3]
    # reduce(concatenate, [a, b])
    # ['one', 'two', 'three', 1, 2, 3]


    # poop'd out.



More information about the Python-list mailing list