How to build Hierarchies of dict's? (Prototypes in Python?)
I'm sure I've read before about how to construct prototypes in Python, but I haven't been able to track it down (or figure it out). What I basically want is a kind of class that has both class and instance level dict variables, such that descendant classes automatically create their own class and instance level dict variables. The idea is that if a member of this hierarchy looks up something in it's local dict, and doesn't find it, it then looks in the class dict, and if not there it looks in its ancestral dict's. This is rather like what Python does at compile time, but I want to do it at run time. I'm sure I've seen how to do it...but have no idea where, or what it was called, or when (probably around the time Prothon was being discussed, as I have the idea of prototype associated with it for no clear reason). -- http://mail.python.org/mailman/listinfo/python-list
Re: How to build Hierarchies of dict's? (Prototypes in Python?)
Gabriel Genellina wrote: >> En Fri, 23 Feb 2007 17:53:59 -0300, Charles D Hixson >> <[EMAIL PROTECTED]> escribió: >> >> >>> I'm sure I've read before about how to construct prototypes in Python, >>> but I haven't been able to track it down (or figure it out). >>> >>> What I basically want is a kind of class that has both class and >>> instance level dict variables, such that descendant classes >>> automatically create their own class and instance level dict variables. >>> The idea is that if a member of this hierarchy looks up something in >>> it's local dict, and doesn't find it, it then looks in the class dict, >>> and if not there it looks in its ancestral dict's. This is rather like >>> what Python does at compile time, but I want to do it at run time. >>> >> >> Well, the only thing on this regard that Python does at compile time, >> is to determine whether a variable is local or not. Actual name >> lookup is done at runtime. >> You can use instances and classes as dictionaries they way you >> describe. Use getattr/setattr/hasattr/delattr: >> >> py> class A: >> ... x = 0 >> ... y = 1 >> ... >> py> class B(A): >> ... y = 2 >> ... >> py> a = A() >> py> setattr(a, 'y', 3) # same as a.y = 3 but 'y' may be a variable >> py> print 'a=',vars(a) >> a= {'y': 3} >> py> >> py> b = B() >> py> print 'b=',vars(b) >> b= {} >> py> setattr(b,'z',1000) >> py> print 'b=',vars(b) >> b= {'z': 1000} >> py> print 'x?', hasattr(b,'x') >> x? True >> py> print 'w?', hasattr(b,'w')? False > The trouble is, I'd want to be adding variables at run time. At > least, I *think* that's a problem. Perhaps I'm misunderstanding what > Python's capabilities already are. How would one write a member > function to add a variable to a class? > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: How to build Hierarchies of dict's? (Prototypes in Python?)
Larry Bates wrote: > Charles D Hixson wrote: > >> I'm sure I've read before about how to construct prototypes in Python, >> but I haven't been able to track it down (or figure it out). >> >> What I basically want is a kind of class that has both class and >> instance level dict variables, such that descendant classes >> automatically create their own class and instance level dict variables. >> The idea is that if a member of this hierarchy looks up something in >> it's local dict, and doesn't find it, it then looks in the class dict, >> and if not there it looks in its ancestral dict's. This is rather like >> what Python does at compile time, but I want to do it at run time. >> >> I'm sure I've seen how to do it...but have no idea where, or what it was >> called, or when (probably around the time Prothon was being discussed, >> as I have the idea of prototype associated with it for no clear reason). >> > > What you describe is exactly how Zope works so you might want to spend > some time looking at it. > > http://www.zope.org > > -Larry > Thanks for the suggestion, and I'll do that if I must, but Zope is pretty heavy to drag into something for just one function, and I don't really see any use for most parts of it in what I'm doing. And that's a LOT of code to wade through for one technique. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to build Hierarchies of dict's? (Prototypes in Python?)
Toby wrote: > Charles D Hixson wrote: > >> What I basically want is a kind of class that has both class and >> instance level dict variables, such that descendant classes >> automatically create their own class and instance level dict variables. >> The idea is that if a member of this hierarchy looks up something in >> it's local dict, and doesn't find it, it then looks in the class dict, >> and if not there it looks in its ancestral dict's. This is rather like >> what Python does at compile time, but I want to do it at run time. >> > > I don't understand, Python already does it at runtime: > > class A: > A_class_var = 1 > > class B(A): > B_class_var = 2 > def __init__(self): > self.B_inst_var = 3 > > >>>> b.A_class_var >>>> > 1 > >>>> b.B_class_var >>>> > 2 > >>>> b.B_inst_var >>>> > 3 > >>>> A.another = 4 >>>> b.another >>>> > 4 > > Can you post a ">>>"-script of what you would like your classes to do? > > > Toby > Sorry, the "script" hasn't been written. But Python apparently *won't* (automatically) do what I want, which is create a class whose sub-classes automatically have unique class variables of a determined form such that I can do a hierarchical search through them. (I could plausibly handle this for the instance case but "class variables are static", so it looks like I can't do it for class variables in a straightforward manner. This looks like it's going to demand a factory method, or some alternate approach. (Not sure yet which I'll choose.) What I'm looking for is a reasonable way to implement what Marvin Minsky calls Panologies. These are "objects" (my term) with sufficient local intelligence to try alternative models of a situation until they find one that's appropriate. E.g., is this being operated on as a physical transaction or a social transaction. (Yes, it is physically happening, and it's taking place in physical space, but different models yield different analyses of what's happening. Which is appropriate for the situation currently being evaluated?) Well, I'm not trying to handle all that, merely to create a simple model of what a panology *IS*. So each Panology object will need a list of delegatees to handle the operations, and a list of indexes to assist it in evaluating which delegatee to use. If it doesn't find it locally, it will need to search through the situational context and these should be maintained at both the class and instance levels by it's ancestors. The base class should have a method that manages the searching, and the finding of delegatees (models) based around the indexing keys. This will take a bit of work, but if I can manage it, it should be rather interesting. It could also be used to test some of Minsky's ideas...or not, because what I'm thinking of it different from exactly what he's proposing. E.g., after I figure out how to build the basic structure, I'm going to need to figure out how to determine the appropriate model. This may be a harder problem. P.S.: What I really expect is that by the time I get this solved, somebody else will already have a solution. (It's happened before. I had the "idea" of an "intelligent spam filter" before spambayes was built...but I was much too slow at the implementation. MUCH! (I spend too much time dreaming and not enough time programming.) P.P.S.: This isn't all loss. I'm expecting that eventually I'll start running into performance problems, and at that point it would be necessary to start translating into a native-compiler language. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to build Hierarchies of dict's? (Prototypes in Python?)
Toby wrote: > Charles D Hixson wrote: > >> a class whose sub-classes automatically have unique class variables of >> a determined form such that I can do a hierarchical search through them >> > > Something like this? > (scroll down to see the results) > > > # --- begin --- > > class AttrSearch(object): > @classmethod > def getclassattrset(cls, name): > s = set() > if name in cls.__dict__: > s.add((cls.__name__, cls.__dict__[name])) > for base in cls.__bases__: > try: > s.update(base.getclassattrset(name)) > except AttributeError: > pass > return s > > def getattrset(self, name): > s = set() > try: > s.add((None, self.__dict__[name])) > except KeyError: > pass > s.update(self.__class__.getclassattrset(name)) > return s > > def __getattribute__(self, name): > if name.startswith('__'): #XXX not pretty > return object.__getattribute__(self, name) > found = AttrSearch.getattrset(self, name) > print 'Looking for "%s" in a %s instance, found %d candidates:' \ > % (name, self.__class__.__name__, len(found)) > print '\n'.join([ ' %-4s %s' % x for x in found ]) > print '(now choose wisely what to return)' > > class A(AttrSearch): > a = 1 > > class B(A): > a = 2 > > class C(A): > a = 3 > > class D(B, C): > a = 4 > > > D().a > > # --- end --- > > > Results: > > Looking for "a" in a D instance, found 4 candidates: > A1 > B2 > C3 > D4 > (now choose wisely what to return) > > > Toby > Yes, thank you. (I'd come up with a kludge, but this is much nicer.) -- http://mail.python.org/mailman/listinfo/python-list
Iterators: Would "rewind" be a good idea?
I was reading through old messages in the list and came up against an idea that I thought might be of some value: "Wouldn't it be a good idea if one could "rewind" an iterator?" Not stated in precisely those terms, perhaps, but that's the way I read it. I appreciate that one could use a sequence rather than an iterator, and that I don't understand the implementation issues. (They don't look large, but what to I know?) But would it be a good idea to have a rewind method for iterators? I tend to think of them as mag tapes, and I was always wanting to rewind those. Or skip to file n. (Well, that probably doesn't have any relevance to the usage of iterators.) OTOH, if this is a bother, it's almost always quite easy to create a new iterator, it just feels less efficient. Still, I would use this much more often that I would use reversed (which I've never wanted to use). -- http://mail.python.org/mailman/listinfo/python-list
class level properties
I'm trying to construct read-only variables at the class level. I've been unsuccessful. Any suggestions? Mixing @classmethod and @property doesn't appear to produce workable code. Ditto for mixing @classmethod and __getattr__. (The property approach compiles, but execution says that you can't execute properties.) I've got a rather large number of variables, so I don't want to define function accessors for each of them, and I *REALLY* don't want to have to access them as functions rather than variables or properties. -- http://mail.python.org/mailman/listinfo/python-list
Re: class level properties
Arnaud Delobelle wrote: > On Apr 12, 8:36 pm, Charles D Hixson <[EMAIL PROTECTED]> > wrote: > >> I'm trying to construct read-only variables at the class level. I've >> been unsuccessful. Any suggestions? >> >> Mixing @classmethod and @property doesn't appear to produce workable >> code. Ditto for mixing @classmethod and __getattr__. (The property >> approach compiles, but execution says that you can't execute properties.) >> >> I've got a rather large number of variables, so I don't want to define >> function accessors for each of them, and I *REALLY* don't want to have >> to access them as functions rather than variables or properties. >> > > Metaclasses, of course! > > >>>> class MetaX(type): >>>> > ... @property > ... def spam(self): return 'eggs' > ... > >>>> class X(object): >>>> > ... __metaclass__ = MetaX > ... > >>>> X.spam >>>> > 'eggs' > > > HTH > > -- > Arnau Thanks. I can make that work. Is it possible to move the entire implementation of the interpretation of _valueMap, below, into properties in some similar way? I'm referring to the part managed by __getattr__ below. I want a hundred or so read-only variables, and I'm not sure the best way to achieve it. classMetaROVars(type): @property defsimple(self): return"simple example working" class test(object): __metaclass__=MetaROVars _valueMap={ "t1": (3,"Concept decay rate", "[1, 99]"), "t2":(10,"TaskLink decay rate", "[1, 99]"), } [EMAIL PROTECTED] def__getattr__(self, name): ifname not in test._valueMap: raise AttributeError, name returntest._valueMap[name][0] defdescribe(self, name): ifname not in test._valueMap: raise AttributeError, name returntest._valueMap[name][1] + ", lying in the range " + test._valueMap[name][2] p=test() printp.t1 printp.describe("t1") printp.t2 printtest.simple -- http://mail.python.org/mailman/listinfo/python-list
Re: class level properties
Peter Otten wrote: > Charles D Hixson wrote: > > >> I want a hundred or so read-only variables, and I'm not sure the best >> way to achieve it. >> > > What do you really want to do? I recommend that you forget about bondage and > rely upon displine: > > class Test(object): > """Never change an attribute with an uppercase name.""" > SIMPLE = "simple example working" > > Now that was easy... > > Peter > > What I'm doing it translating Java code which has a large number of "public static final (type)" variables. As to your answer ... yes, and with good discipline you can write object oriented code in C and never need a garbage collector. It's *not* a good answer. Before I'd chose that one, I'd make it necessary to instantiate the class before testing the value of it's constants. It's just that that seems to be a silly requirement, so I'd like to avoid it. (That's the "solution" that I currently have working with __getattr__.) -- http://mail.python.org/mailman/listinfo/python-list