Dynamic list name from a string

M

MarcoS

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

'%s_list' %my_dynamic list = []

It's this possible?
 
S

Steven D'Aprano

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:

Traceback (most recent call last):
File said:
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:

'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.)
 
A

Andre Alexander Bell

Hello,

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
 
M

MarcoS

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
 
D

DevPlayer

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

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top