Re: Confusion with calling function of a subclass
Pyenos wrote: class TREE: def gettree(self):print self TREE.gettree() # I get an error saying # TypeError: unbound method gettree() must be called # with TREE instance as first argument (got nothing instead I still don't understand how to solve this simple code. what is it supposed to do? what do you expect self to be, and where do you expect it to come from ? have you tried adding some expletives, to see if that solves the problem ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: def index(self):
Marc 'BlackJack' Rintsch wrote: This depends on the definition of `expr`. If `expr` includes the possibility of enclosing parenthesis then yes. There are scenarios where you would need them. For example if you use objects that overload operators to build a callable used as decorator: @spam + eggs + viking def fn(...): ... that's a SyntaxError. the decorator syntax only allows for a dotted name, optionally followed by an argument list in parentheses. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Confusion with calling function of a subclass
Adonis Vargas [EMAIL PROTECTED] writes: Pyenos wrote: class TREE: def gettree(self):print self TREE.gettree() # I get an error saying# TypeError: unbound method gettree() must be called # with TREE instance as first argument (got nothing instead I still don't understand how to solve this simple code. You first need to create an instance of the class: tree = TREE() tree.gettree() or TREE().gettree() Hope this helps. Adonis P.S. You should look into the tutorial http://docs.python.org/tut/tut.html it will answer a lot of your questions. Yes, it definitely solved my problem. Thank you very much. :D -- http://mail.python.org/mailman/listinfo/python-list
Re: tkFileDialog closes main application
On Thu, 21 Dec 2006 22:37:37 +0100, James Stroud [EMAIL PROTECTED] wrote: Eric Brunel wrote: BTW, why do you create a sub-class of Frame for your application? Why not create a sub-class of Tk instead? The short answer is that inhereting from Frame will allow embedding of the application in another application. A Tk() can not be embedded like this. Tk is appropriately instantiated if (and only if) __name__ == __main__ here, allowing the App to run as the main application here. So I rephrase my question: will this application ever need to be embedded into another one? There are problems with this way of doing things, especially with menus: if you have to define a menu bar, you just can't attach it to a Frame; you have to have a Tk or Toplevel instance. So basically you're stuck: you can't make your application embeddable anymore. So if you actually need to have a graphical component / mega-widget that has a chance to be embedded in something else, sub-classing Frame is the way to go. If you don't, you'll have far less trouble if you sub-class Tk or Toplevel. -- python -c print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-']) -- http://mail.python.org/mailman/listinfo/python-list
Re: def index(self):
Gert Cuykens [EMAIL PROTECTED] wrote: On 21 Dec 2006 09:44:48 GMT, Duncan Booth [EMAIL PROTECTED] wrote: George Sakkis [EMAIL PROTECTED] wrote: @expr def fn(...): ... is exactly equivalent to: def fn(...): ... fn = (expr)(fn) ok i did my homework reading about decorators http://www.python.org/doc/2.4.4/whatsnew/node6.html could it be the example above needs to be like @expr def fn(...): ... is exactly equivalent to: def fn(...): ... fn = expr(fn) no it doesn't *need* to be like that, but it *could* be written like that. It is true that the parentheses I used are redundant (I thought they made my point clearer), but removing redundant parentheses doesn't actually change the meaning at all. In any case, either of these rewrites is an approximation. There is no Python code you can write which is exactly equivalent to, but doesn't use, the decorator syntax. A closer approximation would be: If you consider: def fn(...): ... is equivalent to writing: fn = new.function(somecodeobject, globals(), 'fn', (...default argument expressions...), ...and maybe a closure...) then: @expr def fn(...): ... is equivalent to writing: __anonymous_temp_1 = expr __anonymous_temp_2 = new.function(somecodeobject, globals(), 'fn', (...default argument expressions...), ...and maybe a closure...) fn = __anonymous_temp_1(__anonymous_temp_2) but I don't think that is really any clearer. It does perhaps indicate the order in which things happen more clearly: decorator expression is evaluated, then default arguments, then function is created, then decorator is called, then finally the result is assigned to a variable with the same name as the function. -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib.unquote and unicode
Martin v. Löwis [EMAIL PROTECTED] wrote: The way that uri encoding is supposed to work is that first the input string in unicode is encoded to UTF-8 and then each byte which is not in the permitted range for characters is encoded as % followed by two hex characters. Can you back up this claim (is supposed to work) by reference to a specification (ideally, chapter and verse)? http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.1 Thanks. and thanks from me too. Unfortunately, this isn't normative, but we recommend. In addition, it talks about URIs found HTML only. If somebody writes a user agent written in Python, they are certainly free to follow this recommendation - but I think this is a case where Python should refuse the temptation to guess. So you believe that because something is only recommended by a standard Python should refuse to implement it? This is the kind of thinking that in the 1980's gave us a version of gcc where any attempt to use #pragma (which according to the standard invokes undefined behaviour) would spawn a copy of nethack or rogue. You don't seem to have realised yet, but my objection to the behaviour of urllib.unquote is precisely that it does guess, and it guesses wrongly. In fact it guesses latin1 instead of utf8. If it threw an exception for non- ascii values, then it would match the standard (in the sense of not following a recommendation because it doesn't have to) and it would be purely a quality of implementation issue. If you don't believe me that it guesses latin1, try it. For all valid URIs (i.e. ignoring those with non-ascii characters already in them) in the current implementation where u is a unicode object: unquote(u)==unquote(u.encode('ascii')).decode('latin1') I generally agree that Python should avoid guessing, so I wouldn't really object if it threw an exception or always returned a byte string even though the html standard recommends using utf8 and the uri rfc requires it for all new uri schemes. However, in this case I think it would be useful behaviour: e.g. a decent xml parser is going to give me back the attributes including encoded uris in unicode. To handle those correctly you must encode to ascii before unquoting. This is an avoidable pitfall in the standard library. On second thoughts, perhaps the current behaviour is actually closer to: unquote(u)==unquote(u.encode('latin1')).decode('latin1') as that also matches the current behaviour for uris which contain non-ascii characters when the characters have a latin1 encoding. To fully conform with the html standard's recommendation it should actually be equivalent to: unquote(u)==unquote(u.encode('utf8')).decode('utf8') The catch with the current behaviour is that it doesn't exactly mimic any sensible behaviour at all. It decodes the escaped octets as though they were latin1 encoded, but it mixes them into a unicode string so there is no way to correct its bad guess. In other words the current behaviour is actively harmful. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator for Enforcing Argument Types
John Machin [EMAIL PROTECTED] wrote: if isinstance( action_for_type1(... # big snip elif isinstance(... action_typeN( ... # no else statement Ouch.. someone must have skipped his/her OO class... Quite possibly :-) but that's not the problem here. The method in question might be called say emit_generic(self, any_type_of obj) and so one bunch of isinstance calls is actually needed, but not two bunches. So: lose the decorator and add an else and a raise at the end. There is a secondary problem: annoying the crap out of callers who often know what type they have and want an emit_real which would take an int, a long, or a float and an emit_strg and ... (yes, almost all the possible types are that simple) which wouldn't go through even one chain of isinstance calls. I think the point that was being made was that the method's body should be something like: actions[type(arg)](...) which not only avoids all of the isinstance calls but also the else and the raise at the end. -- http://mail.python.org/mailman/listinfo/python-list
Re: Script Error
ie.Navigate ('URL') ie.SetTextBox(username,'txtUserId',0) not sure but shouldn't you be waiting for navigate to actually finish loading the page before setting fields? see the ie.Busy or ie.readyState properties/methods -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator for Enforcing Argument Types
Duncan Booth wrote: John Machin [EMAIL PROTECTED] wrote: if isinstance( action_for_type1(... # big snip elif isinstance(... action_typeN( ... # no else statement Ouch.. someone must have skipped his/her OO class... Quite possibly :-) but that's not the problem here. The method in question might be called say emit_generic(self, any_type_of obj) and so one bunch of isinstance calls is actually needed, but not two bunches. So: lose the decorator and add an else and a raise at the end. There is a secondary problem: annoying the crap out of callers who often know what type they have and want an emit_real which would take an int, a long, or a float and an emit_strg and ... (yes, almost all the possible types are that simple) which wouldn't go through even one chain of isinstance calls. I think the point that was being made was that the method's body should be something like: actions[type(arg)](...) which not only avoids all of the isinstance calls but also the else and the raise at the end. You are saying that you think that George thinks that they are teaching efficient coding methods in OO classes?? -- http://mail.python.org/mailman/listinfo/python-list
Re: python-hosting.com projects: dead?
On 12/20/06, greg [EMAIL PROTECTED] wrote: Richard Jones wrote: Actually, to clarify the DEFAULT configuration for Trac is to leave it open to spam. That sounds like a really bad choice of default. A bit like the way Windows comes with all the let anyone in the world send me a virus options turned on... Not really, Trac's default to be open is great for intranet installations. It is Webfactions own fault that they haven't been able to shield themself from spam by changing Trac's default to something more restrictive. -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator for Enforcing Argument Types
George Sakkis a écrit : John Machin wrote: Bruno Desthuilliers wrote: my humble opinion Python is dynamic, and fighting against the language is IMHO a really bad idea. The only places where theres a real need for this kind of stuff are when dealing with the outside world (IOW : inputs and outputs). And then packages like formencode can do much more than mere type-checking /my humble opinion Agreed. The worst case I have seen: An elaborate decorator (similar to the OP's) laboriously checks arg types. That's IMHO not consenting adults territory. But it gets a whole lot worse when it's applied to a method whose body is like this: if isinstance( action_for_type1(... # big snip elif isinstance(... action_typeN( ... # no else statement Ouch.. someone must have skipped his/her OO class... Depends... I've sometimes had to write such kind of horrors - at least once: a wrapper class to ensure that all strings accessible directly *or indirectly* (via a dict, list, method call, whatever...) would be unicode strings... But of course I didn't use decorators to type-check annything !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator for Enforcing Argument Types
John Machin [EMAIL PROTECTED] wrote: You are saying that you think that George thinks that they are teaching efficient coding methods in OO classes?? No, but I hope they teach how to recognise patterns, and I imagine they also teach something about refactoring to remove switches or long if/elif chains. (My imagination may not, of course, bear any resemblance to real life.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Regexp Neg. set of chars HowTo?
Hi! Thanks for this! I'll use that! I found a solution my question in regexp way too: import re testtext = minion battalion nation dion sion wion alion m = re.compile([^t^l]ion) print m.findall(testtext) I search for all text that not lion and tion. dd Paul McGuire wrote: It looks like you are trying to de-hyphenate words that have been broken across line breaks. Well, this isn't a regexp solution, it uses pyparsing instead. But I've added a number of other test cases which may be problematic for an re. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator for Enforcing Argument Types
Duncan Booth wrote: John Machin [EMAIL PROTECTED] wrote: You are saying that you think that George thinks that they are teaching efficient coding methods in OO classes?? No, but I hope they teach how to recognise patterns, and I imagine they also teach something about refactoring to remove switches or long if/elif chains. (My imagination may not, of course, bear any resemblance to real life.) My point is that efficent coding methods, recognition of patterns and refactoring are *general* comp sci concepts, they are not special to OO. Why do you hope / imagine such things about OO classes? -- http://mail.python.org/mailman/listinfo/python-list
Re: Regexp Neg. set of chars HowTo?
In [EMAIL PROTECTED], durumdara wrote: I found a solution my question in regexp way too: import re testtext = minion battalion nation dion sion wion alion m = re.compile([^t^l]ion) print m.findall(testtext) I search for all text that not lion and tion. And ^ion. The first ^ in that character group negates that group, the second is a literal ^, so I guess you meant [^tl]ion. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
optparser question
I'm trying optparse and I see a strange (for me) behavior: def store_value(option, opt_str, value, parser): setattr(parser.values, option.dest, value) parser = optparse.OptionParser() parser.add_option(-f, --foo, action=callback, callback=store_value, type=int, dest=foo) args = [-f, 1] (options, args) = parser.parse_args(args) print options, args {'foo': 1} [] # with the type {'foo': None} ['1'] #without it If I not specify the type in add_options, the value aren't passed to the store_value (into value variable), but it's understood as args! If I specify it, it Is this normal? Thanks, Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator for Enforcing Argument Types
John Machin [EMAIL PROTECTED] wrote: Duncan Booth wrote: John Machin [EMAIL PROTECTED] wrote: You are saying that you think that George thinks that they are teaching efficient coding methods in OO classes?? No, but I hope they teach how to recognise patterns, and I imagine they also teach something about refactoring to remove switches or long if/elif chains. (My imagination may not, of course, bear any resemblance to real life.) My point is that efficent coding methods, recognition of patterns and refactoring are *general* comp sci concepts, they are not special to OO. Why do you hope / imagine such things about OO classes? Both things are applicable outside OO, but the OO community is where they evolved. The concept of design patterns was popularized by the Gang of Four in Design Patterns: Elements of Reusable Object-Oriented Software, and I believe that the concept of refactoring also grew out of the OO community. According to Wikipedia, which is occasionally not far wrong: The first known use of the term refactoring in the published literature was in the article, Refactoring: An Aid in Designing Application Frameworks and Evolving Object-Oriented Systems, Proceedings of the Symposium on Object Oriented Programming Emphasizing Practical Applications (SOOPPA) September, 1990, ACM by William F. Opdyke and Ralph E. Johnson. -- http://mail.python.org/mailman/listinfo/python-list
Confusion over calling a nested function inside a parent function
[code] class WORK: def getwork(self): def choosetable(self):pass choosetable() #TypeError: choosetable() takes exactly 1 #argument (0 given) [/code] Calling choosetable() at the above location gives me the error described above. -- http://mail.python.org/mailman/listinfo/python-list
Re: Confusion over calling a nested function inside a parent function
Pyenos wrote: [code] class WORK: def getwork(self): def choosetable(self):pass choosetable() #TypeError: choosetable() takes exactly 1 #argument (0 given) [/code] Calling choosetable() at the above location gives me the error described above. Although choosetable is a memeber of an instance method, it is not one itself. It should not have self as it's first formal parameter. -- http://mail.python.org/mailman/listinfo/python-list
Re: Script Error
Forced_Ambitions [EMAIL PROTECTED] writes: Guys any suggestions ? Could it be because of a MS patch or something as i believe i had some patching on the windows box i was running this script on. Forced_Ambitions wrote: Hi Guys, I am facing a problem with a script that i had written to automate opening a website and signing on to it. It was running fine for a long time but all of a sudden it has stopped progressing beyond opening the URL. I ran the code line by line on the pythonwin's IDE and it ran fine but when i execute the whole script it gives this error: Traceback (most recent call last): File C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py, line 307, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=0) File C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py, line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py, line 631, in run exec cmd in globals, locals File C:\Documents and Settings\Desktop\pi\Ressurection\Dec\19\CoE.py, line 4, in ? ie.SetTextBox(username,'txtUserId',0) File cPAMIE.py, line 387, in SetTextBox doc = self._ie.Document.forms[frmName] File C:\Python24\Lib\site-packages\win32com\client\dynamic.py, line 216, in __getitem__ return self._get_good_object_(self._enum_.__getitem__(index)) File C:\Python24\Lib\site-packages\win32com\client\util.py, line 37, in __getitem__ return self.__GetIndex(index) File C:\Python24\Lib\site-packages\win32com\client\util.py, line 56, in __GetIndex raise IndexError, list index out of range IndexError: list index out of range The code i was using is: import cPAMIE ie= cPAMIE.PAMIE() ie.Navigate ('URL') ie.SetTextBox(username,'txtUserId',0) ie.SetTextBox(pwd,'txtPassword',0) ie.ClickButton('btnSubmit',0) Any ideas as to why am i getting this error when running the code as a script Thanks in advance, Forced could you tell me more about the module, cPAMIE? if you can, give me a link to a documentation of this module. -- http://mail.python.org/mailman/listinfo/python-list
Re: Confusion over calling a nested function inside a parent function
Pyenos [EMAIL PROTECTED] wrote: [code] class WORK: def getwork(self): def choosetable(self):pass choosetable() #TypeError: choosetable() takes exactly 1 #argument (0 given) [/code] Calling choosetable() at the above location gives me the error described above. A function defined inside a method is just a function, it's only when a function is retrieved from the class dictionary (whether it was defined there or assigned to the class later) that it becomes a method. Just leave the self parameter off the choosetable function: you can still access self from the outer scope of getwork. -- http://mail.python.org/mailman/listinfo/python-list
add encoding to standard encodings works different in python 2.5?
Greetings, I use an encoding that is not available in the std python-encodings, say encoding 'flup'; under different circumstances a user might wish different version of 'flup': a strict one or a more relaxed encoding. (yes I know, this is terrible, but this is how it is) in python2.4, I managed this by: made flup_strict.py and flup_relaxed.py (coping an encoding from python std encodings; using a encoding/decoding map as in CP1252.py, with changes in the mapping). placed flup_strict.py and flup_relaxed.py in my 'main'-directory (the dir from which the my-python-source starts) at start of my python-source: add an alias for the encoding: encodings.aliases.aliases['flup']='flup_relaxed' (if user wishes relaxed encoding) this works; the encoding 'flup' is recognized and used. when testing with python 2.5, this does not work. my questions are: - should this work in 2.5? - how can i get this to work in 2.5 (nice if it would work in both 2.4 and 2.5) btw, I use ubuntu linux edgy, with both python 2.4 and 2.5 installed thanks, Henk-Jan -- http://mail.python.org/mailman/listinfo/python-list
Re: Confusion over calling a nested function inside a parent function
MacDonald [EMAIL PROTECTED] writes: Pyenos wrote: [code] class WORK: def getwork(self): def choosetable(self):pass choosetable() #TypeError: choosetable() takes exactly 1 #argument (0 given) [/code] Calling choosetable() at the above location gives me the error described above. Although choosetable is a memeber of an instance method, it is not one itself. It should not have self as it's first formal parameter. [code] class WORK: def getwork(self): def choosetable():pass choosetable() [/code] like this? thank you! ;-) -- http://mail.python.org/mailman/listinfo/python-list
Generating all permutations from a regexp
With regexps you can search for strings matching it. For example, given the regexp: foobar\d\d\d. foobar123 would match. I want to do the reverse, from a regexp generate all strings that could match it. The regexp: [A-Z]{3}\d{3} should generate the strings AAA000, AAA001, AAA002 ... AAB000, AAB001 ... ZZZ999. Is this possible to do? Obviously, for some regexps the set of matches is unbounded (a list of everything that matches * would be very unpractical), but how would you do it for simple regexps like the one above? -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Re: are there Tomboy and F-Spot equivalents?
On 12/21/06, Tshepang Lekhonkhobe [EMAIL PROTECTED] wrote: Hi, I dislike installing the entire Mono stack simply to take notes and manage photos, and am totally biased towards Python. At least for search I got Tracker, instead of Beagle. Are there equvalents applications for Tomboy and F-Spot which are written in Python. No -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows upgrade incomplete
Pete Forman wrote: I've a few versions of Python on my XP PC, most recently Python 2.5. The file associations appear not to have been upgraded. Executing a .py file turned out to still be using 2.3. assoc .py .py=Python.File ftype Python.file Python.file=D:\PROGRA~1\Python23\python.exe %1 %* Presumably if I'd uninstalled the old Python first I'd have not seen this. I've amended my file type associations and all is now well. Someone might care to look at the installer. I've used the MSIs since 2.4. I don't think you need to uninstall anything - unless the older version is no longer required. The last version of Python installed should be the default version. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: query
Fredrik Lundh wrote: [EMAIL PROTECTED] wrote: can anyone help me on indentation in python and tell me some nice text editors used for a beginner in python? http://effbot.org/pyfaq/tutor-whats-the-best-editor-ide-for-python /F In Windows, I like PyScripter. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib.unquote and unicode
Duncan Booth schrieb: So you believe that because something is only recommended by a standard Python should refuse to implement it? Yes. In the face of ambiguity, refuse the temptation to guess. This is *deeply* ambiguous; people have been using all kinds of encodings in http URLs. You don't seem to have realised yet, but my objection to the behaviour of urllib.unquote is precisely that it does guess, and it guesses wrongly. Yes, it seems that this was a bad move. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
PyExcelerator: how to set colours?
I'd like some cell to be a Blue ABCDE. Here's come code thatv tries various values for pattern_for_colour and font.colour_index, to no avail. Can anyone suggest the right way to set colours? Thanks! Gerry == from pyExcelerator import * w = Workbook() ws = w.add_sheet('alpha') style = XFStyle() fore_colour = style.pattern.pattern_fore_colour back_colour = style.pattern.pattern_back_colour ws.write (1, 1, fore_colour) ws.write (1, 2, fore_colour) ws.write (2, 1, back_colour) ws.write (2, 2, back_colour) text= ABCDE row = 5 for offset in range(-32,512): row += 1 style.font.colour_index = fore_colour + offset ws.write(row,3, fore_colour + offset, style) ws.write(row,5,text,style) style.pattern.pattern_fore_colour = fore_colour + offset ws.write(row,6,text,style) w.save('test.xls') = shows no colour variation for any of these values of offset. -- http://mail.python.org/mailman/listinfo/python-list
Re: optparser question
Michele Petrazzo wrote: I'm trying optparse and I see a strange (for me) behavior: def store_value(option, opt_str, value, parser): setattr(parser.values, option.dest, value) parser = optparse.OptionParser() parser.add_option(-f, --foo, action=callback, callback=store_value, type=int, dest=foo) args = [-f, 1] (options, args) = parser.parse_args(args) print options, args {'foo': 1} [] # with the type {'foo': None} ['1'] #without it If I not specify the type in add_options, the value aren't passed to the store_value (into value variable), but it's understood as args! If I specify it, it Is this normal? I believe so. The optparse module lists 'callback' as one of the TYPED_ACTIONS but not one of the ALWAYS_TYPED_ACTIONS, so it should only set nargs=1 if a type= argument was provided. That means that callbacks will be assumed to take zero arguments until you pass an nargs= or a type= argument. You can try using argparse_, which doesn't make these weird inferences, and generally assumes that your action will take a single argument unless you specify otherwise:: import argparse class StoreValue(argparse.Action): ... def __call__(self, parser, namespace, value, opt_str=None): ... setattr(namespace, self.dest, value) ... parser = argparse.ArgumentParser() parser.add_argument('-f', '--foo', action=StoreValue) parser.parse_args('-f 1'.split()) Namespace(foo='1') parser = argparse.ArgumentParser() parser.add_argument('-f', '--foo', action=StoreValue, type=int) parser.parse_args('-f 1'.split()) Namespace(foo=1) Not sure exactly what your callback was trying to do though -- it seems like you're just duplicating the 'store' action (which is the default anyway). FWIW, if you want to write a custom action in argparse, you don't have to worry about the weird TYPED_ACTIONS kinds of things in optparse. Just specify in the action's constructor whatever defaults you need, e.g.:: class MyStoreValue(argparse.Action): ... def __init__(self, nargs=2, type=int, **kwargs): ... superinit = super(MyStoreValue, self).__init__ ... superinit(nargs=nargs, type=type, **kwargs) ... def __call__(self, parser, namespace, value, opt_str=None): ... setattr(namespace, self.dest, value) ... parser = argparse.ArgumentParser() parser.add_argument('-f', '--foo', action=MyStoreValue) parser.parse_args('-f 1 2'.split()) Namespace(foo=[1, 2]) Of course, you can always specify nargs= and type= in the ``add_argument()`` call too. .. _argparse: http://argparse.python-hosting.com/ STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: add encoding to standard encodings works different in python 2.5?
henk-jan ebbers schrieb: - how can i get this to work in 2.5 (nice if it would work in both 2.4 and 2.5) You should implement a lookup function, and register it with codecs.register. Then you can structure your modules any way you like. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: One module per class, bad idea?
Carl Banks wrote: Now, I think this is the best way to use modules, but you don't need to use modules to do get higher-level organization; you could use packages instead. It's a pain if you're working on two different classes in the same system you have to keep switching files; but I guess some people prefer to switch files rather than to scroll for some reason. That would be me. I strongly prefer to switch files rather than scroll. I use an editor that makes it easy to switch files. For me it is much easier to switch between files than to scroll between two parts of a file, and I don't lose my place when I switch back. I like to be able to see things side by side. So I do tend to put classes in separate modules. Not always - when two or more classes are closely related or a class has one or more helper classes they may share a module - but in general my major classes are each to a module. It does make the imports look funny - I tend to give the module the same name as the class, Java style, so I have from foo.bar.MyClass import MyClass but that is a minor point IMO. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: python-hosting.com projects: dead?
BJörn Lindqvist [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] . It is Webfactions own fault that they haven't been able to shield themself from spam by changing Trac's default to something more restrictive. To me, this is a bit too much 'blame the victim'. The fault lies with spammers who are willing to exploit to destruction something they did not build. The rest of us are still learning how to live with the reality of their existence. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating all permutations from a regexp
BJörn Lindqvist wrote: With regexps you can search for strings matching it. For example, given the regexp: foobar\d\d\d. foobar123 would match. I want to do the reverse, from a regexp generate all strings that could match it. The regexp: [A-Z]{3}\d{3} should generate the strings AAA000, AAA001, AAA002 ... AAB000, AAB001 ... ZZZ999. Is this possible to do? Obviously, for some regexps the set of matches is unbounded (a list of everything that matches * would be very unpractical), but how would you do it for simple regexps like the one above? here's a start: http://mail.python.org/pipermail/python-list/2001-August/102739.html (the above generates *some* strings, not all, but the approach it uses can be generalized). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: def index(self):
Ok thx i think i understand it now class C: ... @staticmethod ... def fn(): ... return 'whohoo' ... C.fn() 'whohoo' -- http://mail.python.org/mailman/listinfo/python-list
Re: python-hosting.com projects: dead?
. It is Webfactions own fault that they haven't been able to shield themself from spam by changing Trac's default to something more restrictive. Terry To me, this is a bit too much 'blame the victim'. The fault lies Terry with spammers who are willing to exploit to destruction something Terry they did not build. The rest of us are still learning how to Terry live with the reality of their existence. I'm sure there's plenty of blame to go around. Maybe the Trac authors should take their share for setting a default that leaves it open to spammers. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: rsync for python?
I want to build rsync server that can run in linux and windows, and configure by python. So I'm looking for something like rsync for python. I find rsync.py and pysync. But rsync.py looks like a client mode, it can't be a rsync server, is it? Can pysync be a rsync server? Hi nienfeng As file synchronizers go, I have had very good experience with Unison: http://www.cis.upenn.edu/~bcpierce/unison/ which supports unix and windows, but does not run as a server and is not directly python-enabled. You can set it up to run automatically using cron (linux) or Scheduled Tasks (windows), if that was the functionality you wanted in a server implementation of such a tool. regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: How a script can know if it has been called with the -i command line option?
Michele Simionato wrote: The subject says it all, I would like a script to act differently when called as $ python script.py and when called as $ python -i script.py. I looked at the sys module but I don't see a way to retrieve the command line flags, where should I look? I realize this is quite a hack, but the entire command line is preserved in the process's entry in the OS's process table. if you do ps -ax you will see that the interpreter was invoked with -i. I didn't test this under windows, but it works on Mac and Linux. -- http://mail.python.org/mailman/listinfo/python-list
Re: How a script can know if it has been called with the -i command line option?
Peter Wang wrote: Michele Simionato wrote: The subject says it all, I would like a script to act differently when called as $ python script.py and when called as $ python -i script.py. I looked at the sys module but I don't see a way to retrieve the command line flags, where should I look? I realize this is quite a hack, but the entire command line is preserved in the process's entry in the OS's process table. if you do ps -ax you will see that the interpreter was invoked with -i. I didn't test this under windows, but it works on Mac and Linux. There is a set of utilities that have UNIX-like ps behavior, but, as is typical for Windows, they don't work the way their UNIX and UNIX-like counterparts do. Does 'ps' work from within Cygwin, and if so, would redistributing that be an option? -- Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator for Enforcing Argument Types
Bruno Desthuilliers wrote: my humble opinion Python is dynamic, and fighting against the language is IMHO a really bad idea. The only places where theres a real need for this kind of stuff are when dealing with the outside world (IOW : inputs and outputs). And then packages like formencode can do much more than mere type-checking /my humble opinion I don't think proper use of type checking is fighting against the language. The goal of any language is to enable programmers to express their intent in a form that executes correctly. Python is extremely expressive but there is a trade-off with correctness - you can easily say something that you don't mean. Unit testing is sometimes sufficient, but it can never span the infinite space of potential errors. Type-checking method signatures guarantees a certain amount of low-level correctness, and most type-checking mechanisms also serve as documentation aids. I think that with a sufficiently sophisticated type checking syntax, one can get the best of both worlds. If the type checker understood interfaces (like PyProtocols) and its syntax had the flexibility to indicate sets of allowed arguments and aggregates of allowed types/interfaces, it would cover the majority of cases without limiting expressive power. I understand that we're all adults, but it's still nice to have the computer tell us when we're being childish. :) -peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator for Enforcing Argument Types
Duncan Booth wrote: John Machin [EMAIL PROTECTED] wrote: if isinstance( action_for_type1(... # big snip elif isinstance(... action_typeN( ... # no else statement Ouch.. someone must have skipped his/her OO class... Quite possibly :-) but that's not the problem here. The method in question might be called say emit_generic(self, any_type_of obj) and so one bunch of isinstance calls is actually needed, but not two bunches. So: lose the decorator and add an else and a raise at the end. There is a secondary problem: annoying the crap out of callers who often know what type they have and want an emit_real which would take an int, a long, or a float and an emit_strg and ... (yes, almost all the possible types are that simple) which wouldn't go through even one chain of isinstance calls. I think the point that was being made was that the method's body should be something like: actions[type(arg)](...) which not only avoids all of the isinstance calls but also the else and the raise at the end. Actually my first thought was that the objects being typechecked belong (or could be refactored so that they belong) in a hierarchy so that each action_type_i() could be just an action() method of a subclass (I've actually seen C++ code - apparently from [ex-]C programmers - that uses a private 'kind' field and then builds long switch statements based on 'kind' instead of proper subclassing). But you're right, if the objects in question don't have (and cannot or should not grow) an action() method (e.g. builtins), a dict dispatch based on type is a reasonable choice, at least if you don't care about handling automatically the derived classes. Otherwise you have to simulate the mro(), using something like: class TypeDispatcher(dict): def __call__(self, obj, *args, **kwds): try: # handle both old and new style classes objtype = obj.__class__ except AttributeError: objtype = type(obj) for t in itermro(objtype): if t in self: return self[t](obj, *args, **kwds) raise TypeError('No handler for %r' % objtype.__name__) def itermro(cls): from collections import deque visited = set() queue = deque([cls]) while queue: cls = queue.popleft() yield cls for cls in cls.__bases__: if cls not in visited: visited.add(cls) queue.append(cls) if __name__ == '__main__': class A(object): def foo(self, *args, **kwds): return A.foo dispatcher(%s,%s) % (args,kwds) class B(A): def foo(self, *args, **kwds): return B.foo dispatcher(%s,%s) % (args,kwds) d = TypeDispatcher() d[A] = lambda self,*args,**kwds: self.foo(*args,**kwds) d[int] = lambda self,*args,**kwds: int dispatcher(%s, %s, %s) % (self, args, kwds) for obj in A(), B(), 3: print d(obj, hello, world, x=3, y=3.5) George -- http://mail.python.org/mailman/listinfo/python-list
Re: How a script can know if it has been called with the -i command line option?
Michele Simionato wrote: The subject says it all, I would like a script to act differently when called as $ python script.py and when called as $ python -i script.py. [Michael B. Trausch] There is a set of utilities that have UNIX-like ps behavior, but, as is typical for Windows, they don't work the way their UNIX and UNIX-like counterparts do. Does 'ps' work from within Cygwin, and if so, would redistributing that be an option? If you wanted to get the command line from within Windows, you could use win32api.GetCommandLine. I think the OP's on Linux, and in any case you'd have to do your own parsing, but... dump c:\python -i Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import win32api win32api.GetCommandLine () 'python -i' /dump TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
On Fri, 08 Dec 2006 03:07:09 -0800, Mark Tarver wrote: How do you compare Python to Lisp? What specific advantages do you think that one has over the other? Note I'm not a Python person and I have no axes to grind here. This is just a question for my general education. Mark Kill this frakkin thread; Lisp rules -- while Python is boring (but better than many other alternatives). E.O.F. -- Lars Rune Nøstdal http://nostdal.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: optparser question
Steven Bethard wrote: You can try using argparse_, which doesn't make these weird inferences, and generally assumes that your action will take a single argument unless you specify otherwise:: -cut- Not sure exactly what your callback was trying to do though -- it seems like you're just duplicating the 'store' action (which is the default anyway). I made only a copy from the python docs for show the problem. Ok, I have not understand the trickle for transform the action=callback and provide a callback to a new action. I believe, however, that the doc has to be more explicit about this strange behavior, because a not so expert dev (like me :) ), can don't understand at the first time, it. STeVe Thanks, Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator for Enforcing Argument Types
Peter Wang wrote: I understand that we're all adults, but it's still nice to have the computer tell us when we're being childish. :) like this? def accepts(*types): raise RuntimeError(don't be childish!) def returns(rtype): raise RuntimeError(don't be childish!) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: removing the header from a gzip'd string
Fredrik Lundh wrote: Gabriel Genellina wrote: Using the default options (deflate, default compression level, no custom dictionary) will make those first two bytes 0x78 0x9c. If you want to encrypt a compressed text, you must remove redundant information first. encryption? didn't the OP say that he *didn't* plan to decompress the resulting data stream? Knowing part of the clear message is a security hole. well, knowing the algorithm used to convert from the original clear text to the text that's actually encrypted also gives an attacker plenty of clues (especially if the original is regular in some way, such as always an XML file or always a record having this format). sounds to me like trying to address this potential hole by stripping off 16 bits from the payload won't really solve that problem... /F Yes, I'm also interested to know why the OP wants to remove the header. Though I'm not an expert on the zip format, my understanding is that most binary formats are not of much use in pieces (though some composite formats might be, e.g. you might be able to meaningfully extract a piece, such as an image embedded in a Word file). I somehow don't think a compressed zip file would be of use in pieces (except possibly for the header itself). But I could be wrong of course. Vasudev Ram http://www.dancingbison.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating all permutations from a regexp
BJörn Lindqvist [EMAIL PROTECTED] wrote: With regexps you can search for strings matching it. For example, given the regexp: foobar\d\d\d. foobar123 would match. I want to do the reverse, from a regexp generate all strings that could match it. The regexp: [A-Z]{3}\d{3} should generate the strings AAA000, AAA001, AAA002 ... AAB000, AAB001 ... ZZZ999. Is this possible to do? Obviously, for some regexps the set of matches is unbounded (a list of everything that matches * would be very unpractical), but how would you do it for simple regexps like the one above? A regular expression matcher uses a state machine to match strings. What you want to do is do a traversal through that state machine generating all possible matches at each point. Luckily the python regexp matcher is written in python, so you have access to the state machine directly if you want. Take a look at sre*.py in the python library and you might be able to work out what to do! I had a brief look myself, and it looked... complicated! -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating all permutations from a regexp
Nick Craig-Wood wrote: A regular expression matcher uses a state machine to match strings. unless it's the kind of regular expression matcher that doesn't use a state machine, like the one in Python. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: optparser question
Michele Petrazzo wrote: Ok, I have not understand the trickle for transform the action=callback and provide a callback to a new action. Yeah, you're not the only one. ;-) I believe, however, that the doc has to be more explicit about this strange behavior, because a not so expert dev (like me :) ), can don't understand at the first time, it. Yeah, it's pretty complicated. I didn't really understand it until I wrote argparse_ to replace the optparse module. If you have a good idea for how to improve the documentation, I'm sure the maintainers would be grateful. You can post your suggestion here: http://sourceforge.net/tracker/?group_id=5470atid=105470 You don't need to know LaTeX or anything -- just a simple snippet of text and where in the docs you think it should go is all they need. .. _argparse: http://argparse.python-hosting.com/ STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: removing the header from a gzip'd string
Fredrik Lundh ha escrito: Gabriel Genellina wrote: If you want to encrypt a compressed text, you must remove redundant information first. encryption? didn't the OP say that he *didn't* plan to decompress the resulting data stream? I was trying to imagine any motivation for asking that question. And I considered the second part as I'm not the guy who will reconstruct the original data. But I'm still intrigued by the actual use case... -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Building python C++ extension modules using MS VC++ 2005?
Sandra-24 wrote: You can use 2005 to build extensions for Python 2.5. I've done this with several extensions, both my own and others. I do not know if you can use it for Python 2.4, so I won't advise you on that. I thought Microsoft made its C/C++ compiler, version 7.1 (2003) freely available as a command line tool. If you can't find it on their site, ask around, I'm sure a lot of people have it. Probably you'll also find someone has put it up somewhere if you search on google. Try 2005 first and see what happens though. But how exactly should I do it? I installed VC8 and get the all-familiar error message: Python was built with Visual Stuidio 2003 Actually, I get a copy of VC6/2003 but this compiler can not compile boost 1.33.1/serialization so it can not be used to compile my extension module. Bo -- http://mail.python.org/mailman/listinfo/python-list
Re: How to distribute an additional DLL to site-packages?
I am writing a python extension module that needs to link with a third-party DLL. How can I copy this DLL to the site-packages directory along with my extension modules? It seems that data_files parameter can do this, but I do not know how to get the absolute destination directory. After all, this directory is configurable. So nobody has ever done this??? Bo -- http://mail.python.org/mailman/listinfo/python-list
Re: One module per class, bad idea?
Kent Johnson wrote: Carl Banks wrote: Now, I think this is the best way to use modules, but you don't need to use modules to do get higher-level organization; you could use packages instead. It's a pain if you're working on two different classes in the same system you have to keep switching files; but I guess some people prefer to switch files rather than to scroll for some reason. That would be me. I strongly prefer to switch files rather than scroll. I use an editor that makes it easy to switch files. For me it is much easier to switch between files than to scroll between two parts of a file, and I don't lose my place when I switch back. I like to be able to see things side by side. Man, I don't know you do it. Say I'm sitting there concentrating on programming something, and I see that I'll have to make a change in another file. All of a sudden, I have to recall some filename out of thin air. Totally breaks my train of thought, sometimes I space out trying to think of it because I have to cold-start an entirely different part of my brain. It's less of a mental distraction to just scroll. I'm in the habit of changing things as soon as the need arises. If I'm editing A and I see that I'll have to make a change in B, I stop editing A, change B, then come back to A. For me, it results in MUCH fewer forgotten changes (YMMV). But it also means a lot of switching. Consequently, trying to minimize distraction during switches is important to me. Maybe it isn't if you switch less frequently, and rarely while in the middle of somthing. I wonder if there's any correlation between how often one switches location, and preferrence (tolerance) for file size. I bet the more often one switches location, the more likely they are to prefer larger files. (BTW, any decent editor will let you view different positions of the same file side-by-side.) So I do tend to put classes in separate modules. Not always - when two or more classes are closely related or a class has one or more helper classes they may share a module - but in general my major classes are each to a module. It does make the imports look funny - I tend to give the module the same name as the class, Java style, so I have from foo.bar.MyClass import MyClass but that is a minor point IMO. I'd consider using all lowercase for the module. Of course it doesn't make sense to come up with a unique name for modules when they're mostly one-to-one with classes, but it's still nice to give users a clue whether they object they're looking at is a class or a module. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
stoppable child thread
I am trying to use Peter's StoppableThread(threading.Thread). What I want to do is to start 5 child threads, then do something, then when got ^C keyboard exception, stop the child thread. For some reason (apparently strange for me :) ), the child threads can NOT be stopped. See the enclosed code for more info, Thanks and have a nice Xmas. Jimmy #!/usr/bin/env python import threading, thread from time import sleep, ctime class StoppableThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self._running = True def stop(self): self._running = False def run(self): while self._running: # do stuff here that loops periodically to allow # the flag to be checked print 'start loop at:', ctime() sleep(4) def main(): threads = [] try: for i in range(5): t = StoppableThread() t.start() sleep(0.001) threads.append(t) except KeyboardInterrupt: for t in threads: t.stop() t.join() del threads[:] print 'child thread exiting...'+'/n/n' if __name__ == '__main__': main() -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator for Enforcing Argument Types
Peter Wang wrote: Bruno Desthuilliers wrote: my humble opinion Python is dynamic, and fighting against the language is IMHO a really bad idea. The only places where theres a real need for this kind of stuff are when dealing with the outside world (IOW : inputs and outputs). And then packages like formencode can do much more than mere type-checking /my humble opinion I don't think proper use of type checking is fighting against the language. The goal of any language is to enable programmers to express their intent in a form that executes correctly. Python is extremely expressive but there is a trade-off with correctness - you can easily say something that you don't mean. Unit testing is sometimes sufficient, but it can never span the infinite space of potential errors. Type-checking method signatures guarantees a certain amount of low-level correctness, and most type-checking mechanisms also serve as documentation aids. I think that with a sufficiently sophisticated type checking syntax, one can get the best of both worlds. If the type checker understood interfaces (like PyProtocols) and its syntax had the flexibility to indicate sets of allowed arguments and aggregates of allowed types/interfaces, it would cover the majority of cases without limiting expressive power. I understand that we're all adults, but it's still nice to have the computer tell us when we're being childish. :) Your comments on the following cut-down and disguised version of a *real-world* example would be appreciated: @accepts(object, (int, float)) def tally(self, anobj): self.total += anobj I assure you that the comments of a caller whose code did this: fubar.tally(someobj) and got this: AssertionError: arg 12345678901L does not match (type 'int', type 'float') are definitely *not* repeatable in front of the children. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to distribute an additional DLL to site-packages?
Bo Peng ha escrito: I am writing a python extension module that needs to link with a third-party DLL. How can I copy this DLL to the site-packages directory along with my extension modules? It seems that data_files parameter can do this, but I do not know how to get the absolute destination directory. After all, this directory is configurable. So nobody has ever done this??? Use the package_data option. setup(..., packages=['yyy'], package_data={'yyy':['xxx.dll']}, ...) (Distutils documentation may be arcane sometimes, but this is easily found at http://docs.python.org/dist/node12.html) Absolute dirs are almost never necesary, usually all distutils commands operate on relative paths (relative to location of setup.py for source files, relative to some meaningful directory for targets). -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Retrieve Tkinter listbox item by string, not by index
I'm trying to set the active item in a Tkinter listbox to my application's currently-defined default font. Here's how I get the fonts loaded into the listbox: self.fonts=list(tkFont.families()) self.fonts.sort() for item in self.fonts: self.fontlist.insert(END, item) #self.fontlist is the ListBox instance So far, so good. But I don't know how to set the active selection in the listbox to the default font. All the methods for getting or setting a selection in the listbox are based on index, not a string. And using standard list search methods like this: if Courier in self.fontlist: print list contains, value else: print value, not found returns an error: TypeError: cannot concatenate 'str' and 'int' objects So I'm stuck. Can someone point me in the right direction? -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: stoppable child thread
[EMAIL PROTECTED] ha escrito: def main(): threads = [] try: for i in range(5): t = StoppableThread() t.start() sleep(0.001) threads.append(t) except KeyboardInterrupt: for t in threads: t.stop() t.join() del threads[:] print 'child thread exiting...'+'/n/n' Put a print statement just at the end of main() and see what happens. You said: What I want to do is to start 5 child threads, then do something, then when got ^C keyboard exception, stop the child thread. You've created the threads, you've handled ^C, what's missing...? -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: One module per class, bad idea?
There are arguments of preference to be made on both sides. I think the question largely comes down to what is workable and maintainable. To answer the original question, I think it is not necessarily a bad idea to have one class per file. But if your classes are small, or certain classes are logically related to other classes (e.g., one class is a subclass of another, or one class is implemented in terms of another, or the two classes work together to accomplish some task and it wouldn't make much sense to be using just one of the classes), it makes a lot of sense to keep them together in the same file. If your classes are only a few dozen lines, making lots of files may be more of a pain than having the code together in one file. Where I work, we started with a set of classes that provided a layer of abstraction and encapsulation to accessing our database tables. An object was basically just a loaded DB record and generally didn't provide a lot else. As time went on, we started to code more and more logic into these classes that provided various functions to make it easy to load records, do certain kinds of computations and filtering with them, to generate the SQL to do the insert for the record, etc. The file has now grown into a 6800 line beast (including docstring, whitespace, and CVS history). Pretty much any time we implement some new functionality, there are at least a few changes in that file. When you have multiple developers working on different projects, and they all need to be making changes to that file, the chances for someone making a merge error goes up. So, we are obviously at a point where that file needs to be split up, but there are lots of other files that import and use the one file, so it is a task that has been put off. In retrospect, I wish I has started things under a one class per file strategy, but at the time, it didn't make a lot of sense to split those things up and I didn't anticipate the code getting that big. So... there's no magic one size fits all answer here - do what makes sense. As Carl points out, decent editors should be able to handle dispaying different files. I use vim and know I can split the window (both horizontally and vertically), editing either different sections of the same file or different files and can cut and paste between the two windows. In practice, I usually just jump between places in the same file under a single window, or I textually cut and paste between two separate vim sessions, but if that's something you need to do a lot, you might want to invest a bit in learning how to use split windows in your editor. Some of the documentation for doing this under vim can be found here: http://vimdoc.sourceforge.net/htmldoc/windows.html#:split and here: http://vimdoc.sourceforge.net/htmldoc/usr_08.html (I'm sure emacs can do this as well, but I don't know emacs.) If your editor can't handle similar tasks, you might want to consider getting a better editor. HTH, -ej Carl Banks [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Kent Johnson wrote: Carl Banks wrote: Now, I think this is the best way to use modules, but you don't need to use modules to do get higher-level organization; you could use packages instead. It's a pain if you're working on two different classes in the same system you have to keep switching files; but I guess some people prefer to switch files rather than to scroll for some reason. That would be me. I strongly prefer to switch files rather than scroll. I use an editor that makes it easy to switch files. For me it is much easier to switch between files than to scroll between two parts of a file, and I don't lose my place when I switch back. I like to be able to see things side by side. Man, I don't know you do it. Say I'm sitting there concentrating on programming something, and I see that I'll have to make a change in another file. All of a sudden, I have to recall some filename out of thin air. Totally breaks my train of thought, sometimes I space out trying to think of it because I have to cold-start an entirely different part of my brain. It's less of a mental distraction to just scroll. I'm in the habit of changing things as soon as the need arises. If I'm editing A and I see that I'll have to make a change in B, I stop editing A, change B, then come back to A. For me, it results in MUCH fewer forgotten changes (YMMV). But it also means a lot of switching. Consequently, trying to minimize distraction during switches is important to me. Maybe it isn't if you switch less frequently, and rarely while in the middle of somthing. I wonder if there's any correlation between how often one switches location, and preferrence (tolerance) for file size. I bet the more often one switches location, the more likely they are to prefer larger files. (BTW, any decent editor will let you view different positions of the same file
Re: textwrap.dedent replaces tabs?
Tom Plunket wrote: Frederic Rentsch wrote: Well, there is that small problem that there are leading tabs that I want stripped. I guess I could manually replace all tabs with eight spaces (as opposed to 'correct' tab stops), and then replace them when done, but it's probably just as easy to write a non-destructive dedent. This should do the trick: Dedent = re.compile ('^\s+') for line in lines: print Dedent.sub ('', line) The fact that this doesn't do what dedent() does makes it not useful. Stripping all leading spaces from text is as easy as calling lstrip() on each line: My goodness! How right your are. text = '\n'.join([line.lstrip() for line in text.split('\n')]) alas, that isn't what I am looking for, nor is that what textwrap.dedent() is intended to do. -tom! Following a call to dedent () it shouldn't be hard to translate leading groups of so many spaces back to tabs. But this is probably not what you want. If I understand your problem, you want to restore the dedented line to its original composition if spaces and tabs are mixed and this doesn't work because the information doesn't survive dedent (). Could the information perhaps be passed around dedent ()? Like this: make a copy of your lines and translate the copy's tabs to so many (8?) marker bytes (e.g. ascii 0). Dedent the originals. Left-strip each of the marked line copies to the length of its dedented original and translate the marked groups back to tabs. Frederic -- http://mail.python.org/mailman/listinfo/python-list
Re: One module per class, bad idea?
Erik Johnson wrote: The file has now grown into a 6800 line beast (including docstring, whitespace, and CVS history). Pretty much any time we implement some new functionality, there are at least a few changes in that file. When you have multiple developers working on different projects, and they all need to be making changes to that file, the chances for someone making a merge error goes up. So, we are obviously at a point where that file needs to be split up, but there are lots of other files that import and use the one file, so it is a task that has been put off. In retrospect, I wish I has started things under a one class per file strategy, but at the time, it didn't make a lot of sense to split those things up and I didn't anticipate the code getting that big. Refactor NOW. I realize this is not as easy to do for a large team than it is for a solo programmer like me, but ISTM people tend to overestimate the cost and underestimate the benefit of it. And I've seen some pretty bad excuses besides for not doing it. (But how can we refactor when we have programmers checking stuff out all the time? Um, how bout doing it during off hours? But it's too much to do in a weekend! Which only goes to show you you've let it go too far. Refactor in small doses.) I have two files ~1000 lines that are marked as these files are getting too big. (They currently define 20 and 24 classes--though in fairness the one with 24 has a bunch of small mixins.) Soon as this overloaded holiday season is over, they're getting broken up. So... there's no magic one size fits all answer here - do what makes sense. As Carl points out, decent editors should be able to handle dispaying different files. Actually, I pointed out that decent editors should be able to handle displaying the same file twice. In case you want to edit two different points of the same file side-by-side. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator for Enforcing Argument Types
John Machin wrote: Peter Wang wrote: Bruno Desthuilliers wrote: my humble opinion Python is dynamic, and fighting against the language is IMHO a really bad idea. The only places where theres a real need for this kind of stuff are when dealing with the outside world (IOW : inputs and outputs). And then packages like formencode can do much more than mere type-checking /my humble opinion I don't think proper use of type checking is fighting against the language. The goal of any language is to enable programmers to express their intent in a form that executes correctly. Python is extremely expressive but there is a trade-off with correctness - you can easily say something that you don't mean. Unit testing is sometimes sufficient, but it can never span the infinite space of potential errors. Type-checking method signatures guarantees a certain amount of low-level correctness, and most type-checking mechanisms also serve as documentation aids. I think that with a sufficiently sophisticated type checking syntax, one can get the best of both worlds. If the type checker understood interfaces (like PyProtocols) and its syntax had the flexibility to indicate sets of allowed arguments and aggregates of allowed types/interfaces, it would cover the majority of cases without limiting expressive power. I understand that we're all adults, but it's still nice to have the computer tell us when we're being childish. :) Your comments on the following cut-down and disguised version of a *real-world* example would be appreciated: @accepts(object, (int, float)) def tally(self, anobj): self.total += anobj I assure you that the comments of a caller whose code did this: fubar.tally(someobj) and got this: AssertionError: arg 12345678901L does not match (type 'int', type 'float') are definitely *not* repeatable in front of the children. I guess this is not the 'accepts' decorator of the typecheck module; with that you'd rather write it as @accepts(Self(), Number) and prevent this error (http://oakwinter.com/code/typecheck/tutorial/methods.html). I have also a very recent real-world example to share, from the other side of the fence this time. It's even worse because it's an error that passes silently. Cut-down version follows: @cherrypy.expose def retrieve(self, **kwds): queries = kwds['q'] rows = self._selectRows(*queries) # more stuff 'q' here is a multiselect field that is binded to a list of selected strings. Or so I thought, until someone noticed bizarre results in some cases. Turns out that if you select a single item from the select box, 'q' is binded to a string instead of a list of length 1, so instead of retrieving 'apple', she got back the results for 'a', 'p', 'p', 'l','e'. Bottom line, type checking is a tricky business. In some sense it's similar to the recall/precision tradeoff in information retrieval. With stricter type checking, you can increase the precision but may hurt the recall, i.e. valid code is rejected, as in your example. And vice versa, loosing up the type checks increases the recall but may hurt the precision, as in my example. George -- http://mail.python.org/mailman/listinfo/python-list
Re: How to distribute an additional DLL to site-packages?
Use the package_data option. setup(..., packages=['yyy'], package_data={'yyy':['xxx.dll']}, ...) (Distutils documentation may be arcane sometimes, but this is easily found at http://docs.python.org/dist/node12.html) Absolute dirs are almost never necesary, usually all distutils commands operate on relative paths (relative to location of setup.py for source files, relative to some meaningful directory for targets). I read that page but I am not using package so things are installed to site-packages directly. What should I put for 'yyy'? Bo -- http://mail.python.org/mailman/listinfo/python-list
attribute decorators
would it not be nice if you could assign decorators to attributes too ? for example class C: @staticattribute data='hello' or class C: @privateattribute data='hello' -- http://mail.python.org/mailman/listinfo/python-list
module to implement Abstract Base Class
I had a need recently to check if my subclasses properly implemented the desired interface and wished that I could use something like an abstract base class in python. After reading up on metaclass magic, I wrote the following module. It is mainly useful as a light weight tool to help programmers catch mistakes at definition time (e.g., forgetting to implement a method required by the given interface). This is handy when unit tests or running the actual program take a while. Comments and suggestions are welcome. Thanks, -Emin ### Abstract Base Class Module Follows This module provides the AbstractBaseClass class and the Abstract decorator to allow you to define abstract base classes in python. See the documentation for AbstractBaseClass for instructions. class _AbstractMetaClass(type): This is a metaclass designed to act as an AbstractBaseClass. You should rarely need to use this directly. Inheret from the class (not metaclass) AbstractBaseClass instead. Feel free to skip reading this metaclass and go on to the documentation for AbstractBaseClass. def __init__(cls, name, bases, dict): Initialize the class if Abstract requirements are met. If the class is supposed to be abstract or it is concrete and implements all @Abstract methods, then instantiate it. Otherwise, an AssertionError is raised. Alternatively, if cls.__allow_abstract__ is True, then the class is instantiated and no checks are done. if (__debug__ and not getattr(cls,'__allow_abstract__',False) and not _AbstractMetaClass._IsSupposedToBeAbstract(cls)): abstractMethods = _AbstractMetaClass._GetAbstractMethods( cls.__bases__) for name in abstractMethods: if ( getattr(getattr(cls,name),'__abstract__',False)): klasses = _AbstractMetaClass._GetParentsRequiring(name,cls) if (len(klasses)==0): klasses = '(Unknown); all parents are %s.' % ( cls.__bases__) else: klasses = str(klasses) raise AssertionError( 'Class %s must override %s to implement:\n%s.' % (cls,name,klasses)) super(_AbstractMetaClass,cls).__init__(name,bases,dict) def __call__(self, *args, **kw): Only allow instantiation if Abstract requirements are met. If there are methods that are still abstract and __allow_abstract__ is not set to True, raise an assertion error. Otherwise, instantiate the class. if (__debug__): stillAbstract = [ name for name in _AbstractMetaClass._GetAbstractMethods([self]) if (getattr(getattr(self,name),'__abstract__',False))] assert (getattr(self,'__allow_abstract__',False) or len(stillAbstract) == 0), ( Cannot instantiate abstract base class %s because the follwoing methods are still abstract:\n%s % (str(self),stillAbstract)) return type.__call__(self,*args,**kw) def _IsSupposedToBeAbstract(cls): Return true if cls is supposed to be an abstract class. A class which is ''supposed to be abstract'' is one which directly inherits from AbstractBaseClass. Due to metaclass magic, the easiest way to check this is to look for the __intended_abstract__ attribute which only AbstractBaseClass should have. for parent in cls.__bases__: if (parent.__dict__.get('__intended_abstract__',False)): return True @staticmethod def _GetAbstractMethods(classList,abstractMethods=None): Returns all abstract methods in a list of classes. Takes classList which is a list of classes to look through and optinally takes abstractMethods which is a dict containing names of abstract methods already found. if (None == abstractMethods): abstractMethods = {} for cls in classList: for name in cls.__dict__: method = getattr(cls,name) if (callable(method) and getattr(method,'__abstract__',False)): abstractMethods[name] = True _AbstractMetaClass._GetAbstractMethods(cls.__bases__, abstractMethods) return abstractMethods.keys() @staticmethod def _GetParentsRequiring(methodName,cls): Return list of parents that have a method defined as abstract. Arguments are methodName (string representing name of method to check) and cls (the class whose parents should be checked). result = [] for parent in cls.__bases__: if (getattr(parent,methodName,False)
Re: Problem in using Pulp
Robert Kern wrote: [EMAIL PROTECTED] wrote: Thanks, now I am not getting that error, but now I am getting a different error: -error--- GLPK(C:\Documents and Settings\Amit\Desktop\glpk-4.9\glpk-4.9\examples\).solve(prob) File C:\Documents and Settings\Amit\Desktop\pulp\pulp.py, line 114, in solve return lp.solve(self) File C:\Documents and Settings\Amit\Desktop\pulp\pulp.py, line 1740, in solve status = solver.actualSolve(self) File C:\Documents and Settings\Amit\Desktop\pulp\pulp.py, line 188, in actualSolve raise PuLP: cannot execute +self.path PuLP: cannot execute C:\Documents and Settings\Amit\Desktop\glpk-4.9\glpk-4.9\examples - can anyone tell me where the problem is? I am using following code. GLPK(C:\Documents and Settings\Amit\Desktop\glpk-4.9\glpk-4.9\examples\).solve(prob) The last character in that string is a double quote. You don't want that. What you want to do is escape all of the backslashes (or use raw strings to avoid the escaping altogether). E.g. C:\\Documents and Settings\\Amit\\Desktop\\glpk-4.9\\glpk-4.9\\examples\\ or rC:\Documents and Settings\Amit\Desktop\glpk-4.9\gplk-4.9\examples\ The second example won't work: you can't have a final backslash in a raw string! -- http://mail.python.org/mailman/listinfo/python-list
Use a Thread to reload a Module?
Hi Python Experts, I hope I can explain this right. I'll try. Background: I have a module that I leave running in a server role. It has a module which has data in it that can change. So every nth time a function in the server gets called, I want to reload the module so it has the freshest data. But there's a lot of data so it takes 5-10 seconds to do a reload. My question is: Would I be able to launch a seperate thread to reload the module while the server does it work? Hopefully it would be using the old module data right up until the thread was finished reloading. Thanks in advance, Greg Here's some psuedo code that might illustrate what I'm talking about: import lotsa_data def serve(): reload(lotsa_data) #can this launch a thread so do_stuff runs right away? do_stuff(lotsa_data.data) while 1: listen_for_requests() -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem in using Pulp
MRAB wrote: Robert Kern wrote: The last character in that string is a double quote. You don't want that. What you want to do is escape all of the backslashes (or use raw strings to avoid the escaping altogether). E.g. C:\\Documents and Settings\\Amit\\Desktop\\glpk-4.9\\glpk-4.9\\examples\\ or rC:\Documents and Settings\Amit\Desktop\glpk-4.9\gplk-4.9\examples\ The second example won't work: you can't have a final backslash in a raw string! My apologies. You are correct. -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: attribute decorators
Gert Cuykens wrote: would it not be nice if you could assign decorators to attributes too ? for example class C: @staticattribute data='hello' or class C: @privateattribute data='hello' and that would do what? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: One module per class, bad idea?
Carl Banks wrote: Erik Johnson wrote: The file has now grown into a 6800 line beast (including docstring, whitespace, and CVS history). Pretty much any time we implement some new functionality, there are at least a few changes in that file. When you have multiple developers working on different projects, and they all need to be making changes to that file, the chances for someone making a merge error goes up. So, we are obviously at a point where that file needs to be split up, but there are lots of other files that import and use the one file, so it is a task that has been put off. In retrospect, I wish I has started things under a one class per file strategy, but at the time, it didn't make a lot of sense to split those things up and I didn't anticipate the code getting that big. Refactor NOW. Carl Banks Are there tools out their to help with the refactoring task of splitting a module into two or more sections then showing what other files need to change? -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter, StringVar and dict
James Stroud wrote: Kevin Walzer wrote: I'm trying to manage user preferences in a Tkinter application by initializing some values that can then be configured from a GUI. The values are set up as a dict, like so: self.prefs= { 'interface': '-en1', 'verbose': '-v', 'fontname': 'Courier', 'point': 12, } To link these values to the appropriate Tkinter variables, I'm using code like this: self.prefs['interface'] = StringVar() self.prefs['interface'].set(-en0) # initialize This raises an error in Tkinter: Exception in Tkinter callback Traceback (most recent call last): File /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tkinter.py, line 1403, in __call__ return self.func(*args) File /Users/kevin/Programming/packetstream/packetstream-classes.py, line 293, in setPrefs self.prefs['interface'] = StringVar() File /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tkinter.py, line 3237, in __setitem__ self.tk.call(self.name, 'configure', '-'+key, value) TclError: unknown option -interface Can someone help me smooth this out--to get dict key-values into a Tkinter variable like StringVar()? Thanks. I overlooked this latter question. Probably, your naming confusion above with self.prefs and the resulting errors obscure your intention. But, were I to keep a dictionary of StringVars for prefs, I would initialize it in this manner: # somewhere in self defaults = { 'interface' : '-en1', 'verbose' : '-v', 'fontname' : 'Courier', 'point' : 12 } self.prefs = dict((d,StringVar()) for d in defaults) for d in defaults: self.prefs[d].set(defaults[d]) Note, of course, that you will need to access 'point' like this if you want it back as an int: int(self.prefs['point'].get()) Because StringVars return strings from their get() method. James Thanks, these snippets helped me work this out. -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Using Tools/freeze.py on AIX -- having problems
I have a python script that I need to freeze on AIX 5.1 (customer has AIX and does not want to install Python). The python script is pretty simple (the only things it imports are sys and socket). The README file in the Tools/freeze directory of the Python-2.4.4 distribution says the following (and many other things): Previous versions of Freeze used a pretty simple-minded algorithm to find the modules that your program uses, essentially searching for lines starting with the word import. It was pretty easy to trick it into making mistakes, either missing valid import statements, or mistaking string literals (e.g. doc strings) for import statements. This has been remedied: Freeze now uses the regular Python parser to parse the program (and all its modules) and scans the generated byte code for IMPORT instructions. It may still be confused -- it will not know about calls to the __import__ built-in function, or about import statements constructed on the fly and executed using the 'exec' statement, and it will consider import statements even when they are unreachable (e.g. if 0: import foobar). This new version of Freeze also knows about Python's new package import mechanism, and uses exactly the same rules to find imported modules and packages. One exception: if you write 'from package import *', Python will look into the __all__ variable of the package to determine which modules are to be imported, while Freeze will do a directory listing. One tricky issue: Freeze assumes that the Python interpreter and environment you're using to run Freeze is the same one that would be used to run your program, which should also be the same whose sources and installed files you will learn about in the next section. In particular, your PYTHONPATH setting should be the same as for running your program locally. (Tip: if the program doesn't run when you type python hello.py there's little chance of getting the frozen version to run.) I have installed Python-2.4.4 on AIX using the procedure: (logged in as root) ./configure --disable-ipv6 --disable-shared make make test make install The compiler being used during this process is: VisualAge C++ Professional / C for AIX Compiler, Version 6. Python seems to install correctly for the most part (make test gives a few messages about things that are not quite right (3 failed tests (test_mmap, test_pty, test_resource) and 2 unexpectedly skipped (test_curses test_largefile)), but nothing major (all the normal stuff, including test_socket and test_sys, passed)). Also, the unfrozen version of the script seems to run properly on the Python interpreter after installation. After this paragraph follows the output from the freeze. The biggest problem is the part at the bottom Warning: unknown modules remain:. Neither of the suggestions in the README file in the Tools/freeze directory about this warning message have proven helpful. Name File m BaseHTTPServer/usr/local/lib/python2.4/BaseHTTPServer.py m FixTk /usr/local/lib/python2.4/lib-tk/FixTk.py m SocketServer /usr/local/lib/python2.4/SocketServer.py m StringIO /usr/local/lib/python2.4/StringIO.py m Tkconstants /usr/local/lib/python2.4/lib-tk/Tkconstants.py m Tkinter /usr/local/lib/python2.4/lib-tk/Tkinter.py m UserDict /usr/local/lib/python2.4/UserDict.py m __builtin__ m __main__ xfer.py m _codecs m _locale /usr/local/lib/python2.4/lib-dynload/_locale.so m _random /usr/local/lib/python2.4/lib-dynload/_random.so m _socket /usr/local/lib/python2.4/lib-dynload/_socket.so m _sre m _threading_local /usr/local/lib/python2.4/_threading_local.py m array /usr/local/lib/python2.4/lib-dynload/array.so m atexit/usr/local/lib/python2.4/atexit.py m base64/usr/local/lib/python2.4/base64.py m binascii /usr/local/lib/python2.4/lib-dynload/binascii.so m cStringIO /usr/local/lib/python2.4/lib-dynload/cStringIO.so m codecs/usr/local/lib/python2.4/codecs.py m collections /usr/local/lib/python2.4/lib-dynload/collections.so m copy /usr/local/lib/python2.4/copy.py m copy_reg /usr/local/lib/python2.4/copy_reg.py m dis /usr/local/lib/python2.4/dis.py P distutils /usr/local/lib/python2.4/distutils/__init__.py m distutils.dep_util /usr/local/lib/python2.4/distutils/dep_util.py m distutils.errors /usr/local/lib/python2.4/distutils/errors.py m distutils.log /usr/local/lib/python2.4/distutils/log.py m distutils.spawn /usr/local/lib/python2.4/distutils/spawn.py m distutils.sysconfig /usr/local/lib/python2.4/distutils/sysconfig.py m distutils.text_file /usr/local/lib/python2.4/distutils/text_file.py m distutils.util/usr/local/lib/python2.4/distutils/util.py m dummy_thread /usr/local/lib/python2.4/dummy_thread.py P
scopes of local and global variable
#CODE## t_len=0 class WORK: def getwork(self): def formattable(table_to_process,type): TYPE=[p,t,T,s,i] #list of types to format if type==TYPE[1]: def format_t(): row=[] for col in table_to_process: ### # ERROR PRONE PART# ### if len(str(col))t_len: t_len=len(str(col)) ### # Error message says: # # UnboundLocalError: local variable 't_len' referenced before assignment# row+=col if (table_to_process.index(col)+1)%7==0: t_temp.append(row) row=[] format_t() # Interpreter says that t_len is local variable although i have specified t_len=0 in line 1. Also, although i've stated t_len=0 in line 1, it says that t_len is referenced before assignment. -- http://mail.python.org/mailman/listinfo/python-list
Re: attribute decorators
Fredrik Lundh wrote: Gert Cuykens wrote: would it not be nice if you could assign decorators to attributes too ? for example class C: @staticattribute data='hello' or class C: @privateattribute data='hello' and that would do what? /F Don't mind Fredrik's trolling. Your examples are perfectly clear, however, a similar call for extending the use of decorators to other structures besides functions was rejected: http://lambda-the-ultimate.org/node/1389 I'm not sure if that decision still stands with Python 3000, however, Guido has changed his mind before: http://www.artima.com/weblogs/viewpost.jsp?thread=87182 -- http://mail.python.org/mailman/listinfo/python-list
Re: scopes of local and global variable
Pyenos wrote: #CODE## t_len=0 class WORK: def getwork(self): def formattable(table_to_process,type): TYPE=[p,t,T,s,i] #list of types to format if type==TYPE[1]: def format_t(): row=[] for col in table_to_process: ### # ERROR PRONE PART# ### if len(str(col))t_len: t_len=len(str(col)) ### # Error message says: # # UnboundLocalError: local variable 't_len' referenced before assignment# row+=col if (table_to_process.index(col)+1)%7==0: t_temp.append(row) row=[] format_t() # wow. Interpreter says that t_len is local variable although i have specified t_len=0 in line 1. Also, although i've stated t_len=0 in line 1, it says that t_len is referenced before assignment. each function introduces a new scope. /f -- http://mail.python.org/mailman/listinfo/python-list
Re: scopes of local and global variable
Fredrik Lundh [EMAIL PROTECTED] writes: Pyenos wrote: #CODE## t_len=0 class WORK: def getwork(self): def formattable(table_to_process,type): TYPE=[p,t,T,s,i] #list of types to format if type==TYPE[1]: def format_t(): row=[] for col in table_to_process: ### # ERROR PRONE PART# ### if len(str(col))t_len: t_len=len(str(col)) ### # Error message says: # # UnboundLocalError: local variable 't_len' referenced before assignment# row+=col if (table_to_process.index(col)+1)%7==0: t_temp.append(row) row=[] format_t() # wow. Interpreter says that t_len is local variable although i have specified t_len=0 in line 1. Also, although i've stated t_len=0 in line 1, it says that t_len is referenced before assignment. each function introduces a new scope. /f does class WORK inherit t_len=0 from line1? does def getwork() inherit t_len=0 from line1? does def formattable(table_to_process,type) inherit t_len=0 from line1? does def format_t() inherit t_len=0 from line1? thanks. -- http://mail.python.org/mailman/listinfo/python-list
Spyce vs mod_python PSP
Hi, I have just tarted trying to transfer some of my knowledge of python to server side applications. I stated off using mod_python PSP because it was what I found first. I then found spyce, which seems a better solution. It avoids the problem of keeping indentation correct when writing code embedded in HTML, and seems to make things like dealing with forms simpler. Having said that it doesn't seem to appear in the standard ubuntu repositories, while mod_python PSP does,which would seemto be a vote against it? What do peopl here think? Any suggestions? Cheers (and happy christmas), Ben -- http://mail.python.org/mailman/listinfo/python-list
Re: Spyce vs mod_python PSP
..or any of the many other embedded python solutions that seem to be out thee... Ben wrote: Hi, I have just tarted trying to transfer some of my knowledge of python to server side applications. I stated off using mod_python PSP because it was what I found first. I then found spyce, which seems a better solution. It avoids the problem of keeping indentation correct when writing code embedded in HTML, and seems to make things like dealing with forms simpler. Having said that it doesn't seem to appear in the standard ubuntu repositories, while mod_python PSP does,which would seemto be a vote against it? What do peopl here think? Any suggestions? Cheers (and happy christmas), Ben -- http://mail.python.org/mailman/listinfo/python-list
Re: Spyce vs mod_python PSP
frankly, i don't konw anything about mod_python nor spyce, but i wish you good luck. -- http://mail.python.org/mailman/listinfo/python-list
let me simplify my question about scope of vars
code var=1 class CLASS: def METHOD1: def METHOD2: var+=var return var METHOD2() #line8 return var METHOD1() #line10 Q1: does class CLASS inherit var=0 from line1? Q2: does def METHOD1 inherit var=0 from line1? Q3: does def METHOD2 inherit var=0 from line1? Q3: does line8 return '2'? Q4: does line10 return '2\n2'? -- http://mail.python.org/mailman/listinfo/python-list
Re: python-hosting.com projects: dead?
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] |Terry To me, this is a bit too much 'blame the victim'. The fault lies |Terry with spammers who are willing to exploit to destruction something |Terry they did not build. The rest of us are still learning how to |Terry live with the reality of their existence. | | I'm sure there's plenty of blame to go around. To repeat, I place all blame, in any perjoritive sense, on the amoral insectoids who violate the basic behavioral norms of restraint that make civil life possible. Blurring the difference between perpetrators and victims only helps perpetrators. To me, it is like this. We go to a restaurant and sit down together to eat and discuss Python. Some jerk walks in, sits down at our table, and starts shoving handbills in our faces while shouting sales pitches at us. Who is to blame for the disruption? | Maybe the Trac authors should take their share for setting a default | that leaves it open to spammers. Just about every restaurant, store, church, school, park, and so on I have been to has been open to spammers along with legitimate attendees. The Trac authors are among the spammers' victims. I agree that it might be wise for them to notice the cretinoids and adjust accordingly. But they are not to blame for the need to do so. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
let me simplify my question on scope of vars
code var=1 class CLASS: def METHOD1: def METHOD2: var+=var return var METHOD2() #line8 return var METHOD1() #line10 end code Q1: does class CLASS inherit var=0 from line1? Q2: does def METHOD1 inherit var=0 from line1? Q3: does def METHOD2 inherit var=0 from line1? Q3: does line8 return '2'? Q4: does line10 return '2\n2'? -- http://mail.python.org/mailman/listinfo/python-list
Re: One module per class, bad idea?
At Friday 22/12/2006 12:56, Kent Johnson wrote: It does make the imports look funny - I tend to give the module the same name as the class, Java style, so I have from foo.bar.MyClass import MyClass but that is a minor point IMO. You can always arrange things at the module level (inside __init__.py) so from outside, people can say: from foo.bar import MyClass if you consider MyClass being in its own module an implementation detail that should be hidden. opinion class=personalModule layout is an important design concept/opinion -- Gabriel Genellina Softlab SRL __ Preguntá. Respondé. Descubrí. Todo lo que querías saber, y lo que ni imaginabas, está en Yahoo! Respuestas (Beta). ¡Probalo ya! http://www.yahoo.com.ar/respuestas -- http://mail.python.org/mailman/listinfo/python-list
Re: scopes of local and global variable
Pyenos wrote: Fredrik Lundh [EMAIL PROTECTED] writes: Pyenos wrote: #CODE## t_len=0 class WORK: def getwork(self): def formattable(table_to_process,type): TYPE=[p,t,T,s,i] #list of types to format if type==TYPE[1]: def format_t(): row=[] for col in table_to_process: ### # ERROR PRONE PART# ### if len(str(col))t_len: t_len=len(str(col)) ### # Error message says: # # UnboundLocalError: local variable 't_len' referenced before assignment# row+=col if (table_to_process.index(col)+1)%7==0: t_temp.append(row) row=[] format_t() # wow. Interpreter says that t_len is local variable although i have specified t_len=0 in line 1. Also, although i've stated t_len=0 in line 1, it says that t_len is referenced before assignment. each function introduces a new scope. /f does class WORK inherit t_len=0 from line1? does def getwork() inherit t_len=0 from line1? does def formattable(table_to_process,type) inherit t_len=0 from line1? does def format_t() inherit t_len=0 from line1? thanks. Yes and no, depending. The rule of thumb I use is that if you assign in a function, the name is not taken from the enclosing scope. For example, compare: # example 1 def doit(): t_len = 42 def nested(): print t_len nested() doit() # will print 42 # example 2 def doit(): t_len = 42 def nested(): if t_len 0: print t_len else: t_len = 1 nested() doit() # will get referenced before assignment error You could make use of your WORK class here, depending on whether t_len makes sense as a member of the WORK class: class WORK: t_len = 0 def getwork(self): def formattable(table_to_process,type): # etc., etc. WORK.t_len = len(str(col)) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Xah's Edu Corner: Introduction to 3D Graphics Programing
Of Interest: Introduction to 3D Graphics Programing http://xahlee.org/3d/index.html Currently, this introduction introduces you to the graphics format of Mathematica, and two Java Applet utilities that allows you to view them with live rotation in a web browser. Also, it includes a introductory tutorial to POV-Ray. Once you understand any one of these pages, you can use your favorite programing language to start doing 3D Graphics Programing. In the coming months, i will also introduce the .obj format that are used by many geometric modeling programs. And, a tutorial on how to use Python (or Perl, lisp) to do 3D Graphics programing, by setting up functions that spits out any of 3D-Geometry Formats (such as Mathematica Graphics or POV-Ray or .inc). These are the imminent plans for the coming weeks. Other potential subjects are introduction or tutorials on various utilities or programing lang libraries that does conversion between different 3D graphics formats, dedicated tutorial on how to generate mathematical surfaces, more elaborate study on POV-Ray's abilities and sample cases, etc. The focus of these pages, will be 3D-Graphics programing with the goal of Algorithmic Mathematical Art. (see http://xahlee.org/Periodic_dosage_dir/t1/20040113_cmaci_larcu.html ) In particular, we focus on creating geometric objects and their arrangement that are esthetic in a mathematical way. (for example, regular tilings in 3D, nested structures in 3D, symmetric structures in 3D, elaborate 3D maze tunnels, beehive sculpting, regular polyhedrons and their decorations, projection and slices of higher dimensional symmetries, 3D-manifolds ... etc.) This mathematical esthetic is opposed to, for example, rendering techniques or technologies (e.g. fogs, sceneries, fast algorithms...etc) that are quite common in computer graphics literatures. Xah [EMAIL PROTECTED] ∑ http://xahlee.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: scopes of local and global variable
James Stroud [EMAIL PROTECTED] writes: #CODE## t_len=0 class WORK: def getwork(self): def formattable(table_to_process,type): TYPE=[p,t,T,s,i] #list of types to format if type==TYPE[1]: def format_t(): row=[] for col in table_to_process: ### # ERROR PRONE PART# ### if len(str(col))t_len: t_len=len(str(col)) ### # Error message says: # # UnboundLocalError: local variable 't_len' referenced before assignment# row+=col if (table_to_process.index(col)+1)%7==0: t_temp.append(row) row=[] format_t() # based on your advice i will try to answer my own questions: does class WORK inherit t_len=0 from line1? yes. does def getwork() inherit t_len=0 from line1? no. does def formattable(table_to_process,type) inherit t_len=0 from line1? no. does def format_t() inherit t_len=0 from line1? no. thank you kindly. -- http://mail.python.org/mailman/listinfo/python-list
Re: scopes of local and global variable
Pyenos wrote: does class WORK inherit t_len=0 from line1? does def getwork() inherit t_len=0 from line1? does def formattable(table_to_process,type) inherit t_len=0 from line1? does def format_t() inherit t_len=0 from line1? Not really, no. The global t_len is different than the local t_len--two variables with the same name. You need to declare global t_len inside your function so it knows that t_len=... is assigning to the old, global variable instead of creating a new one. See #6 here: http://zephyrfalcon.org/labs/python_pitfalls.html -Max -- http://mail.python.org/mailman/listinfo/python-list
Re: let me simplify my question on scope of vars
Pyenos [EMAIL PROTECTED] writes: i will try to answer my own questions(pls verify): code var=1 class CLASS: def METHOD1: def METHOD2: var+=var return var METHOD2() #line8 return var METHOD1() #line10 end code Q1: does class CLASS inherit var=0 from line1? yes. Q2: does def METHOD1 inherit var=0 from line1? no. Q3: does def METHOD2 inherit var=0 from line1? no. Q3: does line8 return '2'? no. will get unreferenced var error. Q4: does line10 return '2\n2'? no. will get unreferenced var error. -- http://mail.python.org/mailman/listinfo/python-list
Re: One module per class, bad idea?
At Friday 22/12/2006 20:25, Paddy wrote: Are there tools out their to help with the refactoring task of splitting a module into two or more sections then showing what other files need to change? Usually no other files need to change. Ex: you have BigOldModule including ClassA, ClassB and FunctionC. Move each one onto its own module, perhaps including a subset of the original imports of BigOldModule. Shrink BigOldModule to just: from ClassA import ClassA from ClassB import ClassB from functionC import functionC and maybe a few other things, so all imports from the outside remain the same. That's all - most of the time. -- Gabriel Genellina Softlab SRL __ Preguntá. Respondé. Descubrí. Todo lo que querías saber, y lo que ni imaginabas, está en Yahoo! Respuestas (Beta). ¡Probalo ya! http://www.yahoo.com.ar/respuestas -- http://mail.python.org/mailman/listinfo/python-list
Re: scopes of local and global variable
Max Wilson [EMAIL PROTECTED] writes: Pyenos wrote: does class WORK inherit t_len=0 from line1? does def getwork() inherit t_len=0 from line1? does def formattable(table_to_process,type) inherit t_len=0 from line1? does def format_t() inherit t_len=0 from line1? Not really, no. The global t_len is different than the local t_len--two variables with the same name. You need to declare global t_len inside your function so it knows that t_len=... is assigning to the old, global variable instead of creating a new one. See #6 here: http://zephyrfalcon.org/labs/python_pitfalls.html -Max so, based on your advice, i think the answers are all no. -- http://mail.python.org/mailman/listinfo/python-list
Re: let me simplify my question on scope of vars
Pyenos [EMAIL PROTECTED] writes: Pyenos [EMAIL PROTECTED] writes: i will try to answer my own questions(pls verify): code var=1 class CLASS: def METHOD1: def METHOD2: var+=var return var METHOD2() #line8 return var METHOD1() #line10 end code Q1: does class CLASS inherit var=0 from line1? yes. Q2: does def METHOD1 inherit var=0 from line1? no. Q3: does def METHOD2 inherit var=0 from line1? no. Q3: does line8 return '2'? no. will get unreferenced var error. Q4: does line10 return '2\n2'? no. will get unreferenced var error. Now I know that Q1 is also no, since var=1 from line 2 is a global variable and I have not declared it as global inside def METHOD2. so var within def METHOD2 is a different variable to the global variable var. -- http://mail.python.org/mailman/listinfo/python-list
Re: scopes of local and global variable
At Friday 22/12/2006 20:45, Pyenos wrote: # Error message says: # # UnboundLocalError: local variable 't_len' referenced before assignment# See item 6 in 10 Python pitfalls: http://zephyrfalcon.org/labs/python_pitfalls.html -- Gabriel Genellina Softlab SRL __ Preguntá. Respondé. Descubrí. Todo lo que querías saber, y lo que ni imaginabas, está en Yahoo! Respuestas (Beta). ¡Probalo ya! http://www.yahoo.com.ar/respuestas -- http://mail.python.org/mailman/listinfo/python-list
Re: let me simplify my question on scope of vars
At Friday 22/12/2006 22:24, Pyenos wrote: code var=1 class CLASS: def METHOD1: def METHOD2: var+=var return var METHOD2() #line8 return var METHOD1() #line10 end code Q1: does class CLASS inherit var=0 from line1? yes. Q2: does def METHOD1 inherit var=0 from line1? no. Q3: does def METHOD2 inherit var=0 from line1? no. Q3: does line8 return '2'? no. will get unreferenced var error. Q4: does line10 return '2\n2'? no. will get unreferenced var error. Now I know that Q1 is also no, since var=1 from line 2 is a global variable and I have not declared it as global inside def METHOD2. so var within def METHOD2 is a different variable to the global variable var. Read the Python Pitfalls I've send some minutes ago, and the tutorial (specially http://docs.python.org/tut/node11.html#scopes) and then re-answer your own questions. -- Gabriel Genellina Softlab SRL __ Preguntá. Respondé. Descubrí. Todo lo que querías saber, y lo que ni imaginabas, está en Yahoo! Respuestas (Beta). ¡Probalo ya! http://www.yahoo.com.ar/respuestas -- http://mail.python.org/mailman/listinfo/python-list
Re: One module per class, bad idea?
Paddy wrote: Carl Banks wrote: Erik Johnson wrote: The file has now grown into a 6800 line beast (including docstring, whitespace, and CVS history). Pretty much any time we implement some new functionality, there are at least a few changes in that file. When you have multiple developers working on different projects, and they all need to be making changes to that file, the chances for someone making a merge error goes up. So, we are obviously at a point where that file needs to be split up, but there are lots of other files that import and use the one file, so it is a task that has been put off. In retrospect, I wish I has started things under a one class per file strategy, but at the time, it didn't make a lot of sense to split those things up and I didn't anticipate the code getting that big. Refactor NOW. Are there tools out their to help with the refactoring task of splitting a module into two or more sections then showing what other files need to change? I don't know what spiffy tools there are. If all I'm doing is moving a class from one module to another, then a simple interactive search and replace suffices for me; I modify import lines by hand. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Retrieve Tkinter listbox item by string, not by index
Kevin Walzer wrote: I'm trying to set the active item in a Tkinter listbox to my application's currently-defined default font. Here's how I get the fonts loaded into the listbox: self.fonts=list(tkFont.families()) self.fonts.sort() for item in self.fonts: self.fontlist.insert(END, item) #self.fontlist is the ListBox instance So far, so good. But I don't know how to set the active selection in the listbox to the default font. All the methods for getting or setting a selection in the listbox are based on index, not a string. And using standard list search methods like this: if Courier in self.fontlist: print list contains, value else: print value, not found returns an error: TypeError: cannot concatenate 'str' and 'int' objects So I'm stuck. Can someone point me in the right direction? I would keep a separate data structure for the fonts and update the scrollbar when the list changed. This would help to separate the representation from the data represented. Here is a pattern I have found most useful and easy to maintain: # untested class FontList(Frame): def __init__(self, *args, **kwargs): Frame.__init__(self, *args, **kwargs) self.pack() self.fonts = list(kwargs['fonts']) self.default = self.fonts.index(kwargs['default_font']) self.lb = Listbox(self) # add scrollbar for self.lb, pack scrollbar # pack self.lb self.set_bindings() self.update() def set_bindings(self): # put your bindings and behavior here for FontList components def update(self): self.lb.delete(0, END) for f in self.fonts: self.lb.insert(f) self.highlight() def highlight(self): index = self.default self.lb.see(index) self.lb.select_clear() self.lb.select_adjust(index) self.lb.activate(index) def change_font(self, fontname): self.default = self.fonts.index(fontname) self.highlight() def add_font(self, fontname, index=None): if index is None: self.fonts.append(fontname) else: self.fonts.insert(index, fontname) self.update() # other methods for adding multiple fonts or removing them, etc. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: One module per class, bad idea?
Gabriel Genellina wrote: At Friday 22/12/2006 20:25, Paddy wrote: Are there tools out their to help with the refactoring task of splitting a module into two or more sections then showing what other files need to change? Usually no other files need to change. Ex: you have BigOldModule including ClassA, ClassB and FunctionC. Move each one onto its own module, perhaps including a subset of the original imports of BigOldModule. Shrink BigOldModule to just: from ClassA import ClassA from ClassB import ClassB from functionC import functionC and maybe a few other things, so all imports from the outside remain the same. That's all - most of the time. I wouldn't recommend this unless it's important not to change the external usage. If you're doing it just to save work in refactoring, it's a partial solution hack that'll lead to more confusion and delay a real solution even more. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Refactoring between files (was: One module per class, bad idea?)
Paddy [EMAIL PROTECTED] writes: Are there tools out their to help with the refactoring task of splitting a module into two or more sections then showing what other files need to change? Sounds like a good feature to add to Bicycle Repair Man: URL:http://bicyclerepair.sourceforge.net/ -- \ Q: I've heard that Linux causes cancer... Torvalds: That's | `\ a filthy lie. Besides, it was only in rats and has not been | _o__)reproduced in humans. -- Linus Torvalds | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Retrieve Tkinter listbox item by string, not by index
James Stroud wrote: Kevin Walzer wrote: I'm trying to set the active item in a Tkinter listbox to my application's currently-defined default font. Here's how I get the fonts loaded into the listbox: self.fonts=list(tkFont.families()) self.fonts.sort() for item in self.fonts: self.fontlist.insert(END, item) #self.fontlist is the ListBox instance So far, so good. But I don't know how to set the active selection in the listbox to the default font. All the methods for getting or setting a selection in the listbox are based on index, not a string. And using standard list search methods like this: if Courier in self.fontlist: print list contains, value else: print value, not found returns an error: TypeError: cannot concatenate 'str' and 'int' objects So I'm stuck. Can someone point me in the right direction? I would keep a separate data structure for the fonts and update the scrollbar when the list changed. This would help to separate the representation from the data represented. Here is a pattern I have found most useful and easy to maintain: # untested class FontList(Frame): def __init__(self, *args, **kwargs): Frame.__init__(self, *args, **kwargs) self.pack() self.fonts = list(kwargs['fonts']) self.default = self.fonts.index(kwargs['default_font']) self.lb = Listbox(self) # add scrollbar for self.lb, pack scrollbar # pack self.lb self.set_bindings() self.update() def set_bindings(self): # put your bindings and behavior here for FontList components def update(self): self.lb.delete(0, END) for f in self.fonts: self.lb.insert(f) self.highlight() def highlight(self): index = self.default self.lb.see(index) self.lb.select_clear() self.lb.select_adjust(index) self.lb.activate(index) def change_font(self, fontname): self.default = self.fonts.index(fontname) self.highlight() def add_font(self, fontname, index=None): if index is None: self.fonts.append(fontname) else: self.fonts.insert(index, fontname) self.update() # other methods for adding multiple fonts or removing them, etc. I overlooked that you will actually want to remove fonts and default_fonts from kwargs before initializing with Frame: # untested class FontList(Frame): def __init__(self, *args, **kwargs): self.fonts = list(kwargs['fonts']) self.default = self.fonts.index(kwargs['default_font']) kwargs.pop('fonts') kwargs.pop('default_font') Frame.__init__(self, *args, **kwargs) self.pack() self.lb = Listbox(self): # etc. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
pyparsing announcement?
I have tried a couple of times now to post an announcement of the latest version of pyparsing, but it does not seem to be making it past the news server, neither through my local ISP's server nor through GoogleGroups. Could it be because I am also posting to comp.lang.python.announce, and this moderated group is holding up posts to all groups? (Doesn't really make sense to me, but it's all I can come up with.) Or is the announcement getting out, and my newsreader just not showing it for some reason? -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: attribute decorators
Gert Cuykens [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | would it not be nice if you could assign decorators to attributes too ? | for example | | class C: |@staticattribute |data='hello' | | or | | class C: |@privateattribute |data='hello' No. @g def f(): pass is equivalent to and an abbreviation fo def f(): pass f = g(f) The rationale for the abbreviation is 1. let the human reader know immediately that the function will get special treatment 2. (related) put the notation about the function at the top with other header stuff 3. avoid retyping really_long_function_names three times (and there are uses of Python where long, multicomponent names are sensible and useful). But nothing is gained and something is lost by writing clear code like data = staticattribute('hello') # or privateattribute('hello') in two lines. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list