On Jul 25, 2012, at 7:26 PM, Stephan Hügel wrote:
>
> # what do I have to do now to end up with instances Abc, Def, Ghi that I can
> query within my app in the same way as Foo?
Let's use the right terminology, you mean "class". Abc, Def, Ghi are classes -
the word "instance" implies you instantiated a class, that is, a "self" that is
associated with that class.
As far as Abc, Def, Ghi being just like Foo - the answer is, they are. In
Python, everything is an object - modules, classes, instances of classes,
names, are all accessible in the same way. Everything is passable as an
argument to anything else, everything can be the value of an attribute
somewhere else. There is no difference between all of these snippets below:
# 1.
class Foo(object):
some_attribute = "some value"
# 2.
Foo = type("Foo", (object,), {"some_attribute":"some_value"})
# 3.
def make_a_foo(somename):
return type(somename, (object,), {"some_attribute":"some_value"})
Foo = make_a_foo("Foo")
so to answer your question, it depends on how you're using this function of
yours. If you have a data array of many anonymous classes, the answer is, "it
depends". You need to access them somehow. If you had this:
my_list_of_classes = make_classes(my_list_of_1000_names)
you've got this use case where you have 1000 names to make into classes. Do
you want to use them by name in a dynamic way ? OK, put them in a dict:
my_dict = dict((c.__name__, c) for c in my_list_of_classes)
session.query(my_dict["SomeName"]).all()
do you want to import them from a module ? OK, then put them in the module:
from myapp import somemodule
for cls in my_list_of_classes:
setattr(somemodule, cls.__name__, cls)
# later
from myapp.somemodule import Cls1234
session.query(Cls1234).all()
In Python, classes are data and names are just ways to access that data, so you
can organize this however you see fit.
>
>
> --
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.