Good idea to use a class as function with __new__?
Hi, I am implementing som code generation and want to to use some variant of the template method pattern. What I came up with is to have a class with the common part in a method and the subclasses can then override the Customize methods to do their own special part. Now to the question I use the __new__ to return the result instead of the instance. So that the class is used as an function. So insted of having. a = Template() result = a.__TemplateMethod(preifix="foo") I can write: result = Template(prefix="foo") class Template(object): def __init__(cls, *args, **kwds): pass def __new__(cls, *args, **kwds): obj = super(Template, cls).__new__(cls, *args, **kwds) return obj.__TemplateMethod(*args, **kwds) def Customize1(self, prefix="hello", *args, **kwds): return prefix+"1\n" def Customize2(self, prefix="hello", *args, **kwds): return prefix+"2\n" def __TemplateMethod(self, *args, **kwds): result = "" result += self.Customize1(*args, **kwds) result += self.Customize1(*args, **kwds) return result b = Template("foo") print b -- http://mail.python.org/mailman/listinfo/python-list
Re: Good idea to use a class as function with __new__?
Gabriel Genellina wrote: > def __call__(self, *args, **kwds): > return self.__TemplateMethod(*args, **kwds) > > x = Template()(prefix="foo") > or perhaps: > x = Template(prefix="foo")() > > I think the extra () improves readability - it's clear that x comes from a > function call, it's not a Template instance as one would expect from your > original code. > And depending on the application, you could keep the instances and call > them with different arguments - with the original code you always create a > new instance just to discard it immediately. > > -- Thanks for the reply. I was considering __call__ but in my case it is really something that will be discarded immediately. And right now it is is implemented as function where I have arguments to send in which customize functions something like: def Template(self, func1=Customize1, func2= Customize2, *args, **kwds): func1(*args, **kwds) func2(*args, **kwds) So I just wanted to organize it a little bit nicer and be able to subclass instead of sending in function pointers. But that had the same interface. But you are right the extra () does make it clearer, so I probably go for that. Cheers, /T > Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
How to set a class inheritance at instance creation?
Hi I wonder if you can set what subclass a class should have at instance creation. The problem is that I have something like: class CoreLang(): def AssignVar(self, var, value): pass class Lang1(CoreLang): def AssignVar(self, var, value): return var, "=", value class Lang2(CoreLang): def AssignVar(self, var, value): return var, "<=", value class WriteStruct(): def Generate(self, vars): for var in vars: print self.AssignVar() The problem is that I want WriteStruct to sometimes be a subclass of Lang1 and sometimes of Lang2. In the above example I could but the Generate Method in CoreLang. But in my real example I also want to able to subclass WriteStruct to be able to easy customize WriteStruct. Which I wouldnt be able to do if it was a method in CoreLang. So in code I would like to write something like: WriteStruct(Lang1).Generate(vars) Even better would be that if I in the Lang1 class could just do WriteStruct().Generate(vars) and Lang1 class would magically make WriteStruct a subclass of itself. Cheers, /T -- http://mail.python.org/mailman/listinfo/python-list
Re: How to set a class inheritance at instance creation?
On 29 Maj, 19:27, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > Why not just have Lang1 and Lang2 inherit from WriteStruct as well? This wont work I think since if add antoher Class: class WriteStruct(): def func1(self); print "Hello2" def Generate(self): self.func1() class WriteStruct2(WriteStruct): def func1(self); print "Hello" def Generate(self): self.func1() Den if Lang1, inherit both WriteStruct and WriteStruct2 I will get name clashes. In my real code I have very big Generate Method in WriteStruct that calls submethods. and thes submethods should be overriden by the subclasses. So I cant change the name on the submethods. > > On May 29, 8:52 am, glomde <[EMAIL PROTECTED]> wrote: > > > Hi I wonder if you can set what subclass a class should > > have at instance creation. > > > The problem is that I have something like: > > > class CoreLang(): > > def AssignVar(self, var, value): > > pass > > > class Lang1(CoreLang): > > def AssignVar(self, var, value): > > return var, "=", value > > > class Lang2(CoreLang): > > def AssignVar(self, var, value): > > return var, "<=", value > > > class WriteStruct(): > > def Generate(self, vars): > > for var in vars: > > print self.AssignVar() > > > The problem is that I want WriteStruct to sometimes be a subclass of > > Lang1 and sometimes > > of Lang2. > > In the above example I could but the Generate Method in CoreLang. But > > in my real > > example I also want to able to subclass WriteStruct to be able to easy > > customize WriteStruct. > > Which I wouldnt be able to do if it was a method in CoreLang. > > > So in code I would like to write something like: > > > WriteStruct(Lang1).Generate(vars) > > > Even better would be that if I in the Lang1 class could > > just do WriteStruct().Generate(vars) and Lang1 class would > > magically make WriteStruct a subclass of itself. > > > Cheers, > > > /T -- http://mail.python.org/mailman/listinfo/python-list
Re: How to set a class inheritance at instance creation?
On 29 Maj, 19:20, Ramashish Baranwal <[EMAIL PROTECTED]> wrote: > On May 29, 8:52 pm, glomde <[EMAIL PROTECTED]> wrote: > > > > > Hi I wonder if you can set what subclass a class should > > have at instance creation. > > > The problem is that I have something like: > > > class CoreLang(): > > def AssignVar(self, var, value): > > pass > > > class Lang1(CoreLang): > > def AssignVar(self, var, value): > > return var, "=", value > > > class Lang2(CoreLang): > > def AssignVar(self, var, value): > > return var, "<=", value > > > class WriteStruct(): > > def Generate(self, vars): > > for var in vars: > > print self.AssignVar() > > > The problem is that I want WriteStruct to sometimes be a subclass of > > Lang1 and sometimes > > of Lang2. > > In the above example I could but the Generate Method in CoreLang. But > > in my real > > example I also want to able to subclass WriteStruct to be able to easy > > customize WriteStruct. > > Which I wouldnt be able to do if it was a method in CoreLang. > > > So in code I would like to write something like: > > > WriteStruct(Lang1).Generate(vars) > > class WriteStruct: > def __init__(self, SubClass): > self._sub = SubClass() > def Generate(self, vars): > for var in vars: > print self._sub.AssignVar() > > This does what you want but isn't inheritance. This would work I think. Thanks. > > > Even better would be that if I in the Lang1 class could > > just do WriteStruct().Generate(vars) and Lang1 class would > > magically make WriteStruct a subclass of itself. > > I don't think I understood what you want here. > I just dont want to pass the class in the instancecreation. Somhehow in my: class Lang1(CoreLang): def Function(self): WriteStruct().Generate() Then somehow this WriteStruct should magically know that has been instantiated in Lang1. But this is not really needed. Just wondered if it was possible. > Ram -- http://mail.python.org/mailman/listinfo/python-list
Re: How to set a class inheritance at instance creation?
On 29 Maj, 22:45, Steve Holden <[EMAIL PROTECTED]> wrote: > glomde wrote: > > Hi I wonder if you can set what subclass a class should > > have at instance creation. > > > The problem is that I have something like: > > > class CoreLang(): > > def AssignVar(self, var, value): > > pass > > > class Lang1(CoreLang): > > def AssignVar(self, var, value): > > return var, "=", value > > > class Lang2(CoreLang): > > def AssignVar(self, var, value): > > return var, "<=", value > > > class WriteStruct(): > > def Generate(self, vars): > > for var in vars: > > print self.AssignVar() > > > The problem is that I want WriteStruct to sometimes be a subclass of > > Lang1 and sometimes > > of Lang2. > > In the above example I could but the Generate Method in CoreLang. But > > in my real > > example I also want to able to subclass WriteStruct to be able to easy > > customize WriteStruct. > > Which I wouldnt be able to do if it was a method in CoreLang. > > > So in code I would like to write something like: > > > WriteStruct(Lang1).Generate(vars) > > > Even better would be that if I in the Lang1 class could > > just do WriteStruct().Generate(vars) and Lang1 class would > > magically make WriteStruct a subclass of itself. > > You should rethink your program design. > > It seems that when you create a WriteStruct you should really be passing > its __init__() method the class that you want it to be a "subclass" of, > creating an instance of that class, and then using generic delegation to > that subclass (using a modified __getattr__()) to handle methods that > aren't found in the WriteStruct. This is what I am going to do. For some reason I got stuck to think I needed to solve it with inheritance. Didnt think of the possibility to modify getattr to make the delegation be much nicer. Thanks for the tip > > I can see there are circumstances in which this might not work, but I > believe your current ugly intentions reveal a design smell that you > really need to get rid of if you want a clean program. > > regards > Steve > -- > Steve Holden+1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > -- Asciimercial - > Get on the web: Blog, lens and tag your way to fame!! > holdenweb.blogspot.comsquidoo.com/pythonology > tagged items: del.icio.us/steve.holden/python > All these services currently offer free registration! > -- Thank You for Reading -- http://mail.python.org/mailman/listinfo/python-list
Why doesnt __getattr__ with decorator dont call __get_method in decorator
Hi, I tried to write a decorator for that should be for methods but for some reasons it doens seem to work when you try to do it on the __getattr__ method in a class. Could anybody give some hints why this is? Example: class decoratorTest(object): def __init__(self, func): self.func = func def __get__(self, instance, cls=None): print "__get__", instance self.instance = instance return self def __call__(self, *args, **kwds): return self.func(self.instance, *args, **kwds) class MyClass1(object): @decoratorTest def decoratorTestFunc(self): print "hello1" @decoratorTest def __getattr__(self,name): print "hello2" a = MyClass1() a.decoratorTestFunc() # This works since the __get__ method is called and the instance is retreived a.test # This doesnt call the __get__ !!! Output __get__ <__main__.MyClass1 object at 0x4012baac> hello1 Traceback (most recent call last): File "/home/tonib/test.py", line 27, in ? a.test File "/home/tonib/test.py", line 12, in __call__ return self.func(self.instance, *args, **kwds) AttributeError: 'decoratorTest' object has no attribute 'instance' -- http://mail.python.org/mailman/listinfo/python-list
Re: Why doesnt __getattr__ with decorator dont call __get_method in decorator
On Mar 28, 4:47 pm, [EMAIL PROTECTED] (Alex Martelli) wrote: > glomde <[EMAIL PROTECTED]> wrote: > > Hi, > > > I tried to write a decorator for that should be for methods but for > > some reasons > > it doens seem to work when you try to do it on the __getattr__ method > > in a class. > > Could anybody give some hints why this is? > ... > > a.test # This doesnt call the __get__ !!! > > > Output > > __get__ <__main__.MyClass1 object at 0x4012baac> > > hello1 > > Traceback (most recent call last): > > File "/home/tonib/test.py", line 27, in ? > > a.test > > File "/home/tonib/test.py", line 12, in __call__ > > return self.func(self.instance, *args, **kwds) > > AttributeError: 'decoratorTest' object has no attribute 'instance' > > What Python release are you using? With Python 2.5, your code gives me > instead: > > >>> a.test > > Traceback (most recent call last): > File "", line 1, in > File "a.py", line 11, in __call__ > return self.func(self.instance, *args, **kwds) > TypeError: __getattr__() takes exactly 2 arguments (3 given) > > > > so there would seem to be some "mis-alignment" wrt the problems you > observe... > > Alex I was using 2.4 but I downloaded and installed ActivePython2.5.0.0 and for I get the same message as in my original email. What python version do you use more exactly? /T -- http://mail.python.org/mailman/listinfo/python-list
Re: Why doesnt __getattr__ with decorator dont call __get_method in decorator
> To get python to run the __get__ method I think you have to call > __getattr__ explicitly: > a.__getattr__('test') > > If you do: > a.test > python follows a different routine: it checks for the existence of the > attribute, then check if there is a __getattr__ attribute. Now the > speculative bit: then I conjecture that python assumes that > __getattr__ is a function with two arguments and directly passes them > on to it. Indeed > > type(a).__dict__['__getattr__'](a, 'test') > > seems to produce the same errors as a.test, whether the instance > attribute is set or not. > And this explain why there are too many arguments (error message > above). > > -- > Arnaud So is this a python bug? I assumed it was seen as function but dont understand why it is like this. But interesting that if you call __getattr__ explicitly it works. Intuitevely I would assumet that the same route should be followed in both case. Maybe it is because __getattr__ is called only when you have an exception. /T -- http://mail.python.org/mailman/listinfo/python-list
What to use for adding syntax for hierarcical trees, metaclasses, tokenize.py or PLY?
Hi I would like to extend python so that you could create hiercical tree structures (XML, HTML etc) easier and that resulting code would be more readable. The syntax i would like is something like the below: # Example creating html tree '*!*' is an operator that creates an new node '*=*' is an operator that sets an attribute. bodyNode = body() *!* bodyNode: *=* color = blue *=* bg = white for i in headings: *!* H1(heading[i]): This would translate to something like this in python: bodyNode = body() if True: bodyNode.attr['color'] = blue bodyNode.attr['bg'] = white for i in headings: if True: bodyNode.append(H1(heading[i])) I think that with the added syntax you get better overview on how your tree looks like. But the thing is how to implement my added syntax. I dont want to mess with Python source code to add the syntax. So I searched a bit on the net and think there might be three alternatves. 1. MetaClasses. I tried to understand them but my head almost exploded :-). But my conclusion was that it is not possible with metaclasses. Since this is a real syntax change. 2. Tokenize.py. I modify tokenize.py to recognize my new operators '#!#' and '#=#' and then I write a parser that exports the code. This option I understand somewhat how to implement. But I would reduce my own code for the parser, so is there any parser that can handle tokenize.py input? So that I could somehow write rules for my code. 3. Use PLY or any other python parser. Write rules for my language. But would I need to writerules that can handle the whole python languager? Then this seems to be overkill. I would just like to recognize my added syntax and convert that. So I would really like to have a rule file that handles python and then add rules for my syntax. Are there any Python rule file for the python language and a python parser for it? Then I could just add my syntax to the rule file and be able to create the output. I would be very thankfull for any hints or thougts on how to do it. Best regards, G -- http://mail.python.org/mailman/listinfo/python-list
Re: What to use for adding syntax for hierarcical trees, metaclasses, tokenize.py or PLY?
Thanks, but the thing is that I want to have the syntactical sugar. And I think that you could use elementtree or xist or any other python tree structure module at the bottom. It could be quite generic. And with the syntactical sugar I find it a lot more readable. A little bit like yaml, but you have the power of python aswell. For example with syntactical sugar: # build a tree structure root = ET.Element("html") *!*root: *!*head("head"): *!*title("title): *=*text = "Page Title" *!*body("body"): *=*bgcolor = "#ff" *=*text = "Hello, World!" This would then be this with element tree package. # build a tree structure root = ET.Element("html") head = ET.SubElement(root, "head") title = ET.SubElement(head, "title") title.text = "Page Title" body = ET.SubElement(root, "body") body.set("bgcolor", "#ff") body.text = "Hello, World!" I find it a lot more readable with the syntactical sugar. So I would really like to add this syntax. /T -- http://mail.python.org/mailman/listinfo/python-list
compiling module from string and put into namespace
Hi, I want to create a function that preprocesses a file and then imports the parsed file. What I found out is that you can do something like this: def ImportFile(fileName): parsedCode = Parser(fileName).Parse() module = new.module(name) exec parsedCode in module.__dict__ sys.modules[name] = module import name But this works only if the ImportFile isnt loaded from a module. Since the import is local. So this wouldnt work: from XXX import ImportFile ImportFile(fileName) fileName.Function() Since the import in ImportFile isnt visible the module that calls it. So how do I do so that the import is visible from callers namespace? Best regards, T -- http://mail.python.org/mailman/listinfo/python-list
Re: compiling module from string and put into namespace
Tanks but that isn't what I am looking for. I really want a function that you can call and imports the module into the calling functions namespace. I dont want the caller to call import but a function. -- http://mail.python.org/mailman/listinfo/python-list
Re: compiling module from string and put into namespace
> I dont want the caller to call import but a function. come again? >>> type (__builtins__.__import__) I didnt mean that __import__ isnt a function, but that I want to make a function called ImoprtFile that actually does something very similar that what __import__. So to rephrsase the questin how does __import__ load a module into the callers namespace. Example: file1 def ImportFile(fileName): parsedCode = Parser(fileName).Parse() module = new.module(name) exec parsedCode in module.__dict__ sys.modules[name] = module import name #!!! This doesn't work. Imports in file1 namespace! file2 import file1 file1.ImportFile(fileName) fileName.function() #This wont work because the import happened locally in file1! Now the import in file1 doesnt take effect in file2. So what do I have to do to make that work. And I dont want to do a custom hook to import. So how does __import__ do? -- http://mail.python.org/mailman/listinfo/python-list
Re: compiling module from string and put into namespace
Ok, now I think I know what I need to do. I need to create a variable in the calling functions locals. So how do I get access to the calles locals dictionary? Is it possible? -- http://mail.python.org/mailman/listinfo/python-list
Re: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation)
> But generally, I don't do layout like that. I'd do: > >--->cursor.execute( >--->--->--->'select id, item, amount, field4, >--->--->--->'from table1 where amount>100' >--->) > >Which keeps looking fine, no matter what tab size, and without mixing >tabs and spaces. > Which only works fine only if you are the one only editing the file. But If you work in a team it is kind of hard to make sure that everybody use tabs and not spaces. And it is not very easy to spot either. The same is valid if somebody use your code or you want to import somebody elses code. -- http://mail.python.org/mailman/listinfo/python-list
Proposal for new operators to python that add syntactic sugar for hierarcical data.
i I would like to extend python so that you could create hiercical tree structures (XML, HTML etc) easier and that resulting code would be more readable than how you write today with packages like elementtree and xist. I dont want to replace the packages but the packages could be used with the new operators and the resulting IMHO is much more readable. The syntax i would like is something like the below: # Example creating html tree '*!*' is an operator that creates an new node, '*=*' is an operator that sets an attribute. So if you take an example to build a smalle web page and compare with how it looks with in element tree now and how it would look like when the abover operators would exist. With element tree package. # build a tree structure root = ET.Element("html") head = ET.SubElement(root, "head") title = ET.SubElement(head, "title") title.text = "Page Title" body = ET.SubElement(root, "body") body.set("bgcolor", "#ff") body.text = "Hello, World!" With syntactical sugar: # build a tree structure root = ET.Element("html") *!*root: *!*head("head"): *!*title("title): *=*text = "Page Title" *!*body("body"): *=*bgcolor = "#ff" *=*text = "Hello, World!" I think that with the added syntax you get better view of the html page. Repeating things dissapears and you get indentation that corresponds to the tree. I think it is very pythonic IMHO. It could be done quite generic. If the variable, object after '*!*' must support append method and if you use '*=*' it must support __setitem__ Any comments? -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for new operators to python that add syntactic sugar for hierarcical data.
There are some difference which are quite essential. First of all I dont se how you set attributes with that and then I dont see how you can mix python code with the creation. So how do you do this: root = ET.Element("html") *!*root: *!*head("head"): *!*title("title): for i in sections: !*! section(): *=*Text = section[i] -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for new operators to python that add syntactic sugar for hierarcical data.
But you cant mix python code in there when creating the nodes. That is when it gets quite ugly an unreadable according to me. But I also relly do think that this: # build a tree structure root = ET.Element("html") *!*root: *!*head("head"): *!*title("title): *=*text = "Page Title" *!*body("body"): *=*bgcolor = "#ff" *=*text = "Hello, World!" Especially if you start having deeper hierachies like. But the big other plus is that you can have any python code in beetween. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for new operators to python that add syntactic sugar for hierarcical data.
Actually we did start of with YAML, but realised that we need to have the power of a programming language aswell. But I wanted to come up with something that looked very clos to YAML since I find it quite readable. I have implemented the syntax, but as a preprocessor for python and it works quite nice. Cheers, T -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for new operators to python that add syntactic sugar for hierarcical data.
> You can put any python expression in there, and in the Node class you can do > what you want. But the main advantage is any python code not only expressions. In addition to that you get nice flow style. Can set variables which you later use as want. > Seems that you are after a templating-system. Well, there are plenty of them > available, including yours. A preprocessor is nothing but a template system > - see TurboGears-utilized KID (http://kid.lesscode.org/) for example, it > generates python files. And way more readable, because you are working in > the domain of your application (HTML) instead of some crude syntax that is > neither fish or flesh. What I propose is for all data that is hierarcical. Not only HTML. I dont use it for creating html. Templating systems have the drawback IMO that the more code you get the more undreadable it gets. If the code part is small they are very nice. The other part is that indentation, syntax highlighting and so on works not so well when working with such code. I would translate your example to the below. Which I think is much more readable, since you see the python code flow much easier. I realised that you realy should do Element("html") and not html("html") when adding nodes in my syntax and using elementtree. from urllib import urlopen from elementtree.ElementTree import parse, tostring feed = 'http://naeblis.cx/rtomayko/weblog/index.atom' root = parse(urlopen(feed)).getroot() ns = '{http://purl.org/atom/ns#}' title = root.findtext(ns + 'title') root = ET.Element("html") *+* root: *+* Element("head"): *+* Element("title") *+* Element("body"): *=* bgcolor = "blue" *=* text = "yellow" *+* Element("table"): *=* cellpadding="4" *=* cellspacing="4" for i, entry in enumerate(root): *+* Element("tr"): if entry.tag==ns + 'entry': *+* Element("td"): *=* bgcolor = ('white', 'yellow')[i % 2] *+* Element("a"): *=* href = entry.find(ns + 'link').attrib['href'] *=* text = "entry.findtext(ns + 'title')" With the above you can use your favorite editor to do the coding and get indentation, syntax highlightning and so on. Which I find can be quite a burden with a templating system especially the more code that is in there. It is also easier to debug in comparison when using a templating system. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for new operators to python that add syntactic sugar for hierarcical data.
> You also repeat yourself: head("head"), title("title"), body("body") > > What about this: > > # build a tree structure > root = ET.Element("html") > !root > !head > !title > if A is True: > &text = "Page A" > else: > &text = "Page B" > !body > &bgcolor = "#ff" > &text = "Hello, World!" > > Yes this is how it should be. But It depends on which package would be used. If you used xist it would look like that since they have one class for each html tag. I really propose a generic solution that any package that support the method append and __settiem__ could use the new syntax. But minor isssues but it would look something like this with xist: !root !head(): !title(): if A is True: &text = "Page A" else: &text = "Page B" !body() &bgcolor = "#ff" &text = "Hello, World!" > mmm...yamlthon? yython...:-) Guess what I have for suffix on the files before preprocessing? pyml ofcourse. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for new operators to python that add syntactic sugar for hierarcical data.
> What about using data for nodes and '=' for attributes ? > Would look like: > > > > Page Title > > > Hello World > > > > > I think that with the added syntax you get better view of the html > > page. > > indeed !-) I dont think it is very pythonic :-). You dont use endtags and then you dont use ':' to mark that you nest a level. :-) And I dont see where it is allowed to put real python code. So could you show an example with a for loop? :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for new operators to python that add syntactic sugar for hierarcical data.
> Here's a nice stan example, taken from Kieran Holland's tutorial > http://www.kieranholland.com/code/documentation/nevow-stan/ I took a quick look and it looks nice as long as your page is static. But I couldnt se how you could mix in python code seamlessy when creating your tree. But I might be wrong if you could write: tags.body[ for i in range(10): tags.h1[ "Heading %s." %(i) ], tags.p[ "This text is inside a paragraph tag." ], ] I think that this is close enough to my syntax. But I dont think you can do it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for new operators to python that add syntactic sugar for hierarcical data.
> Adding ugly and unintuitive "operators" to try to turn a general purpose > programming language into a half-backed unusable HTML templating > language is of course *much* more pythonic... IT is not only for HTML. I do think html and xml are the biggest creators of hierarcical treestructures. But it would work for any package that manipulates, creates hierarchical data. I used HTML as example since it is a good example and most people would understand the intention. But could you elaborate on your comment that it is unusable. Do you think all template systems are unusable or what is the specific reason you think what i propose is unusable? IMO it is a mix between yml and python. Yml has the advantage that it can be read by many programming languages but the disadvantage is that it is static. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for new operators to python that add syntactic sugar for hierarcical data.
> What about writing a mini-language that gets translated to Python? Think of > Cheetah, which does exactly this (albeit not being limited to templating HTML > data). I have implemented my proposal as preprocessor. And it works fine. But my proposal in not only for HTML it can be used for all hieracical data. Example: myList = [] *+* myList: *+* []: for i in range(10): *+* i *+* {}: for i in range(10): *=* i = i Which should create myList = [[0..9], {0:0, ... 9:9}] So it adds the power of for loops etc when creating data structures. ANY datastructure. > nothing general the OP is trying to achieve here Define general :-). I do think I solve something and make it more readable. You could also argue that list comprehension doesnt solve anything general. > By the way: the language you (the OP) are trying to implement here goes > strictly against the MVC model of application programming. You know that, > right? ???. I cant see how this breaks MVC. MVC depends on how you parition your application this doesnt put any constraint on how you should do your application. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for new operators to python that add syntactic sugar for hierarcical data.
I'm answering two of you posts here... > Sweet Lord, have mercy ! > > > Which should create myList = [[0..9], {0:0, ... 9:9}] > > myList = [ > range(10), > dict((i, i) for i in range(10)) > ] > Let's talk about readability My code was just to show that the proposal is not only for HTML generation but could be used whenever you want to create COMPLEX hierarcical datastructures. In the above example I would of course use what you wrote. Do I need to show you a example where you cant use the style you showed? > Strange enough, working with trees is nothing new, and it seems that > almost anyone managed to get by without cryptic 'operators' stuff. Strange enough once almost anyone managed to get by without Python... :-) > > I used HTML as example since it is a good > > example and > > most people would understand the intention. > >Sorry for being dumb. It not your fault :-) > > But could you elaborate on your comment that it is unusable. > > Ask all the coders that switched from Perl to Python why they did so... You seem to really have a thing for Perl... >From what you written I assume you mean that it is no good because you find the syntax cryptic. For me cryptic is for example how you in Perl create list of lists, ie it takes a while to understand and when you havent done in a while youyou have to relearn it. Python has a few of those aswell... but you really only need them when doing something cryptic... IMO what I propose isnt cryptic, because of * I think after it has been explained it is no problem to understand how it works. * It doesnt have strange sideeffects * Doesnt break any old code. * You dont have to relearn if you havent done it a while. Also if you never would have seen such code before, I think you would understand what is meant and even be able to modify it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for new operators to python that add syntactic sugar for hierarcical data.
> What you are trying to achieve is to make syntactic sugar for making namespace > definitions look nicer. But: the way you are trying to do so isn't pythonic, > because there isn't one obvious way how your proposal works; you're not even > specifying a proper semantic interpretation of your syntax (and use "magic" > markers, which is even more a NoNo). I used 'magic' markers, since I am lousy at coming up with new keywords > > For a better thought out proposal (IMHO) for stacking and defining namespaces > (based on the current metaclass behaviour), look for the PEP on the "make" > keyword (which was sent to Py-Dev some weeks ago). It might be that my proposal the same as the 'make' pep but not so general... But I'll try to formalize it a little bit more. I am proposing two new keywords 'node' and 'attr'. Which have the syntax: node [callable|name][:] This will append itself to the current node if it is a callable. If it is a name it will become the new current node. The current node has the scope of the block or until a new node is created. attr name = expression This will set the attribute name to expression on the current node. I dont think it is the same as the 'make' but I wouldnt rule it out. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for new operators to python that add syntactic sugar for hierarcical data.
> We already have this (quite close to) this syntax: > > class (super): > = * > [class *] > > There's also the Zope3 'implements' trick, that allow to modify the > class namespace without assignement: > > class : > (*args, **kw)* > > So what you want is very certainly doable without any syntax change. It's not obvious me how you would do it it with the above syntax. Could you give me an example? For example how would you do: root = ET.Element("html") node root: attr head("head"): node title("title): for i in sections: node section(): attr Text = section[i] -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for new operators to python that add syntactic sugar for hierarcical data.
So I read trough all of the make PEP and make would support the syntax i propose.. and more generic and better in many ways. Since it was rejected I have to continue live with my preprocessor... >From the make PEP . Allowing this sort of customization could allow XML to be written without repeating element names, and with nesting of make-statements corresponding to nesting of XML elements: make Element html: make Element body: text('before first h1') make Element h1: attrib(style='first') text('first h1') tail('after first h1') make Element h1: attrib(style='second') text('second h1') tail('after second h1') -- http://mail.python.org/mailman/listinfo/python-list
is it possible to set namespace to an object.
Hi, is it somehow possible to set the current namespace so that is in an object. Somthing like. class Test(): testObj = Test() set namespace testObj Name = "Test" Name would set testObj.Name to "Test". I was thinking this could be done with the with statement somehow (without using as) in the __enter__ function. Is the above possible? /T -- http://mail.python.org/mailman/listinfo/python-list
Re: is it possible to set namespace to an object.
On 21 Jan, 18:59, Wildemar Wildenburger <[EMAIL PROTECTED]> wrote: > glomde wrote: > > Hi, > > > is it somehow possible to set the current namespace so that is in an > > object. > > [snip] > > set namespace testObj > > Name = "Test" > > > Name would set testObj.Name to "Test". > > > [snip] > > > Is the above possible? > > Don't know, sorry. But let me ask you this: Why do you want to do this? > Maybe there is another way to solve the problem that you want to solve. The reason is that I do not want to repeat myself. It is to set up XML type like trees and I would like to be able to do something like. with ElemA(): Name = "Top" Description "Blahaha..." with ElemB(): Name = "ChildA" Description "Blahaha..." This would be the instead of. with ElemA() as node: node.Name = "Top" node.Description "Blahaha..." with ElemB() as node: node.Name = "ChildA" node.Description "Blahaha..." So to save typing and have something that I think looks nicer. BR /T > > /W -- http://mail.python.org/mailman/listinfo/python-list
Re: is it possible to set namespace to an object.
On 21 Jan, 20:16, George Sakkis <[EMAIL PROTECTED]> wrote: > On Jan 21, 1:56 pm, glomde <[EMAIL PROTECTED]> wrote: > > > > > On 21 Jan, 18:59, Wildemar Wildenburger > > > <[EMAIL PROTECTED]> wrote: > > > glomde wrote: > > > > Hi, > > > > > is it somehow possible to set the current namespace so that is in an > > > > object. > > > > [snip] > > > > set namespace testObj > > > > Name = "Test" > > > > > Name would set testObj.Name to "Test". > > > > > [snip] > > > > > Is the above possible? > > > > Don't know, sorry. But let me ask you this: Why do you want to do this? > > > Maybe there is another way to solve the problem that you want to solve. > > > The reason is that I do not want to repeat myself. It is to set up XML > > type like > > trees and I would like to be able to do something like. > > > with ElemA(): > > Name = "Top" > > Description "Blahaha..." > > with ElemB(): > > Name = "ChildA" > > Description "Blahaha..." > > > > > This would be the instead of. > > with ElemA() as node: > > node.Name = "Top" > > node.Description "Blahaha..." > > with ElemB() as node: > > node.Name = "ChildA" > > node.Description "Blahaha..." > > > > > So to save typing and have something that I think looks nicer. > > ... and more confusing for anyone reading the code (including you > after a few weeks/months). If you want to save a few keystrokes, you > may use 'n' instead of 'node' or use an editor with easy auto > completion. > > By the way, is there any particular reason for generating the XML > programmatically like this ? Why not have a separate template and use > one of the dozen template engines to populate it ? > > George I am not using it for XML generation. It was only an example. But the reason for using it programmatically is that you mix power of python with templating. Using for loops and so on. XIST(www.livinglogic.de) is doing something similar. But I would like the namespace thing. The above was only an example. And yes it might be confusing if you read the code. But I still want to do it, the question is it possible? -- http://mail.python.org/mailman/listinfo/python-list
Re: is it possible to set namespace to an object.
On 21 Jan, 22:00, George Sakkis <[EMAIL PROTECTED]> wrote: > On Jan 21, 2:52 pm, glomde <[EMAIL PROTECTED]> wrote: > > > > > On 21 Jan, 20:16, George Sakkis <[EMAIL PROTECTED]> wrote: > > > > On Jan 21, 1:56 pm, glomde <[EMAIL PROTECTED]> wrote: > > > > > On 21 Jan, 18:59, Wildemar Wildenburger > > > > > <[EMAIL PROTECTED]> wrote: > > > > > glomde wrote: > > > > > > Hi, > > > > > > > is it somehow possible to set the current namespace so that is in an > > > > > > object. > > > > > > [snip] > > > > > > set namespace testObj > > > > > > Name = "Test" > > > > > > > Name would set testObj.Name to "Test". > > > > > > > [snip] > > > > > > > Is the above possible? > > > > > > Don't know, sorry. But let me ask you this: Why do you want to do > > > > > this? > > > > > Maybe there is another way to solve the problem that you want to > > > > > solve. > > > > > The reason is that I do not want to repeat myself. It is to set up XML > > > > type like > > > > trees and I would like to be able to do something like. > > > > > with ElemA(): > > > > Name = "Top" > > > > Description "Blahaha..." > > > > with ElemB(): > > > > Name = "ChildA" > > > > Description "Blahaha..." > > > > > > > > > This would be the instead of. > > > > with ElemA() as node: > > > > node.Name = "Top" > > > > node.Description "Blahaha..." > > > > with ElemB() as node: > > > > node.Name = "ChildA" > > > > node.Description "Blahaha..." > > > > > > > > > So to save typing and have something that I think looks nicer. > > > > ... and more confusing for anyone reading the code (including you > > > after a few weeks/months). If you want to save a few keystrokes, you > > > may use 'n' instead of 'node' or use an editor with easy auto > > > completion. > > > > By the way, is there any particular reason for generating the XML > > > programmatically like this ? Why not have a separate template and use > > > one of the dozen template engines to populate it ? > > > > George > > > I am not using it for XML generation. It was only an example. But > > the reason for using it programmatically is that you mix power > > of python with templating. Using for loops and so on. > > Any template engine worth its name supports loops. Other than that, > various engines provide different degrees of integration with Python, > from pretty limited (e.g. Django templates) to quite extensive (e.g. > Mako, Tenjin). > > > The above was only an example. And yes it might be confusing if you > > read the code. But I still want to do it, the question is it possible? > > I would be surprised if it is. Yet another idea you may want to > explore if you want that syntax so much is by (ab)using the class > statement since it introduces a new namespace: > > class ElemA: > Name = "Top" > Description "Blahaha..." > class ElemB: > Name = "ChildA" > Description "Blahaha..." > > PEP 359 would address this easily (it's actually the first use case > shown) but unfortunately it was withdrawn. > > George > > [1]http://www.python.org/dev/peps/pep-0359/#example-simple-namespaces Yes the make statement would have done it. But I realized that it might be possible if it is possible to override the __setattr__ of local. Then the enter function would set a global variable and the default setattr would set/get variables from this variable. Is this possible? -- http://mail.python.org/mailman/listinfo/python-list
possible to overide setattr in local scope?
In a class it is poosible to override setattr, so that you can decide how you should handle setting of variables. Is this possible to do outside of an class on module level. mysetattr(obj, var, value): print "Hello" So that test = 5 would print Hello -- http://mail.python.org/mailman/listinfo/python-list
runscript module, where are the docs...
Hi! I am going through some code and found import runscript BUT I cant find and information about this module. I searched Google did a grep in the /usr/lib/python directory. What is the purpose of this module and where can I find information about it. Or the source. Best regards, Toni -- http://mail.python.org/mailman/listinfo/python-list
Bug/Patch: Problem with xml/__init__.py when using freeze.py
Hi, I tried to do freeze.py for my script that uses ElementTree. But got the this error: File "/usr/lib/python2.5/xml/__init__.py", line 45, in _xmlplus.__path__.extend(__path__) AttributeError: 'str' object has no attribute 'extend' The reason seems that _xmlplus.__path__ is a string after freeze.py. I fixed it by changing the import to: try: _xmlplus.__path__.extend(__path__) sys.modules[__name__] = _xmlplus except AttributeError: pass This might not be the correct solution but it works for me. I do not really now how the __path__ variable works in a freezed environment. Best regards /T -- http://mail.python.org/mailman/listinfo/python-list