FAQ
Hi, I need to create a list with a dynamic name, something like this:

'%s_list' %my_dynamic list = []

It's this possible?

Search Discussions

  • Steven D'Aprano at Dec 20, 2010 at 10:32 am

    On Mon, 20 Dec 2010 02:08:57 -0800, MarcoS wrote:

    Hi, I need to create a list with a dynamic name, something like this:

    '%s_list' %my_dynamic list = []

    It's this possible?
    I'm pretty sure you don't *need* to, you just think you do. It is highly
    unlikely that there is anything you can do with such a variable-variable-
    name that you can't do by a more sensible technique.

    But since you ask:

    name = 'variable'
    variable
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'variable' is not defined
    globals()[name] = "this is a bad idea, don't do it"
    variable
    "this is a bad idea, don't do it"


    Here's another way:

    del variable
    exec("%s = 'this is an even worse idea, be careful with this'" % name)
    variable
    'this is an even worse idea, be careful with this'



    Seriously, you probably shouldn't do this. The first is harmful because
    it leads to confusing, complicated, unclear code that is hard to
    maintain; the second is harmful for the same reasons, *plus* it is
    slower, AND could lead to serious security bugs. Google on "code
    injection attack" for more information.



    (There are uses for these techniques, or at least similar techniques, but
    they are rare, fairly advanced, and quite specialised.)

    --
    Steven
  • Andre Alexander Bell at Dec 20, 2010 at 10:33 am
    Hello,
    On 12/20/2010 11:08 AM, MarcoS wrote:
    Hi, I need to create a list with a dynamic name, something like this:

    '%s_list' %my_dynamic list = []

    It's this possible?
    I would suggest you use a dictionary to store your lists like this:

    lists = {}

    lists[my_dynamic_list] = []

    Maybe you tell us some more what you want to achieve...

    Regards


    Andre
  • MarcoS at Dec 20, 2010 at 11:38 am
    Ok, thanks Steven and Andre for yours reply.

    This is my situation:
    I've a list of objects of differents classes, with a common attribute
    name
    Something like this:

    class Object1:
    obj1_name
    .... other fields
    date

    class Object2:
    obj2_name
    .... other fields
    date

    ...

    class ObjectN:
    objN_name
    .... other fields
    date

    the lists are created dynamically at runtime, depending or not if
    there one or more correspondig Objects,
    ex.
    list_object1 = [object1_1, object1_2 ... object1_n]
    ...
    list_objectN = [object2_1, object2_2 ... object2_n]

    Then i need to include all into one global list sorting the various
    objects by date
    ex
    global_list = [object1_1, object2_n, object1_2 ... etc]

    I think that Andre solution it's the best way to solve my dynamics
    lists problem, now I'll
    verify how to create the global list and sort it
  • DevPlayer at Dec 29, 2010 at 4:32 am
    # 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.

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedDec 20, '10 at 10:08a
activeDec 29, '10 at 4:32a
posts5
users4
websitepython.org

People

Translate

site design / logo © 2023 Grokbase