Re: changing local namespace of a function
Bo Peng wrote: By the way, will 'with statement', like the one in pascal and many other languages, be a good addition to python? For example, with d do: z = x + y would be equivalent to d['z']=d['x']+d['y'] or d.z = d.x + d.y in some other cases. This would absolutely be the *best* solution to my problem. Bo Guido van Rossum has stated that he wants Python to eventually have a 'with' statement of the form: with d: .z = .x + .y (The leading '.' being required to avoid ambiguity in name lookups) Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
RE: "Collapsing" a list into a list of changes
It's not _exactly_ what you asked for but it may be enough... Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from sets import Set >>> l = [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5] >>> s = Set(l) >>> s Set([0, 1, 2, 3, 4, 5]) >>> l2 = list(s) >>> l2 [0, 1, 2, 3, 4, 5] >>> I say it's not exactly what you wanted because I don't think the ordering of l2 is necessarily the same as l. That may or may not be a problem for you. Regards Steve > -Original Message- > From: Alan McIntyre [mailto:[EMAIL PROTECTED] > Sent: 04 February 2005 17:44 > To: python-list@python.org > Subject: "Collapsing" a list into a list of changes > > Hi all, > > I have a list of items that has contiguous repetitions of > values, but the number and location of the repetitions is not > important, so I just need to strip them out. For example, if > my original list is [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5], I > want to end up with [0,1,2,3,2,4,5]. > > Here is the way I'm doing this now: > > def straightforward_collapse(myList): > collapsed = [myList[0]] > for n in myList[1:]: > if n != collapsed[-1]: > collapsed.append(n) > > return collapsed > > Is there an elegant way to do this, or should I just stick > with the code above? > > Thanks, > Alan McIntyre > http://www.esrgtech.com > > ** The information contained in, or attached to, this e-mail, may contain confidential information and is intended solely for the use of the individual or entity to whom they are addressed and may be subject to legal privilege. If you have received this e-mail in error you should notify the sender immediately by reply e-mail, delete the message from your system and notify your system manager. Please do not copy it for any purpose, or disclose its contents to any other person. The views or opinions presented in this e-mail are solely those of the author and do not necessarily represent those of the company. The recipient should check this e-mail and any attachments for the presence of viruses. The company accepts no liability for any damage caused, directly or indirectly, by any virus transmitted in this email. ** -- http://mail.python.org/mailman/listinfo/python-list
Re: PythonWin and PyWin32
Chris Lott wrote: Can someone elaborate for me what the pywin32 project is exactly? Is PythonWin a replacement for idle? More to the point, do I need to worry about this as I am learning about Python, since Idle and the Windows Installer seem to work fine on my XP box? Python and IDLE work fine on Windows. pywin32 is about better support for Windows specific idioms (e.g. easier COM support, more convenient registry access). Pythonwin is a windows native Python IDE built using MFC. Idle uses TKinter and doesn't really feel like a standard Windows app. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: who can tell me BASICS of Python
Troll ? -- http://mail.python.org/mailman/listinfo/python-list
Re: changing local namespace of a function
Bo Peng wrote: I guess I will go with solution 3. It is evil but it is most close to my original intention. It leads to most readable code (except for the first line to do the magic and the last line to return result) and fastest performance. Thousands of programs use Python's class attribute access syntax day-in and day-out and find the performance to be acceptable. Premature optimization is the root of much evil - the exec + locals() hack if very dependent on the exact Python version you are using. Expect some hard to find bugs if you actually use the hack. And code which relies on an evil hack in order to have the desired effect doesn't count as readable in my book - I would be very surprised if many people reading your code knew that updates to locals() can sometimes be made to work by performing them inside a bare exec statement. Thank again for everyone's help. I have learned a lot from the posts, especially the wrapdict class. It sounds like the dictionaries you are working with actually have some meaningful content that you want to manipulate. I'd seriously suggest creating a class which is able to extract the relevant data from the dictionaries, supports the desired manipulations, and then be instructed to update the original dictionaries. For example, an approach based on Michael's dictionary wrapper class class DataAccessor(object): # Just a different name for Michael's "wrapbigdict" def __init__(self, data): object.__setattr__(self, "_data", data) def __getattr__(self, attrname): return self._data[attrname] def __setattr__(self, attrname, value): self._data[attrname] = value class DataManipulator(DataAccessor): def __init__(self, data): DataAccessor.__init__(self, data) def calc_z(self): self.z = self.x + self.y In action: Py> data = DataManipulator(dict(x=1, y=2)) Py> data.z Traceback (most recent call last): File "", line 1, in ? File "", line 6, in __getattr__ KeyError: 'z' Py> data.calc_z() Py> data.z 3 Py> data._data {'y': 2, 'x': 1, 'z': 3} The class based approach also gives you access to properties, which can be used to make that first call to 'z' automatically calculate the desired result instead of giving a KeyError: class EnhancedDataManipulator(DataAccessor): def __init__(self, data): DataAccessor.__init__(self, data) class _utils(object): @staticmethod def make_prop(name, calculator): def get(self, _name=name, _calculator=calculator): try: return self._data[_name] except KeyError: val = _calculator(self) self._data[_name] = val return val def set(self, val, _name=name): self._data[_name] = val def delete(self, _name=name): del self._data[_name] return property(get, set, delete) @staticmethod def calc_z(self): return self.x + self.y z = _utils.make_prop('z', _utils.calc_z) Note the nested _utils class isn't strictly necessary. I just like to use it to separate out the information which the class uses to construct itself from those which are provided to clients of the class. Anyway, the enhanced version in action: Py> data = EnhancedDataManipulator(dict(x=1,y=2)) Py> data.x 1 Py> data.y 2 Py> data.z 3 Py> data.x = 30 Py> data.z 3 Py> data.z = 10 Py> data.z 10 Py> del data.z Py> data.z 32 If you want to add more calculated properties to the data manipulator, simply define additional calculator methods, and define the attribute with make_prop. Use a class. Giving meaningful form to a collection of attributes is what they're for, and Python provides many features designed to make that process easier. Trying to fake it with function namespaces is just going to make trouble for you in the future. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: returning True, False or None
On Fri, 04 Feb 2005 13:04:16 -0500, rumours say that Steve Holden <[EMAIL PROTECTED]> might have written: [STeVe] >> For a given list: >> * If all values are None, the function should return None. >> * If at least one value is True, the function should return True. >> * Otherwise, the function should return False. [Stevbe] >If you wanted to get clever you could write something like > >for i in True, False: > if i in lst: > return i >return False [!Steve] You mistyped None as False in the last line. Your typos are getting worse every day :) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: empty classes as c structs?
Steven Bethard wrote: Yes -- help me rally behind my generic object PEP which proposes a Bunch type (probably to be renamed) for the Python standard lib. =) Did you see the suggestion of 'namespace' as a name? Given that the idea is to get access to the contents using the standard Python syntax for accessing module and class namespaces, it seems to make sense. Michael Spencer also posted an interesting idea recently about setting up a view of an existing dictionary, rather than as a separate object: class attr_view(object): def __init__(self, data): object.__setattr__(self, "_data", data) def __getattr__(self, attrname): return self._data[attrname] def __setattr__(self, attrname, value): self._data[attrname] = value Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: executing VBScript from Python and vice versa
Cool. :-) And it's OK, also, for JScript (MS-Javascript) : import win32com.client vbs = win32com.client.Dispatch("ScriptControl") vbs.language = "vbscript" scode="""Function mul2(x) mul2=x*2 End Function """ vbs.addcode(scode) print vbs.eval("mul2(123)") js = win32com.client.Dispatch("ScriptControl") js.language = "jscript" scode="""function mul3(x){ vret=x*3; return(vret); } function mul4(x){ vret=x*4; return(vret); } """ js.addcode(scode) print js.eval("mul3(123);") print js.eval("mul4(121);") @-salutations -- Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: changing local namespace of a function
Bo Peng <[EMAIL PROTECTED]> wrote: ... > Thank again for everyone's help. I have learned a lot from the posts, > especially the wrapdict class. Hmmm, you do realize that wrapdict uses a lot of indirection while my equivalent approach, just posted, is very direct, right? To reiterate the latter, and dress it up nicely too, it's class wrapwell(object): def __init__(self, somedict): self.__dict__ = somedict and use d=wrapwell(whateverdict) to make the wrapper. Now, reading or writing d.x is just like reading or writing whateverdict['x'], etc etc. Alex -- http://mail.python.org/mailman/listinfo/python-list
Python Processes for Win32
I have a daemon type script (daemon.py -- we'll say) that I would like to have run continuously. I'd like to be able to do something like this: daemon.py start ... and then to have it stop I'd like to do this: daemon.py stop I am having a hard time googling for a clue as to how to accomplish this. If anyone can point me in the right direction, I'd really appreciate it. thanks, Harlin -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
On Mon, 31 Jan 2005 18:49:15 +0100, Alex Martelli <[EMAIL PROTECTED]> wrote: > Michael Tobis <[EMAIL PROTECTED]> wrote: > >> With all due respect, I think "so go away if you don't like it" is >> excessive, and "so go away if you don't like it and you obviously don't >> like it so definitely go away" is more so. The writer is obviously > > I disagree: I believe that, if the poster really meant what he wrote, he > may well be happier using other languages and all the declarations he > cherishes, so recommending that course of action to him is quite proper > on my part. You are wrong, for once. That poster could have been me a few years back, when I was younger, more stupid, more arrogant and less experienced. He'll get over it. Also, what he described /is/ a problem. I still get bitten by it now and then. It's just that it has even larger /benefits/ which aren't obvious at first. In BASIC, /bin/sh and perl without 'use strict', the lack of declarations is only a negative thing without benefits. If you know those languages, it's easy to jump to the conclusion that this applies to Python, too. /Jorgen -- // Jorgen GrahnR'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: why are LAMP sites slow?
> > The server is slow to respond to requests. Browser rendering is > > independent of the server architecture and "slow to be fetched from > > the server" sounds like it means low network speed. I'm talking > about > > the very familiar experience of clicking a link and then waiting, > > waiting, waiting for the page to load. You rarely see that happen > > with Ebay or Google. It happens all the time with Wikipedia. > > This has a lot to do with the latency and speed of the connecting > network. Sites like Ebay, Google, and Amazon are connected > to internet backbone nodes (for speed) and are cached throughout > the network using things like Akami (to reduce latency)... Akami for services, or better yet, cacheing hardware such as NetCache. Frequently requested data doesn't even have to come from the server disks/database - it's sent from the NetCache. -- http://mail.python.org/mailman/listinfo/python-list
Re: empty classes as c structs?
Nick Coghlan <[EMAIL PROTECTED]> wrote: ... > Michael Spencer also posted an interesting idea recently about setting up > a view of an existing dictionary, rather than as a separate object: > > class attr_view(object): >def __init__(self, data): > object.__setattr__(self, "_data", data) >def __getattr__(self, attrname): > return self._data[attrname] >def __setattr__(self, attrname, value): > self._data[attrname] = value Wasted indirection, IMHO. A better implementation: class attr_view(object): def __init__(self, data): self.__dict__ = data Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
Have a gander at Boa Constructor. YOu can certainly go to a shell when debugging. (ie set breakpoint) then the shell is attached to that context. T Ashot wrote: This is sort of both Python and Vim related (which is why I've posted to both newsgroups). Python related: -- I have been frustrated for quite some time with a lack of a history command in IDLE (in fact with IDLE in general). Often I'll develop new code at the command line, testing each line as I go. Currently I have to copy and paste, removing outputs and the ">>>" at each line. Is it perhaps possible to make some kind of hack to do this (dump a command history)? Idle in general isn't that great IMO, so I was wondering also if there are better alternatives out there? What do people use mostly? I've tried something called pyCrust, but this too didn't have history and some other things I was looking for. On a more general note, although the agility and simplicity of Python make programming tools like an IDE less necessary, it still seems that Python is lacking in this departement. The PyDev plug-in for Eclipse seems like good step in this direction, although I haven't tried it yet. Does anyone have any experience with this, or perhaps can point me to other tools. Vim related: -- Ideally, it would be nice to have a command mapped to a keystroke that can append the last executed command to a file. Even better would be a system that would integrate the file editing and interactive command line tool more seamlessly. Something along the lines of a debugger + file editor + command line utility, where file editor = vim. I know that vim has a utility for running python commands from its command prompt, but I have had a hard time getting this to work in windows and haven't explored it. Has anyone seen/tried a system along these lines, perhaps incorporating the python debugger (pdb)? I can see something that will run the file you are editing in vim up to the cursor or a mark with a set_trace at the line you are editing. Any info is appreciated, thanks. -- Ashot Petrosian University of Texas at Austin, Computer Sciences -- http://mail.python.org/mailman/listinfo/python-list
Re: FW: executing VBScript from Python and vice versa
PythonWin 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2004 Mark Hammond ([EMAIL PROTECTED]) - see 'Help/About PythonWin' for further copyright information. >>> from win32com.client import Dispatch >>> x = Dispatch("MSScriptControl.ScriptControl") >>> x.Language='VBScript' >>> x.AddCode("""Function HelloWorld ... HelloWorld = "hello world" ... End Function ... """) >>> >>> x.Eval("HelloWorld") u'hello world' >>> Valentina Boycheva wrote: Thanks for the reply. I already have "Learning Python" from Mark Lutz and David Ascher, which covers 2.3 (I am in 2.4). However, it seems like heavy artillery to me. What I want is, for instance, run a VBScript to get a function output and feed it to the Python script that called it. The reason is that because I feel more comfortable with VBScript and have written a small library of useful utilities, I don't want it to become obsolete. In the mean time I did more reading and found a couple of prospective alternatives - popen and os.system(command). Still need to work out how to use them... -Original Message- From: aurora [mailto:[EMAIL PROTECTED] Sent: Friday, February 04, 2005 3:28 PM To: python-list@python.org Subject: Re: executing VBScript from Python and vice versa Go to the bookstore and get a copy of Python Programming on Win32 by Mark Hammond, Andy Robinson today. http://www.oreilly.com/catalog/pythonwin32/ It has everything you need. Is there a way to make programs written in these two languages communicate with each other? I am pretty sure that VBScript can access a Python script because Python is COM compliant. On the other hand, Python might be able to call a VBScript through WSH. Can somebody provide a simple example? I have exactly 4 days of experience in Python (and fortunately, much more in VB6) Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: "Collapsing" a list into a list of changes
Steven Bethard <[EMAIL PROTECTED]> wrote: > Here's a solution that works for iterables other than lists: > > py> def collapse(iterable): > ... enumeration = enumerate(iterable) > ... _, lastitem = enumeration.next() > ... yield lastitem > ... for i, item in enumeration: > ... if item != lastitem: > ... yield item > ... lastitem = item > ... > py> lst = [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5] > py> list(collapse(lst)) > [0, 1, 2, 3, 2, 4, 5] > > Again, I'm still not sure I'd call this more elegant... H, what role does the enumeration play here? I don't see how you're using it, at all. Why not just: def collapse(iterable): it = iter(iterable) lastitem = it.next() yield lastitem for item in it: if item != lastitem: yield item lastitem = item that's basically just the same as your code but without the strangeness of making an enumerate for the purpose of ignoring what the enumerate adds to an ordinary iterator. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: how to send an int over a socket
On 04 Feb 2005 19:24:29 -0800, Paul Rubin <> wrote: > Tom Brown <[EMAIL PROTECTED]> writes: ... > Why don't you look at the struct module instead. You could also look > the xdr or xmlrpc libraries, which may be closer to what you want. Or look at existing, successful standards like HTTP, SMTP, etc. Most of them are text-based -- which wastes a small bit of bandwidth and CPU cycles, but helps debugging and interoperability a lot. The xdr module which P.R. refers to implements a simple, standard way of passing binary datatypes over a network, and is available everywhere, for all languages. Don't know anything about xmlrpc, except that it is magnitudes more complex and powerful. /Jorgen -- // Jorgen GrahnR'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
a type without a __mro__?
Can anybody suggest where to find (within the standard library) or how to easily make (e.g. in a C extension) a type without a __mro__, except for those (such as types.InstanceType) which are explicitly recorded in the dispatch table copy._deepcopy_dispatch...? Weird request, I know, so let me explain. There's a bug in the forthcoming 2.3.5's copy.py which can be tickled only by such a type. Fixing the bug is trivially easy (I'll just use inspect.getmro(cls) instead of cls.__mro__), but I also want to add to test_copy.py a unit test that tickles the bug, rather than just commit an ``untested fix''. I'm stumped at finding a type that's suitable for reproducing the bug; I've asked the submitter of the original bug report (which comes up with Zope and some specific application -- unsuitable for a core python unit test, sigh), I've asked on python-dev, I've even IM'd a couple of Python-guru friends, but the friends are equally stumped and I'm getting no answers on python-dev nor from the submitter of the bug report. So, I thought I'd turn to the collective ingenuity of comp.lang.python... thanks in advance for any help! Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: changing local namespace of a function
Bo Peng <[EMAIL PROTECTED]> wrote: > M.E.Farmer wrote: > > I really don't see your need. > > Maybe it is just my laziness. It is almost intolerable for me to write > lines and lines of code like > >d['z'] = func(d['x']+d['y']+d['whatever']['as']+d[a][0] ) > > It is ugly, unreadable and error prone. If I have to use this code, I > would write > >_z = func(_x + _y + _whatever['as'] + _a[0]) So, what about having as the real code d.z = func(d.x + d.y + d.whatever['as'] + d.a[0]) Doesn't seem too different from what you would write, would it? To wrap a dictionary into an object whose attributes are mapped to items of the dictionary is not hard: just start your function with d = type('wrapadict', (), {})() d.__dict__ = the_dict_to_wrap and there you are. Affecting *BARE* names is a completely different order of magnitude of complication away from affecting *COMPOUND* names. Barenames are, almost inevitably, handled with deep magic, essentially for the purposes of can't-do-without optimization; compound names are _way_ more malleable... Alex -- http://mail.python.org/mailman/listinfo/python-list
variable declaration
Hi Paddy! 03 Feb 2005 at 21:58, Paddy McCarthy wrote: >> Explicit' keyword! May be, python also have such a feature, I just >> don't know about it? Alexander, [EMAIL PROTECTED] PM> Advocates always say Type Checking, but so often it seems like Type PM> Constriction. - To hell with it! PM> I don't believe I would be more productive by cluttering Python with PM> the Type schemes and variable declarations found in languages like PM> Pascal, C, Basic, C++ and Java. People have said that there may be a PM> more intelligent way, maybe type inferencing? But no, please, nothing PM> like the above, it would just get in the way. No, I don't even think about compulsory type checking, and so on. I just want something like this: var epsilon=0 var S S=0 while epsilon<10: S=S+epsilon epselon=epsilon+1#interpreter should show error here,if it's in "strict mode" print S It is easy, and clean-looking. Alexander, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
variable declaration
Привет Peter! 31 января 2005 в 09:09, Peter Otten в своем письме к All писал: PO> pychecker may help you find misspelled variable names. You have to PO> move the code into a function, though: PO> $ cat epsilon.py ...skipped... PO> $ pychecker epsilon.py PO> epsilon.py:6: Local variable (epselon) not used Well, I can change it a little to pass this check. Just add "print epselon" line. I think if as soon as I will make such error, I will write special checker. It will take code like this: def loop(): #var S,epsilon epsilon=0 S=0 while epsilon<10: S=S+epsilon epselon=epsilon+1 print S Such checker will say "error:epselon is not declared!" if I will use something not declared. If everything is ok, it will call pychecker. Simple and tasty, isn't it? Of cource, it may be difficult to handle fields of classes: MyClass.epsElon=MyClass.epsilon+1 but it is solvable, I think. What do you think, is it a good idea? Alexander, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
An interesting python problem using Zope 2.7.3
Greetings!!! I ran the following simple string commands in Linux + Python and the results are: [EMAIL PROTECTED] root]# python Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> "A" 'A' >>> "A/" 'A/' >>> "A" 'A' >>> Now when the same is run from Zope273 + python + Linux or windows, the results are, 1. 'A' 2. A/ 3. A respectively. Any suggestions? thanx -- http://mail.python.org/mailman/listinfo/python-list
Re: returning True, False or None
Brian van den Broek <[EMAIL PROTECTED]> wrote: ... > >>* If all values are None, the function should return None. > >>* If at least one value is True, the function should return True. > >>* Otherwise, the function should return False. ... > > for val in (x for x in lst if x is not None): > > return val > > return None ... > These don't do what the OP desired. Ah, you're right, True should take precedence, point 2 of the specs. OK, let's take advantage of the fact that None < False < True: return max(lst) This fails when lst is empty (the specs presumably imply a None should be returned then). More robust: return max(lst or [None]) Alex -- http://mail.python.org/mailman/listinfo/python-list
variable declaration
Hi, Alex! 31 jan 2005 at 13:46, Alex Martelli wrote: (sorry for the delay,my mail client don't highlight me your answer) AM> Since the lack of declarations is such a crucial design choice for AM> Python, then, given that you're convinced it's a very bad thing, I AM> suggest you give up Python in favor of other languages that give you AM> what you crave. Well, I like Python. But, as every language I know, it have some bad sides which I don't like. One of them in Python is lack of variable declarations, another (this problem is common with C/C++) is: === >>>print 1/2 0 === (I understand why it is so, but I don't like it anyway. Such behaviour also can cause some hard-to-find-bugs) AM> issue for you. Therefore, using Python, for you, would mean you'd be AM> fighting the language and detesting its most fundamental design AM> choice: and why should you do that? There are zillions of languages AM> -- use another one. Thank you for advice:) >> Pascal, or special syntax in C. It can cause very ugly errors,like >> this: epsilon=0 S=0 while epsilon<10: S=S+epsilon >> epselon=epsilon+1 print S It will print zero, and it is not easy to >> find such a bug! AM> Actually, this while loop never terminates and never prints anything, Oh, I don't find it:) AM> so that's gonna be pretty hard to ignore;-). AM> But, assume the code is AM> slightly changed so that the loop does terminate. In that case...: AM> It's absolutely trivial to find this bug, if you write even the AM> tiniest and most trivial kinds of unit tests. If you don't even have AM> enough unit tests to make it trivial to find this bug, I shudder to AM> think at the quality of the programs you code. Thank you for advice again, I already use different tests in my work and I found them usefull. But! I want to use Python for prototyping. I want to write my algorithms on it, just to see they do almost they must to do. Next, I want to play with them to understand their properties and limitations. If sometimes such a program fall, or not very fast, or sometimes show wrong results, it's not a big problem. So, I use Python like tool for prototyping. After I debug the algorithm and understand it, I can rewrite it on C++ (if I need), carefully, paying attention to speed, side effects, memory requirements, and so on. With full testing, of course. Hence, from "language for prototyping" I need next features: 1. I want to think about algorithm (!!!), and language must help me to do it. It must take care on boring things like memory management, garbage collection, strict type inference, my typos. It must provide easy-to-use packages for many of my low-level needs. And so on. 2. goto 1:) Python is realy very good for such demands. Except one: it force me to type variable names carefully:) In other words, divert my attraction from algorithm, to typing. AM> Even just focusing on AM> typos, AM> think of how many other typos you could have, besides the misspelling AM> of 'epsilon', that unit tests would catch trivially AND would be AM> caught in no other way whatsoever -- there might be a <= where you AM> meant a <, a 1.0 where you meant 10, a - where you meant a +, etc, AM> etc. AM> You can't live without unit tests. And once you have unit tests, the AM> added value of declarations is tiny, and their cost remains. Fine! Let interpreter never show us errors like division by zero, syntax errors, and so on. If file not found, library don't need to say it. Just skip it!!! Because every, even simple, test will find such bugs. Once you have unit tests, the added value of is tiny, and their cost remains. :) Or, maybe, we will ask interpreter to find and prevent as many errors as he can? And, one more question: do you think code like this: var S=0 var eps for eps in xrange(10): S=S+ups is very bad? Please explain your answer:) AM> Python has no declarations whatsoever. If you prefer Visual Basic, I AM> strongly suggest you use Visual Basic, rather than pining for Visual AM> Basic features in Python. If and when your programming practices ever AM> grow to include extensive unit-testing and other aspects of agile AM> programing, THEN you will be best advised to have a second look at AM> Python, and in such a case you will probably find Python's strengths, AM> including the lack of declarations, quite compelling. Uh! And you! And you!... And you must never even come close to any languages with variable declaration! Even to Visual Basic! :) AM> brain". I find it's true: Python gets out of my way and let me solve AM> problems much faster, because it fits my brain, rather than changing AM> the way I think. I'm agree with you. AM> If Python doesn't fit YOUR brain, for example because your brain is AM> ossified around a craving for the declaration of variables, then, AM> unless you're specifically studying a new language just for personal AM> growth purposes, I think you might well be better off with a language AM> t
sos!
hellow everybody! I'm from china. I'm a beginner of python. in china, python is not a fashionable language, so it's difficult to find some books about python. finally,I find a book named "python how to program" wrote by H.M.Deitel . who can tell me where can I find some interesting source code about python. otherwise, I will fell boring about study! -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
Alexander Zatvornitskiy <[EMAIL PROTECTED]> wrote: > Hi, Alex! > > 31 jan 2005 at 13:46, Alex Martelli wrote: > > (sorry for the delay,my mail client don't highlight me your answer) > > AM> Since the lack of declarations is such a crucial design choice for > AM> Python, then, given that you're convinced it's a very bad thing, I > AM> suggest you give up Python in favor of other languages that give you > AM> what you crave. > Well, I like Python. But, as every language I know, it have some bad sides > which I don't like. One of them in Python is lack of variable declarations, > another (this problem is common with C/C++) is: > === > >>>print 1/2 > 0 > === > (I understand why it is so, but I don't like it anyway. Such behaviour > also can cause some hard-to-find-bugs) You're conflating a fundamental, crucial language design choice, with a rather accidental detail that's already acknowledged to be suboptimal and is already being fixed (taking years to get fixed, of course, because Python is always very careful to keep backwards compatibility). Run Python with -Qnew to get the division behavior you probably want, or -Qwarn to just get a warning for each use of integer division so those hard to find bugs become trivially easy to find. Or import from the future, etc, etc. The fact that in Python there are ONLY statements, NO declarations, is a completely different LEVEL of issue -- a totally deliberate design choice taken in full awareness of all of its implications. I do not see how you could be happy using Python if you think it went wrong in such absolutely crucial design choices. > AM> issue for you. Therefore, using Python, for you, would mean you'd be > AM> fighting the language and detesting its most fundamental design > AM> choice: and why should you do that? There are zillions of languages > AM> -- use another one. > Thank you for advice:) You're welcome. > >> Pascal, or special syntax in C. It can cause very ugly errors,like > >> this: epsilon=0 S=0 while epsilon<10: S=S+epsilon > >> epselon=epsilon+1 print S It will print zero, and it is not easy to > >> find such a bug! > AM> Actually, this while loop never terminates and never prints anything, > Oh, I don't find it:) Hit control-C (or control-Break or whatever other key combination interrupts a program on your machine) when the program is just hanging there forever doing nothing, and Python will offer a traceback showing exactly where the program was stuck. In any case, you assertion that "it will print zero" is false. You either made it without any checking, or chose to deliberately lie (in a rather stupid way, because it's such an easy lie to recognize as such). > Fine! Let interpreter never show us errors like division by zero, syntax > errors, and so on. If file not found, library don't need to say it. Just skip > it!!! Because every, even simple, test will find such bugs. Once you have unit > tests, the added value of is tiny, and their cost remains. Another false assertion, and a particularly ill-considered one in ALL respects. Presence and absence of files, for example, is an environmental issue, notoriously hard to verify precisely with unit tests. Therefore, asserting that "every, even simple, test will find" bugs connected with program behavior when a file is missing shows either that you're totally ignorant about unit tests (and yet so arrogant to not let your ignorance stop you from making false unqualified assertions), or shamelessly lying. Moreover, there IS no substantial cost connected with having the library raise an exception as the way to point out that a file is missing, for example. It's a vastly superior approach to the old idea of "returning error codes" and forcing the programmer to check for those at every step. If the alternative you propose is not to offer ANY indication of whether a file is missing or present, then the cost of THAT alternative would most obviously be grievous -- essentially making it impossible to write correct programs, or forcing huge redundancy if the check for file presence must always be performed before attempting I/O. In brief: you're not just wrong, you're so totally, incredibly, utterly and irredeemably wrong that it's not even funny. > And, one more question: do you think code like this: > > var S=0 > var eps > > for eps in xrange(10): > S=S+ups > > is very bad? Please explain your answer:) Yes, the many wasted pixels in those idiotic 'var ' prefixes are a total and utter waste of programmer time. Mandated redundancy, the very opposite of the spirit of Python. > Uh! And you! And you!... And you must never even come close to any languages > with variable declaration! Even to Visual Basic! :) Wrong again. I've made a good living for years as a C++ guru, I still cover the role of C++ MVP for the Brainbench company, I'm (obviously) totally fluent in C (otherwise I could hardly contribute to the development of Python's C-coded infrastructure, now
Re: Error!
"John Machin" <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>... > administrata wrote: > > I'm programming Car Salesman Program. > > It's been "3 days" learning python... > > >From whom or what book or what tutorial? > > > But, i got problem > > You got problemS. What Jeff & Brian wrote, plus: > > You have "change" instead of "charge". > > You forgot to add in the base price -- "actual price" according to you > comprises only the taxes and fees. Where is your car yard? We'd each > like to order a nice shiny red Ferrari :-) > > Cheers, > John erm... sry i don't get it :\ can you modify actual_price? actual_price = (((base_price * tax / 100) + license1 / 100) + dealer + charge -- http://mail.python.org/mailman/listinfo/python-list
Re: Medical GUI Application With Python
> "Evrim" == Evrim Ozcelik <[EMAIL PROTECTED]> writes: Evrim> We are developing a medical software about PSG Evrim> (PolySomnoGraphy) analysis. The application takes signal Evrim> data from an electronic device and we will show this Evrim> continious signal function on the interfaces. There are Evrim> about 20-30 signal channels and the user selected channels Evrim> are shown. We want to run this application over different Evrim> platforms. Evrim> My question is: Evrim>1. What must be our IDE 2. What class library for GUI Evrim> must be use (wxWindows, Qt, GTK, etc.) 3. Is there any GUI Evrim> package for visulazing signal functions (like sinozodial Evrim> functions) in real time; this module will behave as an Evrim> oscilloscope I wrote an EEG viewer in python using pygtk for the GUI and matplotlib for the 2D plotting (and VTK for the 3D). It runs unchanged on OSX, linux and win32. You can see a few screenshots at http://pbrain.sf.net . The underlying 2D plotting library, matplotlib, does handle animations (dynamic plots) and can be embedded in the GUI of your choice (Tk, WX, GTK, FLTK and QT). I also wrote matplotlib, as a first step in developing the application above. The performance of dynamic animated plots (what you call real time) varies for different backends. GTK is typically fastest: on a modern P4 you can do about 50 frames/sec for simple plots and 10-15 frames/sec for more complicated plots (images, larger data sets). The performance for the Tk GUI is considerably slower. Most people who say real time don't really mean it, they mean they want frequent updates and should assess whether the plotting library can support refresh rates (frames/sec) that are fast enough to be visually pleasing and to be true to the signal plotted. matplotlib is not the fastest 2D python plotting library, but it is one of the most feature complete and may be fast enough for your purposes -- http://matplotlib.sf.net . My guess is that for 20-30 channels the refresh rate in the current implementation will be slower than you want, but these things are always improving since matplotlib is under active development and there are some performance bottlenecks that could be removed with a little work. The examples directory which is in the src distributions has a number of examples illustrating dynamic plots: anim.py, system_monitor.py, dynamic_image_gtkagg.py, dynamic_image_wxagg.py, dynamic_demo.py. JDH -- http://mail.python.org/mailman/listinfo/python-list
Re: a type without a __mro__?
Alex Martelli wrote: > Can anybody suggest where to find (within the standard library) or how > to easily make (e.g. in a C extension) a type without a __mro__, except > for those (such as types.InstanceType) which are explicitly recorded in > the dispatch table copy._deepcopy_dispatch...? something like this? >>> import re >>> x = re.compile("") >>> x <_sre.SRE_Pattern object at 0x00B2F7A0> >>> x.__mro__ Traceback (most recent call last): File "", line 1, in ? AttributeError: __mro__ >>> import copy >>> type(x) in copy._deepcopy_dispatch False -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Processes for Win32
Hi ! Look for "service" in PyWin @-salutations -- Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: [EVALUATION] - E01: The Java Failure - May Python Helps?
Jan Dries wrote: >> have Pythoneers ever "banned" anyone from a public forum? it's not like >> we haven't seen trolls and crackpots before, you know. > > Well, we don't have to ban them because we have the PSU eliminate them > alltogether. So much more > efficient. Or do you think it's a coincidence we've never seen or heard > Timothy "autocoding" Rue > again? he's been assimilated: >>> "rue" in str(vars(__builtins__)) True -- http://mail.python.org/mailman/listinfo/python-list
Re: "Collapsing" a list into a list of changes
Alan McIntyre wrote: > Hi all, > > I have a list of items that has contiguous repetitions of values, but > the number and location of the repetitions is not important, so I just > need to strip them out. For example, if my original list is > [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5], I want to end up with [0,1,2,3,2,4,5]. > > Here is the way I'm doing this now: > > def straightforward_collapse(myList): > collapsed = [myList[0]] > for n in myList[1:]: > if n != collapsed[-1]: > collapsed.append(n) > > return collapsed > > Is there an elegant way to do this, or should I just stick with the code > above? > > Thanks, > Alan McIntyre > http://www.esrgtech.com Here is a version using dictionary properties, ie no duplication of keys. def condense(l): d={} for item in l: d[item]=1 l=d.keys() return l Cheers Tony -- http://mail.python.org/mailman/listinfo/python-list
Re: returning True, False or None
Christos TZOTZIOY Georgiou wrote: On Fri, 04 Feb 2005 13:04:16 -0500, rumours say that Steve Holden <[EMAIL PROTECTED]> might have written: [STeVe] For a given list: * If all values are None, the function should return None. * If at least one value is True, the function should return True. * Otherwise, the function should return False. [Stevbe] If you wanted to get clever you could write something like for i in True, False: if i in lst: return i return False [!Steve] You mistyped None as False in the last line. Your typos are getting worse every day :) That wasn't a *type*, it was a *thinko* regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Error!
administrata wrote: "John Machin" <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>... administrata wrote: I'm programming Car Salesman Program. It's been "3 days" learning python... From whom or what book or what tutorial? But, i got problem You got problemS. What Jeff & Brian wrote, plus: You have "change" instead of "charge". You forgot to add in the base price -- "actual price" according to you comprises only the taxes and fees. Where is your car yard? We'd each like to order a nice shiny red Ferrari :-) Cheers, John erm... sry i don't get it :\ He's referring to the fact that your calculations, probably through inexperience with programming, don't appear to add tax to the base price but rather simply compute tax from it. Don't worry, it wasn't *that* funny :-) can you modify actual_price? actual_price = (((base_price * tax / 100) + license1 / 100) + dealer + charge It would be much simpler if, having read the base price and the license (which I presume you are expecting to be percentages) you then separately computed the tax *amount* and the license *amount*, then just added everything together. So, for example, your program might look like this: base_price = int(raw_input(...)) tax_rate = int(raw_input(...) tax_amount = base_price * ((100+tax_amount)/...) ... actual_price = (base_price + tax_amount + license_amount + dealer + charge) print "Please hand over", actual_price Obviously the "..." are the bits you fill in to complete the program. Good luck! regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: An interesting python problem using Zope 2.7.3
ranjith g p wrote: Greetings!!! I ran the following simple string commands in Linux + Python and the results are: [EMAIL PROTECTED] root]# python Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. "A" 'A' "A/" 'A/' "A" 'A' Now when the same is run from Zope273 + python + Linux or windows, the results are, 1. 'A' 2. A/ 3. A respectively. Any suggestions? thanx Define "is run from"? When you enter an expression-statement at the interpreter's interactive prompt the interpreter computers the result and, if the result is not None, prints its repr(). How are you getting Zope to print the results? If they are coming through a web browser, for example, there will be obvious difficulties with unquoted "<" and ">" characters, regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: sos!
jordan2856977 wrote: hellow everybody! I'm from china. I'm a beginner of python. in china, python is not a fashionable language, so it's difficult to find some books about python. finally,I find a book named "python how to program" wrote by H.M.Deitel . who can tell me where can I find some interesting source code about python. otherwise, I will fell boring about study! Start at the links you find on http://www.python.org/moin/BeginnersGuide and take it from there. Also, if you want to see actual code there's lots of it in the standard library. If that's all too useful, take a look at http://www.uselesspython.com/ Welcome to Python! regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: returning True, False or None
Steve Holden wrote: Christos TZOTZIOY Georgiou wrote: On Fri, 04 Feb 2005 13:04:16 -0500, rumours say that Steve Holden <[EMAIL PROTECTED]> might have written: [STeVe] For a given list: * If all values are None, the function should return None. * If at least one value is True, the function should return True. * Otherwise, the function should return False. [Stevbe] If you wanted to get clever you could write something like for i in True, False: if i in lst: return i return False [!Steve] You mistyped None as False in the last line. Your typos are getting worse every day :) That wasn't a *type*, it was a *thinko* regards Steve Sheesh, now I even make typos typing about typos ... giving-up-on-the-spill-chocker-ly y'rs - steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] (Alexander Zatvornitskiy) wrote: > And, one more question: do you think code like this: > > var S=0 > var eps > > for eps in xrange(10): > S=S+ups > > is very bad? Please explain your answer:) Let me answer that by way of counter-example. Yesterday I was writing a little perl script. I always use "use strict" in perl, which forces me to declare my variables. Unfortunately, my code was giving me the wrong answer, even though the interpreter wasn't giving me any error messages. After a while of head-scratching, it turned out that I had written "$sum{x} += $y" instead of "$sum{$x} += $y". The need to declare variables didn't find the problem. I *still* needed to test my work. Given that I needed to write tests anyway, the crutch of having to declare my variables really didn't do me any good. -- http://mail.python.org/mailman/listinfo/python-list
Re: mounting a filesystem?
Dan Stromberg wrote: > Is there a python module that can mount a filesystem? > > More specifically, a loopback filesystem with a particular offset, under > linux? Why don't you just call the mount command via os.system, one of the popen methods or one of the commands.* methods? Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: "Collapsing" a list into a list of changes
Steve, Yeah, in this particular application the ordering and reoccurrence of a value in a non-contiguous way does matter; if those two things weren't required I think the method you suggested would be a good way to remove the duplicates. Thanks! Coates, Steve (ACHE) wrote: It's not _exactly_ what you asked for but it may be enough... Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. from sets import Set l = [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5] s = Set(l) s Set([0, 1, 2, 3, 4, 5]) l2 = list(s) l2 [0, 1, 2, 3, 4, 5] I say it's not exactly what you wanted because I don't think the ordering of l2 is necessarily the same as l. That may or may not be a problem for you. Regards Steve -- http://mail.python.org/mailman/listinfo/python-list
Trouble converting hex to decimal?
I'm trying to process the IP packet length field, as recorded by pcap (Ethereal) and recovered using pcapy. When I slice out those bytes, I get a value that shows in '\x00' format, rather than '0x00'. Neither int() nor eval() are working. How do I handle this? Earl Eiland -- http://mail.python.org/mailman/listinfo/python-list
Re: "Collapsing" a list into a list of changes
Tony, Actually I only want to remove a certain kind of duplication; if an item occurs twice - say like this: [1,1,1,2,2,2,1,1,1], then I need to keep the order and occurrence of the individual values: [1,2,1]. Using a dict as you proposed loses the order of occurrence, as well as multiple occurrences of groups of the same item. If I didn't need those two qualities of the list to be preserved, though, I think I'd use something like your solution (if I was using a Python older than 2.3) or Steve Coats' solution posted above using Set. Thanks! Alan Tony wrote: Here is a version using dictionary properties, ie no duplication of keys. def condense(l): d={} for item in l: d[item]=1 l=d.keys() return l Cheers Tony -- http://mail.python.org/mailman/listinfo/python-list
Re: "Collapsing" a list into a list of changes
Alex, Wow, that method turns out to be the fastest so far in a simple benchmark on Python2.3 (on my machine, of course, YMMV); it takes 14% less time than the one that I deemed most straightforward. :) Thanks, Alan Alex Martelli wrote: H, what role does the enumeration play here? I don't see how you're using it, at all. Why not just: def collapse(iterable): it = iter(iterable) lastitem = it.next() yield lastitem for item in it: if item != lastitem: yield item lastitem = item that's basically just the same as your code but without the strangeness of making an enumerate for the purpose of ignoring what the enumerate adds to an ordinary iterator. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Trouble converting hex to decimal?
Earl Eiland wrote: I'm trying to process the IP packet length field, as recorded by pcap (Ethereal) and recovered using pcapy. When I slice out those bytes, I get a value that shows in '\x00' format, rather than '0x00'. Neither int() nor eval() are working. How do I handle this? Earl Eiland You could either reconstruct the value yourself from the ord() values of the individual bytes, or look at the struct module which can help you with this kind of decoding task. regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Trouble converting hex to decimal?
Earl, Try this: >>> ord('\x00') 0 or: >>> import struct >>> struct.unpack('b', '\x00') (0,) If you're needing to pull values out of multiple bytes (shorts, longs, floats, etc.), have a look at the struct module. Here's an example: >>> struct.unpack('f', '\x00\x00(B') (42.0,) Hope this helps, Alan Earl Eiland wrote: I'm trying to process the IP packet length field, as recorded by pcap (Ethereal) and recovered using pcapy. When I slice out those bytes, I get a value that shows in '\x00' format, rather than '0x00'. Neither int() nor eval() are working. How do I handle this? Earl Eiland -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
Ashot wrote: > This is sort of both Python and Vim related (which is why I've posted to > both newsgroups). > > Python related: > -- > I have been frustrated for quite some time with a lack of a history > command in IDLE (in fact with IDLE in general). Often I'll develop new > code at the command line, testing each line as I go. Currently I have to > copy and paste, removing outputs and the ">>>" at each line. > Is it perhaps possible to make some kind of hack to do this (dump a > command history)? > > Idle in general isn't that great IMO, so I was wondering also if there are > better alternatives out there? What do people use mostly? I've tried > something called pyCrust, but this too didn't have history and some other > things I was looking for. PyCrust is only a shell, not a full-blown IDE, so it likely lacks things that you were looking for. But it certainly does have history, multi-line command recall, and cut/paste options with and without the leading prompts. In fact, the default Copy command (Ctrl+C) strips out the prompts, and the Copy Plus command (Shift+Ctrl+C) retains the prompts. If you select the Session tab you'll see the entire command history, without prompts and without the responses from the Python interpreter. Here are some other keybindings: >>> shell.help() * Key bindings: Home Go to the beginning of the command or line. Shift+HomeSelect to the beginning of the command or line. Shift+End Select to the end of the line. End Go to the end of the line. Ctrl+CCopy selected text, removing prompts. Ctrl+Shift+C Copy selected text, retaining prompts. Ctrl+XCut selected text. Ctrl+VPaste from clipboard. Ctrl+Shift+V Paste and run multiple commands from clipboard. Ctrl+Up Arrow Retrieve Previous History item. Alt+P Retrieve Previous History item. Ctrl+Down Arrow Retrieve Next History item. Alt+N Retrieve Next History item. Shift+Up ArrowInsert Previous History item. Shift+Down Arrow Insert Next History item. F8Command-completion of History item. (Type a few characters of a previous command and press F8.) Ctrl+EnterInsert new line into multiline command. Ctrl+]Increase font size. Ctrl+[Decrease font size. Ctrl+=Default font size. >>> Hope that helps. Pat -- Patrick K. O'Brien Orbtechhttp://www.orbtech.com Schevo http://www.schevo.org Pypersyst http://www.pypersyst.org -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
Alexander Zatvornitskiy wrote: > ÐÑÐÐÐÑ Peter! > > 31 ÑÐÐÐÑÑ 2005 Ð 09:09, Peter Otten Ð Ñ ÐÐÑÑÐÐ Ð All > ÐÐÑÐÐ: > PO> pychecker may help you find misspelled variable names. You have to > PO> move the code into a function, though: > > PO> $ cat epsilon.py > ...skipped... > PO> $ pychecker epsilon.py > PO> epsilon.py:6: Local variable (epselon) not used > > Well, I can change it a little to pass this check. Just add "print > epselon" line. You are now on a slippery slope. I'd rather think of ways to write my code in a way for it to succeed or at least fail in an obvious way. I don't consider a scenario likely where you both misspell a name nearly as often as you write it correctly, and do that in a situation where the program enters an infinite loop instead of just complaining with an exception, which is by far the most likely reaction to a misspelt name. > I think if as soon as I will make such error, I will write special > checker. It will take code like this: > > def loop(): > #var S,epsilon > epsilon=0 > S=0 > while epsilon<10: > S=S+epsilon > epselon=epsilon+1 > print S Code not written is always errorfree, and in that spirit I'd rather strive to write the function more concisely as def loop2(): s = 0 for delta in range(10): s += delta print s This illustrates another problem with your approach: would you have to declare globals/builtins like range(), too? > Such checker will say "error:epselon is not declared!" if I will use > something not declared. If everything is ok, it will call pychecker. > Simple and tasty, isn't it? That your program compiles in a somewhat stricter environment doesn't mean that it works correctly. > Of cource, it may be difficult to handle fields of classes: > MyClass.epsElon=MyClass.epsilon+1 MyClass.epsilon += 1 reduces the risk of a spelling error by 50 percent. I doubt that variable declarations reduce the likelihood of erroneous infinite loops by even 5 percent. > but it is solvable, I think. What do you think, is it a good idea? I suggested pychecker more as a psychological bridge while you gain trust in the Python way of ensuring reliable programs, i. e. writing small and readable functions/classes that do one thing well and can easily be tested. Administrative overhead -- as well as excessive comments -- only serve to bury what is actually going on. I guess that means no, not a good idea. On the other hand, taking all names used in a function and looking for similar ones, e. g. by calculating the Levenshtein distance, might be worthwhile... Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: sos!
jordan2856977 a écrit : hellow everybody! I'm from china. I'm a beginner of python. in china, python is not a fashionable language, so it's difficult to find some books about python. finally,I find a book named "python how to program" wrote by H.M.Deitel . who can tell me where can I find some interesting source code about python. otherwise, I will fell boring about study! Well, if you want to study some interesting source code, you have the whole Python standard lib, and *many* open source programs (Zope, Twisted, etc...) You can also find some good free books online, like Dive Into Python, or Text Processing With Python. (google should find relevant URLs). HTH, and welcome. -- http://mail.python.org/mailman/listinfo/python-list
Re: who can tell me BASICS of Python
[EMAIL PROTECTED] a écrit : I want to know which compiler I can use ... thank you To compile what ? Python code ? The compiler is in the standard lib. -- http://mail.python.org/mailman/listinfo/python-list
Re: [EVALUATION] - E01: The Java Failure - May Python Helps?
Jeremy Bowers wrote: On Thu, 03 Feb 2005 09:26:08 +0200, Ilias Lazaridis wrote: My question is essentially: How many of those constructs are already supported by python (and the surrounding open-source-projects): http://lazaridis.com/case/stack/index.html This post is hard to follow, but I'm going to assume this is the core question, as it is labelled as such. ok Thank you for your thorought comments. The first thing that leaps to mind is that you need to play with Python for a bit to get a full analysis of it. Due to the nature of Python, some of the things you have in that list don't really apply. The most obvious example of this is "code generation": Assuming you mean [...] I want to generate things (code, txt, html etc.) out of my object-model, whilst using with a flexible generator, if possible a standard one. Does such generator exist? [...] "Use of metadata within the design (on text level [code file])" can mean a thousand things. For what it's worth, Python tends to make it so easy I do it all the time, but for any given way you mean it, I can't promise there exists a pre-rolled framework for you. I want to add metadata to everything within my design (functions, data, classes, ...), if possible with a standard way. Does such metadata-functionality (build-in, add-on-library, framework) exist for python? So I can only speak generally. Given your list, you may find that Python is weak in the "graphical programming" department; drop-and-drop GUI generation isn't as well-tuned as VB. (I, for one, consider that development methodology toxic and actively dangerous, but I can understand why you miss it.) I prefere generic GUI's. But sometimes there is a need for simple predefined GUI's. Thus: I want to create GUI's in an generic way, and/or in an standard way (via GUI editor). Skipping down to your evaluation sequence: http://lazaridis.com/case/stack/index.html#evaluation * Create a class: Well, I'll show you this one: class Something: pass There, a class. ok - you've missed: "declare this class as persistent" * Simple GUI: You may wish to check out Boa Constructor, as the closest thing to the GUI generator you probably want. There are at least 3 major viable GUI toolkits for Python and several other minor (but still capable) ones. => {GUI Generator: Boa Constructor} * Embedded DBs: I don't know, Google for your embedded DB name + Python. Failing that, there are several ways to wrap your embedded DB such that a Python program can use it. ok Clarification: standard way to save python objects into an embedded db (in conjunction wiht "declare this class as persistent") * Web GUI: There are more Python web frameworks than you can shake a stick at, and I don't mean "some guys hacked together templating system" either; there are a lot of very mature systems out there, expressing a lot of different philosophies. Given some of your other requirements, for a web-based application I'd recommend examining Zope. ok. Can please someone name some of them? [they should work together with simple python classes and the standard metadata] * Deployment: I don't generally have enough problems with this to be worth thinking about. I don't know what the state of the remote debugging is on Python; Google "remote debugging Python". [I like to avoid interaction with google.] * For your "complex updates", I see two distinct things there; half of the depend on the database, not Python. It depends on how my python-build system binds to the underlaying database. For the other half, it depends on if you mean "while the program is still running". If so, they are challenging. If not, they are trivial. You are right. New Requirements: a) While the programm in shutted down. b) While the programm in still running. * I'd recommend adding "testability" to your stack, and refer you to the "unittest" module; others can suggest their preferred testing modules, but I tend to stick with that as the general framework is available in a lot of languages that I use. If by evolutive development you are including the ideas behind "agile software development" (hard to tell if you mean that, or a community open to change*) I don't know "agile software development", thus I cannot answer you. I'll think about to add "testability" to the stack. Based on what I see here, I have two basic comments. First, yes, [...] have, that even if it isn't perfect it's a helluva lot better than Java! I've not evaluated Java. Just it's communities. Thus I can "dive" immediately & fully into python, without any philosoph switch (if i select python finally). *: Community open to change: One caveat, from what I've seen when other people talk about this. The Python community is open to change, but it is still a meritocracy, and you will still need to convince others your change is good. [...] - (standard library etc.) I understand. - A rational change suggestion does not need time to be accepted. Just rational decision takers (e
Re: Error!
Steve Holden a écrit : (snip) So, for example, your program might look like this: base_price = int(raw_input(...)) tax_rate = int(raw_input(...) tax_amount = base_price * ((100+tax_amount)/...) s/(100+tax_amount)/(100 + tax_rate)/, I guess ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Error!
Bruno Desthuilliers wrote: Steve Holden a écrit : (snip) So, for example, your program might look like this: base_price = int(raw_input(...)) tax_rate = int(raw_input(...) tax_amount = base_price * ((100+tax_amount)/...) s/(100+tax_amount)/(100 + tax_rate)/, I guess ? Oops. Let's try tax_amount = base_price*(tax_rate/100.0) Clearly I was right about simplification being a good idea :-) regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: empty classes as c structs?
On Sat, 05 Feb 2005 02:38:13 -0500, Leif K-Brooks <[EMAIL PROTECTED]> wrote: > Actually, in Python, class definitions are runtime executable statements > just like any other. You can do this: > > >>> def make_class(with_spam=True): > ... if with_spam: > ... class TheClass(object): > ...def dostuff(self): > ... print 'Spam, spam, spam, spam!' > ... else: > ... class TheClass(object): > ...def dostuff(self): > ... print "I don't like spam!" > ... return TheClass The real power of the class statement is that you can code it this way: class TheClass(object): if with_spam: def dostuff(self): print 'Spam, spam, spam, spam!' else: def dostuff(self): print "I don't like spam!" Instead of creating two classes in separate branches of the if statement, you can as well use the if inside the class statement. It's perfectly valid. Of course, one still has to feed it with the 'with_spam' argument - but if 'with_spam' is a global, or if the class statement wrapped inside a function that defines 'with_spam', it will work just as fine. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: [EMAIL PROTECTED] mail: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: a type without a __mro__?
Fredrik Lundh wrote: Alex Martelli wrote: Can anybody suggest where to find (within the standard library) or how to easily make (e.g. in a C extension) a type without a __mro__, except for those (such as types.InstanceType) which are explicitly recorded in the dispatch table copy._deepcopy_dispatch...? something like this? import re x = re.compile("") x <_sre.SRE_Pattern object at 0x00B2F7A0> x.__mro__ Traceback (most recent call last): File "", line 1, in ? AttributeError: __mro__ import copy type(x) in copy._deepcopy_dispatch False Unfortunately, it *does* have a __deepcopy__ method, so I don't think it actually triggers the bug Alex is interested in: Py> import re Py> x = re.compile("") Py> x.__mro__ Traceback (most recent call last): File "", line 1, in ? AttributeError: __mro__ Py> from copy import deepcopy Py> deepcopy(x) Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\copy.py", line 172, in deepcopy y = copier(memo) TypeError: cannot deepcopy this pattern object Py> x.__deepcopy__ Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
variable declaration
Hi, Alex! 05 feb 2005 at 12:52, Alex Martelli wrote: >> declarations, another (this problem is common with C/C++) >> is: === print 1/2 0 === (I understand why it is so, but I don't like >> it anyway. Such behaviour also can cause some hard-to-find-bugs) AM> You're conflating a fundamental, crucial language design choice, with AM> a rather accidental detail It's not my problem:) I just wrote about two things that I don't like. AM> Run Python with -Qnew to get the division behavior you probably want, AM> or -Qwarn to just get a warning for each use of integer division so AM> those hard to find bugs become trivially easy to find. Thank you. It will help me. AM> The fact that in Python there are ONLY statements, NO declarations, === def qq(): global z z=5 === What is "global"? Statement? Ok, I fill lack of "var" statement:) AM> is a completely different LEVEL of issue -- a totally deliberate AM> design choice taken in full awareness of all of its implications. I AM> do not see how you could be happy using Python if you think it went AM> wrong in such absolutely crucial design choices. Ok, I understand your position. >> >> errors,like this: epsilon=0 S=0 while epsilon<10: >> >> S=S+epsilon epselon=epsilon+1 print S It will print zero, and it >> >> is not easy to find such a bug! >> AM> Actually, this while loop never terminates and never prints >> AM> anything, >> Oh, I don't find it:) AM> Hit control-C (or control-Break or whatever other key combination AM> interrupts a program on your machine) when the program is just AM> hanging there forever doing nothing, and Python will offer a AM> traceback showing exactly where the program was stuck. AM> In any case, you assertion that "it will print zero" is false. You AM> either made it without any checking, or chose to deliberately lie (in AM> a rather stupid way, because it's such an easy lie to recognize as AM> such). Sorry, while saying "I don't find it" I mean "I don't take it into account at time I wrote original message. Now I find it, and it make me smile.". As you understand, I'am not very good in English. >> Fine! Let interpreter never show us errors like division by zero, >> syntax errors, and so on. If file not found, library don't need to >> say it. Just skip it!!! Because every, even simple, test will find >> such bugs. Once you have unit tests, the added value of >> is tiny, and their cost remains. AM> Another false assertion, and a particularly ill-considered one in ALL AM> respects. Presence and absence of files, for example, is an AM> environmental issue, notoriously hard to verify precisely with unit AM> tests. Therefore, asserting that "every, even simple, test will find" AM> bugs connected with program behavior when a file is missing shows AM> either that you're totally ignorant about unit tests (and yet so AM> arrogant to not let your ignorance stop you from making false AM> unqualified assertions), or shamelessly lying. Here, you take one detail and bravely fight with it. Just try to understand meaning of my sentence, in all. It will help:) AM> Moreover, there IS no substantial cost connected with having the AM> library raise an exception as the way to point out that a file is AM> missing, for example. It's a vastly superior approach to the old idea AM> of "returning error codes" and forcing the programmer to check for AM> those at every step. If the alternative you propose is not to offer AM> ANY indication of whether a file is missing or present, then the cost AM> of THAT alternative would most obviously be grievous -- essentially AM> making it impossible to write correct programs, or forcing huge AM> redundancy if the check for file presence must always be performed AM> before attempting I/O. AM> In brief: you're not just wrong, you're so totally, incredibly, AM> utterly and irredeemably wrong that it's not even funny. Hey, take it easy! Relax, reread that piece of text. It was written with smile on my lips. Here it is for your convenience: AM> And once you have unit tests, the added value of declarations is AM> tiny, and their cost remains. Fine! Let interpreter never show us errors like division by zero, syntax errors, and so on. If file not found, library don't need to say it. Just skip it!!! Because every, even simple, test will find such bugs. Once you have unit tests, the added value of is tiny, and their cost remains. Again, skip small details and take a look on the problem "in general". Here is, again, the main idea: Or, maybe, we will ask interpreter to find and prevent as many errors as he can? You wrote about "substantial cost" of var declarations. Yes, you are write. But think about the cost of lack of var declarations. Compare time that programmer will waste on search for the reason of bug caused by such typo, plus time what programmer will waste while remembering exact variable name. Compare it with time for lookin
Re: a type without a __mro__?
Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Alex Martelli wrote: > > > Can anybody suggest where to find (within the standard library) or how > > to easily make (e.g. in a C extension) a type without a __mro__, except ^^ > > for those (such as types.InstanceType) which are explicitly recorded in > > the dispatch table copy._deepcopy_dispatch...? > > something like this? > > >>> import re > >>> x = re.compile("") > >>> x > <_sre.SRE_Pattern object at 0x00B2F7A0> > >>> x.__mro__ > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: __mro__ Alas, no -- wish it were so easy! It does need to be a TYPE, not just any object, to reproduce the bug that was reported about 2.3.5c1's copy.py. The relevant code in copy.py does the equivalent of: >>> type(x).__mro__ (, ) >>> not of just x.__mro__, which would easily be made to fail. How a type(whatever) can end up without a __mro__ in 2.3.* is rather murky to me; looks like something strange must be happening wrt the type's flags, or something. Normal types such as _sre.SRE_Pattern, or the Copyable type I put in _testcapi, just sprout an __mro__ without even trying. Ah well, thanks anyway -- guess I'll commit the fix (using inspect.getmro(cls) rather than cls.__mro__) even though I don't have a unit test to show it's necessary and sufficient:-( Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: changing local namespace of a function
Alex Martelli wrote: Bo Peng <[EMAIL PROTECTED]> wrote: ... Thank again for everyone's help. I have learned a lot from the posts, especially the wrapdict class. Hmmm, you do realize that wrapdict uses a lot of indirection while my equivalent approach, just posted, is very direct, right? To reiterate the latter, and dress it up nicely too, it's class wrapwell(object): def __init__(self, somedict): self.__dict__ = somedict and use d=wrapwell(whateverdict) to make the wrapper. Now, reading or writing d.x is just like reading or writing whateverdict['x'], etc etc. I was wondering if that would work, but never got around to trying it. It can be used with the property-based auto calculation approach, too (the calculated properties just store the results in self.__dict__ instead of self._data): class DataManipulator(object): def __init__(self, data): self.__dict__ = data class _utils(object): @staticmethod def make_prop(name, calculator): def get(self, _name=name, _calculator=calculator): try: return self.__dict__[_name] except KeyError: val = _calculator(self) self.__dict__[_name] = val return val def set(self, val, _name=name): self.__dict__[_name] = val def delete(self, _name=name): del self.__dict__[_name] return property(get, set, delete) @staticmethod def calc_z(self): return self.x + self.y z = _utils.make_prop('z', _utils.calc_z) Py> d = DataManipulator(dict(x=1, y=2)) Py> d.x 1 Py> d.y 2 Py> d.z 3 Py> d.x = 10 Py> d.z 3 Py> del d.z Py> d.z 12 Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: empty classes as c structs?
Alex Martelli wrote: Nick Coghlan <[EMAIL PROTECTED]> wrote: ... Michael Spencer also posted an interesting idea recently about setting up a view of an existing dictionary, rather than as a separate object: class attr_view(object): def __init__(self, data): object.__setattr__(self, "_data", data) def __getattr__(self, attrname): return self._data[attrname] def __setattr__(self, attrname, value): self._data[attrname] = value Wasted indirection, IMHO. A better implementation: class attr_view(object): def __init__(self, data): self.__dict__ = data Alex Yeah, I caught your comment in the other thread. It was something I'd wondered about, but never followed up . And any time you want real dictionary behaviour, a quick call to "vars(x)" will do nicely. I think the idea definitely deserves mention as a possible implementation strategy in the generic objects PEP, with the data argument made optional: class namespace(object): def __init__(self, data=None): if data is not None: self.__dict__ = data # Remainder as per Bunch in the PEP. . . Py> result = namespace() Py> result.x = 1 Py> result.y = 2 Py> vars(result) {'y': 2, 'x': 1} Py> gbls = namespace(globals()) Py> gbls.result <__main__.namespace object at 0x00B2E370> Py> gbls.result.x 1 Py> gbls.result.y 2 Py> gbls.gbls <__main__.namespace object at 0x00B2E410> This does mean construction using keywords or a sequence of pairs requires an extra call to dict() at the invocation point. However, it means that the class can also be used to manipulate an existing dictionary, which the current PEP version doesn't allow. namespace(existing_dict) would mean that the namespace should manipulate the original dictionary. namespace() would create a new, initially empty, dict to work on. namespace(dict()) would create a new, non-empty, dict based on the standard arguments to the dictionary constructor. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: [EVALUATION] - E01: The Java Failure - May Python Helps?
In message <[EMAIL PROTECTED]>, Ilias Lazaridis <[EMAIL PROTECTED]> writes [I like to avoid interaction with google.] Well, use a different search engine. I've not evaluated Java. That is strange - the title of this thread indicates that you have evaluated Java. You have posted similar threads in comp.lang.ruby and comp.lang.java.*. You are a troll. Stephen -- Stephen Kellett Object Media Limitedhttp://www.objmedia.demon.co.uk RSI Information:http://www.objmedia.demon.co.uk/rsi.html -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
Alexander Zatvornitskiy <[EMAIL PROTECTED]> wrote: ... > AM> The fact that in Python there are ONLY statements, NO declarations, > === > def qq(): > global z > z=5 > === > What is "global"? Statement? Ok, I fill lack of "var" statement:) 'global' is an ugly wart, to all intents and purposes working "as if" it was a declaration. If I had to vote about the one worst formal defect of Python, it would surely be 'global'. Fortunately, it's reasonably easy to avoid the ugliness, by avoiding rebinding (within functions) global variables, which tend to be easy. What you keep demanding is a way to inject far worse ugliness, and in a context in which the typical behavior of pointy-haired bosses will be to make it unavoidable for many of the people who work with Python. I am strongly convinced that, if you had your wish, the total amount of happiness in the world would be quite substantially diminished, and I will do anything I can to stop it from happening. > >> Fine! Let interpreter never show us errors like division by zero, > >> syntax errors, and so on. If file not found, library don't need to > >> say it. Just skip it!!! Because every, even simple, test will find > >> such bugs. Once you have unit tests, the added value of > >> is tiny, and their cost remains. > AM> Another false assertion, and a particularly ill-considered one in ALL > AM> respects. Presence and absence of files, for example, is an ... > Here, you take one detail and bravely fight with it. Just try to understand > meaning of my sentence, in all. It will help:) I tear ONE of your examples to pieces in gory detail, because it's not worth doing the same over and over again to every single piece of crap you filled that sentence with -- very similar detailed arguments show how utterly inane the whole assertion is. There IS no meaning to your (several) sentences above-quoted, that it can help anybody to "try to undestand": it's simply an insanely bad attempt at totally invalid parallels. > AM> In brief: you're not just wrong, you're so totally, incredibly, > AM> utterly and irredeemably wrong that it's not even funny. > Hey, take it easy! Relax, reread that piece of text. It was written with smile > on my lips. Here it is for your convenience: Do yourself a favor: don't even _try_ to be funny in a language you have so much trouble with. Your communication in English is badly enough impaired even without such lame attempts at humor: don't made bad things even worse -- the result is NOT funny, anyway, just totally garbled. I'm not a native English speaker, either, so I keep a careful watch on this sort of thing, even though my English would appear to be a bit better than yours. > Again, skip small details and take a look on the problem "in general". Here is, There IS no ``problem "in general"'': Python does a pretty good job of diagnosing as many errors as can be diagnosed ***without demanding absurdities such as redundancy on the programmer's part***. Period. > again, the main idea: > > Or, maybe, we will ask interpreter to find and prevent as many errors as he > can? To show how absurd that would be: why not force every line of the program to be written twice, then -- this would help diagnose typos, because the interpreter could immediately mark as errors any case in which the two copies aren't equal. Heck, why stop at TWICE -- even MORE errors will be caught if every line has to be written TEN times. Or a million. Why not? *AS MANY ERRORS AS [it] CAN* is an *ABSURD* objective, if you don't qualify it with *WHILE AVOIDING ANY ENFORCED REDUNDANCY* introduced solely for that purpose. As soon as you see that such redundancy is a horror to avoid, you will see that Python's design is essentially correct as it is. > You wrote about "substantial cost" of var declarations. Yes, you are > write. But think about the cost of lack of var declarations. Compare time > that programmer will waste on search for the reason of bug caused by such > typo, plus time what programmer will waste while remembering exact > variable name. I've been programming essentially full-time in Python for about three years, plus a few more years before then when I used Python as much as I could, even though my salary was mostly earned with C++, Visual Basic, Java, perl, and so on. My REAL LIFE EXPERIENCE programming in Python temms me that the time I've "wasted on search" etc due to the lack of variable declaration is ***FUNDAMENTALLY NOTHING AT ALL***. Other hundreds of thousands of man-hours of similar Python programming experience on the part of hundreds of other programmers essentially confirm these findings. Your, what, TENS?, of man-hours spent programming in Python tell you otherwise. Fine, then *USE ANOTHER LANGUAGE* and be happy, and let US be just as happy by continuing to use Python -- almost all languages do things the way you want, so ***leave alone*** the few happy oases such as Python and Ruby where programmers c
Re: changing local namespace of a function
Bo Peng wrote: Dear list, I have many dictionaries with the same set of keys and I would like to write a function to calculate something based on these values. For example, I have a = {'x':1, 'y':2} b = {'x':3, 'y':3} def fun(dict): dict['z'] = dict['x'] + dict['y'] fun(a) and fun(b) will set z in each dictionary as the sum of x and y. My function and dictionaries are a lot more complicated than these so I would like to set dict as the default namespace of fun. Is this possible? The ideal code would be: def fun(dict): # set dict as local namespace # locals() = dict? z = x + y You can part way there using keyword arguments. You just have to use dictionary syntax for changing values in the dictionary: >>> def f(d, x=None, y=None): ... d['z'] = x + y ... >>> a = {'x':1, 'y':2} >>> b = {'x':3, 'y':3} >>> >>> f(a, **a) >>> a {'y': 2, 'x': 1, 'z': 3} >>> f(b, **b) >>> b {'y': 3, 'x': 3, 'z': 6} Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: changing local namespace of a function
Nick Coghlan wrote: If you want to add more calculated properties to the data manipulator, simply define additional calculator methods, and define the attribute with make_prop. This has became really appealing You know, I have a deep root in C/C++ so performance is the king and hacking is part of my daily life. Time to change now. :) My original problem was that I need to manipulate and create dictionary items in situ and since there are so many "d['key']"s, I would like to make my code easier to read (and save some key strokes) by using "d.key" or simply "key", without sacrificing performance. OOP seemed to be irrelevant. But this on-demand calculation (quote: make first call to z automatic) is *really* good! I can calculate self._data.stat_a = self._data.stat_b + 1 without worrying about the status of stat_b and users can access any value in the dictionary, original or calculated, in a uniform and easier way! This makes my program instantly easier to use. I can not say enough thank you for this. Bo -- http://mail.python.org/mailman/listinfo/python-list
Re: changing local namespace of a function
Bo Peng wrote: Yes. I thought of using exec or eval. If there are a dozen statements, def fun(d): exec 'z = x + y' in globals(), d seems to be more readable than def fun(d): d['z'] = d['x'] + d['y'] But how severe will the performance penalty be? You can precompile the string using compile(), you only have to do this once. >>> def makeFunction(funcStr, name): ... code = compile(funcStr, name, 'exec') ... def f(d): ... exec code in d ... del d['__builtins__'] # clean up extra entry in d ... return f ... >>> f = makeFunction('z = x + y', 'f') >>> a = {'x':1, 'y':2} >>> b = {'x':3, 'y':3} >>> f(a) >>> a {'y': 2, 'x': 1, 'z': 3} >>> f(b) >>> b {'y': 3, 'x': 3, 'z': 6} -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
Alexander Zatvornitskiy wrote: You wrote about "substantial cost" of var declarations. Yes, you are write. But think about the cost of lack of var declarations. Compare time that programmer will waste on search for the reason of bug caused by such typo, plus time what programmer will waste while remembering exact variable name. This is a problem better solved through a decent editor with code completion than through redundant variable declarations, which waste *far* more programmer time than typos do. The *only* time the typo is a potential problem is if a variable name gets rebound to something different. This is because, in Python, the name binding operation ('=') *is* the declaration of the variable. Rebinding a name often begs the question, "why are you using the same name for two different things in the one function?" It's not like using a different name for the second thing will cost much in terms of program size (unless you have some freakishly long functions) and it surely does little for readability. (Granted, iteration can be an exception, but even then the name generally only gets bound twice at most - once before the loop, and once in the loop body) Consider all of the following cases which are detected while still preserving the convenience of 'name binding is declaration': Py> def f(): ... x = y ... Py> f() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in f NameError: global name 'y' is not defined Py> def f(): ... x += 1 ... Py> f() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in f UnboundLocalError: local variable 'x' referenced before assignment Py> def f(): ... oops = 1 ... print ooops ... Py> f() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in f NameError: global name 'ooops' is not defined Py> def f(): ... class C: pass ... c = C() ... print c.x ... Py> f() Traceback (most recent call last): File "", line 1, in ? File "", line 4, in f AttributeError: C instance has no attribute 'x' Now, if someone were to suggest a *rebinding* operator, that worked just like regular name binding, but expected the name to be already bound, that would be an entirely different kettle of fish - you keep all the benefits of the current system, but gain the typo-checking that the rest of the augmented assignment operators benefit from. Hell, '@' just acquired rebinding semantics through its use in function decorator syntax, so how does it look?: S=0 for eps in xrange(10): S @= S + ups Meh. At symbols are still ugly. A full stop might work better, since the semantics aren't very different from a reader's point of view: S=0 for eps in xrange(10): S .= S + ups Anyway, the exact syntax isn't as important as the concept :) Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
Alex Martelli wrote: 'global' is an ugly wart, to all intents and purposes working "as if" it was a declaration. If I had to vote about the one worst formal defect of Python, it would surely be 'global'. Fortunately, it's reasonably easy to avoid the ugliness, by avoiding rebinding (within functions) global variables, which tend to be easy. Hear, hear! And if I could write "gbls = namespace(globals())" in order to deal with those rare cases where I *do* need to rebind globals, all uses of the keyword could be handled nicely, while entirely eliminating the need for the keyword itself. *ONLY* that tiny subset of such typos which happened on the left of a plain '=' (since all others, happening on the RIGHT of an '=' or on the left of an _augmented_ '=', were already caught), and ONLY regarding barenames (such typos on any but the rightmost component of compound names were already caught intrinsically, and catching those on the rightmost component is trivially easier than introducing a {YEHH} 'vars' as you so stubbornly insist)... Would you be as violently opposed to a 'rebinding' augmented assignment operator? Since bare assignment statements essentially serve the purpose of variable declarations, I sometimes *would* like a way to say 'bind this existing name to something different'. A rebinding operation would provide a way to make that intention explicit, without cluttering the language with useless declarations. In addition to detecting typos in local variable names, it would *also* address the problem of detecting typos in the right-most name in a compound name (e.g. making a habit of always using the rebinding operator when modifying member variables outside of __init__ would make it easier to avoid inadvertently creating a new instance variable instead of modifying an existing one) With a rebinding operator available, the only typos left to slip through the net are those which match an existing visible name and those where the programmer has explicitly requested an unconditional name binding by using '=' and then made a typo on the left hand side. Cheers, Nick. Did I mention the possible incidental benefit of reducing the whinging about the lack of variable declarations? -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Trouble converting hex to decimal?
Hi The problem is that '\x00' is a escape sequence... Try something like this: >>> x = '\x00' >>> int(repr(x)[3:-1], 16) 0 >>> x = '\x15' >>> int(repr(x)[3:-1], 16) 21 >>> On Sat, 05 Feb 2005 06:51:32 -0700 Earl Eiland <[EMAIL PROTECTED]> wrote: > I'm trying to process the IP packet length field, as recorded by pcap > (Ethereal) and recovered using pcapy. When I slice out those bytes, I > get a value that shows in '\x00' format, rather than '0x00'. Neither > int() nor eval() are working. How do I handle this? > > Earl Eiland > > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: "Collapsing" a list into a list of changes
On Sat, Feb 05, 2005 at 02:31:08PM +1000, Nick Coghlan wrote: > Jack Diederich wrote: > >Since this is 2.4 you could also return a generator expression. > > > > > def iter_collapse(myList): > > > >... return (x[0] for (x) in > >it.groupby([0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5])) > >... > > But why write a function that returns a generator expression, when you > could just turn the function itself into a generator? > > Py>def iter_collapse(myList): > ... for x in it.groupby(myList): > ... yield x[0] > Here is where I say, "because it is faster!" except it isn't. maybe. The results are unexpected, anyway. import timeit import itertools as it def collapse1(myl): for x in it.groupby(myl): yield x[0] def collapse2(myl): return (x[0] for (x) in it.groupby(myl)) list_str = '[0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5]' print "collapse1", timeit.Timer('collapse1(%s)' % (list_str), 'from __main__ import collapse1').timeit() print "collapse2", timeit.Timer('collapse2(%s)' % (list_str), 'from __main__ import collapse2').timeit() print "list(collapse1)", timeit.Timer('list(collapse1(%s))' % (list_str), 'from __main__ import collapse1').timeit() print "list(collapse2)", timeit.Timer('list(collapse2(%s))' % (list_str), 'from __main__ import collapse2').timeit() collapse1 1.06855082512 collapse2 3.40627384186 list(collapse1) 8.31489896774 list(collapse2) 9.49903011322 The overhead of creating the generator expression seems much higher than creating the equivalent function. If you subtract our the setup difference actually running through the whole iterator is slightly faster for genexps than functions that yield. At a guess it has something to do with how they handle lexical scope and some byte code differences. I said guess, right? -Jack -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
Alexander Zatvornitskiy wrote: var epsilon=0 var S S=0 while epsilon<10: S=S+epsilon epselon=epsilon+1#interpreter should show error here,if it's in "strict mode" print S It is easy, and clean-looking. Alexander, [EMAIL PROTECTED] An alternate proposal, where the decision to request rebinding semantics is made at the point of assignment: epsilon = 0 S = 0 while epsilon < 10: S .= S + epsilon epselon .= epsilon + 1 #interpreter should show error here print S Of course, this is a bad example, since '+= ' can be used already: S = 0 epsilon = 0 while epsilon<10: S += epsilon epselon += 1 #interpreter DOES show error here print S However, here's an example where there is currently no way to make the rebinding intent explicit: def collapse(iterable): it = iter(iterable) lastitem = it.next() yield lastitem for item in it: if item != lastitem: yield item lastitem = item With a rebinding operator, the intent of the last line can be made explicit: def collapse(iterable): it = iter(iterable) lastitem = it.next() yield lastitem for item in it: if item != lastitem: yield item lastitem .= item (Note that doing this *will* slow the code down, though, since it has to check for the existence of the name before rebinding it) Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: changing local namespace of a function
Bo Peng wrote: I can not say enough thank you for this. Don't thank me, thank Guido. He created the property machinery - I just let you know it was there :) But yes, Python's OO is OO the way it should be - something that helps you get the job done quickly and cleanly, rather than making you jump through irrelevant hoops. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
How to read POSTed data
Hi. I am trying to set up a simple HTTP-server but I have problems reading data that is beeing POSTed. class httpServer(BaseHTTPServer.BaseHTTPRequestHandler): def do_POST(self): input = self.rfile.read() The self.rfile.read() will hang on the data = self._sock.recv(recv_size) line in the read() function in socket.py. Is there another way to read the data? Thanks, Håkan Persson -- http://mail.python.org/mailman/listinfo/python-list
Re: Trouble converting hex to decimal?
Pedro Werneck wrote: Hi The problem is that '\x00' is a escape sequence... Try something like this: x = '\x00' int(repr(x)[3:-1], 16) 0 x = '\x15' int(repr(x)[3:-1], 16) 21 On Sat, 05 Feb 2005 06:51:32 -0700 Earl Eiland <[EMAIL PROTECTED]> wrote: I'm trying to process the IP packet length field, as recorded by pcap (Ethereal) and recovered using pcapy. When I slice out those bytes, I get a value that shows in '\x00' format, rather than '0x00'. Neither int() nor eval() are working. How do I handle this? Earl Eiland Talk about making things difficult! >>> x = '\x00' >>> ord(x) 0 >>> x = '\x15' >>> ord(x) 21 >>> regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: changing local namespace of a function
Something I forgot to mention. . . Bo Peng wrote: You know, I have a deep root in C/C++ so performance is the king and hacking is part of my daily life. Time to change now. :) The entire design of C++ is in many ways a regrettable monument to the idea that premature optimisation is evil - far too many of the language's default behaviours are 'fast in particular cases, but quite simply wrong in most cases, and the compiler often can't tell you which case applies'. So you can write buggy warning free code just by failing to override the unsafe default behaviours. That said, one of the reasons I like CPython is that it lets you drop into C/C++ really easily when you need to (generally for hardware interface or performance reasons). The builtin profiler can also give some decent hints on the bottlenecks where you need to focus your performance improvements. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
An Ode To My Two Loves
At the risk of calling my manhood into question, I humbly submit the following little diddy (which is a blatant rip-off of a heart wrenching melody of the '70s by that international superstar, Mary Macgregor): To the tune of "Torn Between Two Lovers": Torn between two languages, both of which are awesome tools Lovin' both of you is breakin' all the rules Torn between two incredibly awesome scripting languages, I'm startin' to drool Using you both is breakin' all the rules Is freedom of choice wonderful or a curse? I do a lot of scripting at my day job. Through the years, I've gone through what will probably seem a somewhat familiar progression of scripting languages. Started out with Tcl, moved to Perl when I began to do some serious text munging, moved back to Tcl/Tk when I needed to do some gui stuff, jumped to Python as I began to learn object oriented programming, told Python I needed more space and moved in with Ruby when I needed to do more gui stuff and wanted to use FXRuby. And that's where I stand now, Torn Between Two Scripting Languages. Python and Ruby are both so damn attractive that I can't commit to one of them. I don't want to settle down into a monogamous programming relationship. I mean, if you have Grace Kelly on one arm and Maureen O'Hara on the other (I'm old school), should you really have to give one of them up? Why can't my boss understand this? But no, he has to lecture me about the dangers of "foolin' around" with too many languages. "Oh sure", he says, "you're having fun now juggling two beautiful languages in the air. But how long can you keep living two lives? Sooner or later you are going to slip up and make a mistake. My god, man, what if you start leaving off the 'end' in your if statements? What if you forget that indentation DOES matter?! For the love of all that is sacred and holy, think of the programs!" My boss was always a little melodramatic. Anyway, I don't know why I'm typing this up. I just finished a major update to KirbyBase and I think I'm a little punch drunk. I have been spending a lot of time with Ruby lately and working on KirbyBase caused me to dive back into Python. Why do these two languages have to be so freakin' good! I know a lot of people see big differences in the languages, but I'm not one of them. I don't think I am a smart enough programmer to understand or ever be bothered by some of the more subtle or deeper differences that some people have pointed out. Ah, ignorance is bliss. Well, as long as I can keep my boss from finding out that I am in this programming love triangle, I think I will probably stay happily enmeshed in my little soap opera. Well, I think I will go now and listen to my Captain & Tenille records...why are you looking at me like that. I'm a happily married man with four kids. I like football and guns...really, I do! Under the influence of some kind of strange force and will probably be embarrassed when he snaps out of it, Jamey Cribbs -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I enter/receive webpage information?
On 4 Feb 2005 15:33:50 -0800, Mudcat <[EMAIL PROTECTED]> wrote: > Hi, > > I'm wondering the best way to do the following. > > I would like to use a map webpage (like yahoo maps) to find the > distance between two places that are pulled in from a text file. I want > to accomplish this without displaying the browser. That's called "web scraping", in case you want to Google for info. > I am looking at several options right now, including urllib, httplib, > packet trace, etc. But I don't know where to start with it or if there > are existing tools that I could incorporate. > > Can someone explain how to do this or point me in the right direction? I did it this way successfully once ... it's probably the wrong approach in some ways, but It Works For Me. - used httplib.HTTPConnection for the HTTP parts, building my own requests with headers and all, calling h.send() and h.getresponse() etc. - created my own cookie container class (because there was a session involved, and logging in and such things, and all of it used cookies) - subclassed sgmllib.SGMLParser once for each kind of page I expected to receive. This class knew how to pull the information from a HTML document, provided it looked as I expected it to. Very tedious work. It can be easier and safer to just use module re in some cases. Wrapped in classes this ended up as (fictive): client = Client('somehost:80) client.login('me', 'secret) a, b = theAsAndBs(client, 'tomorrow', 'Wiltshire') foo = theFoo(client, 'yesterday') I had to look deeply into the HTTP RFCs to do this, and also snoop the traffic for a "real" session to see what went on between server and client. /Jorgen -- // Jorgen GrahnR'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: Trouble converting hex to decimal?
On Sat, 05 Feb 2005 06:51:32 -0700, Earl Eiland <[EMAIL PROTECTED]> wrote: > I'm trying to process the IP packet length field, as recorded by pcap > (Ethereal) and recovered using pcapy. When I slice out those bytes, I > get a value that shows in '\x00' format, rather than '0x00'. Neither > int() nor eval() are working. How do I handle this? >From my unpublished protocol analyzing hack: class Ip: "IPv4 header" def __init__(self, frame): (vi, tos, tlen, id, ffoff, ttl, proto, checksum, source, dest) = struct.unpack('! BBH HH BBH LL', frame[:20]) self.len = 4 * (vi & 0xf) if proto==6: self.proto=Tcp elif proto==17: self.proto=Udp elif proto==1: self.proto=Icmp self.source = Address(source) self.dest = Address(dest) That doesn't take IP options into account (or are they part of Ip.len? I forget.), but it has the nifty feature that IP.proto tells the caller what factory function (if any) she should feed the rest of the frame into. /Jorgen -- // Jorgen GrahnR'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
Nick Coghlan <[EMAIL PROTECTED]> wrote: > Alex Martelli wrote: > > 'global' is an ugly wart, to all intents and purposes working "as if" it > > was a declaration. If I had to vote about the one worst formal defect > > of Python, it would surely be 'global'. > > > > Fortunately, it's reasonably easy to avoid the ugliness, by avoiding > > rebinding (within functions) global variables, which tend to be easy. > > Hear, hear! And if I could write "gbls = namespace(globals())" in order to > deal with those rare cases where I *do* need to rebind globals, all uses > of the keyword could be handled nicely, while entirely eliminating the > need for the keyword itself. I entirely agree with you on this. > Would you be as violently opposed to a 'rebinding' augmented assignment operator? Not at all. The only downside I can see, and it seems a minor one to me, is having two "obvious ways" to re-bind a name, since '=' would keep working for the purpose. But making it explicit that one IS rebinding a name rather than binding it anew could sometimes make certain code more readable, I think; quite apart from possible advantages in catching typos (which may be OK, but appear minor to me), the pure gain in reaability might make it worth it. Call my stance a +0. > the problem of detecting typos in the right-most name in a compound name (e.g. It's not clear to me what semantics, exactly, x.y := z would be defined to have (assuming := is the syntax sugar for ``rebinding''). Perhaps, by analogy with every other augmented operator, it should be equivalent to: _temp = x.y x.y = type(temp).__irebind__(temp, z) This makes it crystal-clear what happens when type(x).y is a descriptor with/without __set__ and __get__, when type(x) defines __getattribute__ or __setattr__, etc, etc. Giving type object an __irebind__ which just returns the second operand would complete the semantics. Of course, doing it this way would open the issue of types overriding __irebind__, and it's not clear to me that this is intended, or desirable. So, maybe some other semantics should be the definition. But since "rebinding" is not a primitive, the semantics do need to be somehow defined in terms of elementary operations of getting and setting (of attributes, items, &c). > Did I mention the possible incidental benefit of reducing the whinging > about the lack of variable declarations? It might, with some luck;-). Probably worth a PEP, although I suspect it will not be considered before 3.0. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE history, Python IDE, and Interactive Python with Vim
Hi, Ashot wrote: > This is sort of both Python and Vim related (which is why I've posted to > both newsgroups). [...] I know you've been using ipython recently (the readline color bugs), so perhaps my reply is a bit redundant. Forgive me if that's the case, I just want to give you some useful info. Just in case you haven't come across these features (the manual is kind of long and dry), I should note that ipython has pretty much everything you've asked for here. %hist -n dumps your history without line numbers (for copy/paste), %logstart gives you an incremental log (valid python code) of your current session, %save allows you to save a selected group of lines to a file, and %edit will open up $EDITOR (or vi in Unix by default) at the source of any accessible object. With %pdb, you can even trigger automatically pdb at any uncaught exception (in Emacs, you'll even get the source simultaneously opened, I'm sure something similar could be done for vi). Ipython is not an IDE, but it does offer an extensible command-line environment which tries hard to be very efficient. Hopefully this year I'll be able to work on integrating it (optionally, since it will never lose its command-line functionality) with GUIs as well. Regards, f -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
On Sat, 5 Feb 2005 17:00:15 +0100, [EMAIL PROTECTED] (Alex Martelli) wrote: > >I consider this one of the worst ideas to have been proposed on this >newsgroup over the years, which _IS_ saying something. \ I would disagree, but only to the extent that nothing that is only a request for an option toggle should qualify for this award. For anyone not interested in it's effects, it's business as usual. They can even reward themselves with the knowledge that among the time and typing they did not waste was in asking for the toggle to be on. It is also true that mplementation might be a diversion of efforts from the implementation of features solving more generally recognized problems. There *are* a lot of bad things to say about the idea. But I think it worth mentioning that the OP is requesting only a toggle. Why is it worth mentioning? Because maybe one needs to save the heaviest rhetoric for when this is not the case. There was a simple answer to those who hate decorators - don't use them. I won't. And the most controversial suggestions about optional static typing all perserve their sanity by remaining suggestions about something defined as optional. Generally speaking, it might then be said to be good community poilcy to hold one's fire at least a bit if a feature request, or accepted PEP, will not impact one's own code writing beyond the extent one might choose it to. Though I do think there *should* be a worst feature request contest at PyCon, What is with this white space business, anyway? ;) Art -- http://mail.python.org/mailman/listinfo/python-list
Alternative to standard C "for"
Hi there, I am quite new to Python, and have a straight & simple question. In C, there is for (init; cond; advance). We all know that. In Python there are two ways to loop over i=A..B (numerical.): 1) i = A while ihttp://mail.python.org/mailman/listinfo/python-list
Re: Alternative to standard C "for"
> I am quite new to Python, and have a straight & simple question. > In C, there is for (init; cond; advance). We all know that. > In Python there are two ways to loop over i=A..B (numerical.): > 1) i = A >while i ...do something... > i+=STEP This is indeed quite ugly. You rarely need such loops in Python and with some thinking you can often translate the C-equivalent to something more pythonic. As you guessed, your second problem is best solved with a generator function - xrange(). It is completely equal to range() except that it returns a generator instead of a list. -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Re: Alternative to standard C "for"
[EMAIL PROTECTED] writes: > problem. If i do ..in range(1, 1).. (what I really need > sometimes), it takes few hundred megs of memory and slows > down. Are there other good ways for this simple problem? Generators? use xrange instead of range. -- http://mail.python.org/mailman/listinfo/python-list
Re: Alternative to standard C "for"
[EMAIL PROTECTED] wrote: > Are there other good ways for this simple problem? Generators? Very interesting problem :) That never occured to me. To prevent python from loading that entire list into memory, one could, as you suggested, use a generator: >>> def genrange( start , stop , step = 1 ): while start < stop: yield start start += step >>> for x in range( 5 ): print "%s " % str( x ), 0 1 2 3 4 >>> for x in genrange( 0 , 5 ): print "%s " % str( x ), 0 1 2 3 4 -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Alternative to standard C "for"
Paul Rubin wrote: > use xrange instead of range. Woops ;) I wasn't aware such a function existed. apologies-for-reinventing-the-wheel-ly y'rs, -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
Arthur <[EMAIL PROTECTED]> wrote: > On Sat, 5 Feb 2005 17:00:15 +0100, [EMAIL PROTECTED] (Alex Martelli) > wrote: > > > >I consider this one of the worst ideas to have been proposed on this > >newsgroup over the years, which _IS_ saying something. \ > > I would disagree, but only to the extent that nothing that is only a > request for an option toggle should qualify for this award. For > anyone not interested in it's effects, it's business as usual. You must have lead a charmed life, I think, unusually and blissfully free from pointy-haired bosses (PHBs). In the sublunar world that most of us inhabit, ``optional'' idiocies of this kind soon become absolutely mandatory -- thanks to micromanagement by PHBs. For the last few years I've been working as a consultant -- mostly (thanks be!) for a wonderful Swedish customer whose managers are in fact great techies, but otherwise for a fair sample of typical development shops. Such "fair samples" have weaned me from my own mostly-charmed blissful life, confirming that the amount of utter stupidity in this world is REALLY high, and far too much is that is in management positions. Now, I've recently had a great offer to work, doing mostly Python, for another incredibly great firm, and, visa issues permitting, I'll gladly leave the life of consultants' joys and sorrows behind me again -- I've spent most of my life working as a full-time employee for a few great firms, and the last few years have confirmed to me that this fits my character and personality far better than being a consultant does (just like the years between my two marriages have confirmed to me that I'm better suited to be a husband, rather than a roving single... I guess there's a correlation there!-). So, I'm not speaking for selfish reasons: at my soon-to-be employer, techies rule, and optional idiocies won't matter much. I _am_ speaking on behalf of maybe half of the million or so Python programmers in the world, who are NOT so lucky as to be working in environments free from the blight of micromanagement. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Alternative to standard C "for"
BJörn Lindqvist wrote: >> I am quite new to Python, and have a straight & simple question. >> In C, there is for (init; cond; advance). We all know that. >> In Python there are two ways to loop over i=A..B (numerical.): >> 1) i = A >>while i> ...do something... >> i+=STEP > > This is indeed quite ugly. You rarely need such loops in Python and > with some thinking you can often translate the C-equivalent to > something more pythonic. As you guessed, your second problem is best > solved with a generator function - xrange(). It is completely equal to > range() except that it returns a generator instead of a list. Slight terminology glitch -- it does return an iterator, not a generator. Generators are functions that return iterators. regards, Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: changing local namespace of a function
Alex Martelli wrote: Hmmm, you do realize that wrapdict uses a lot of indirection while my equivalent approach, just posted, is very direct, right? To reiterate the latter, and dress it up nicely too, it's class wrapwell(object): def __init__(self, somedict): self.__dict__ = somedict Bad mistake on my part, sorry! Nick Coghlan wrote: ... a class that combined property access with the above... In a similar vein to Nick's solution: class AutoProperty(object): def __init__(self, meth): self.meth = meth self.name = meth.__name__ self.__doc__ = meth.__doc__ def __get__(self, obj, cls): if isinstance(obj, cls): return obj.__dict__.setdefault(self.name, self.meth(obj)) else: return self.__doc__ # You could define __set__ and __del__ but they don't seem # necessary based on what you've said so far class DataManipulator(object): def __init__(self, data): self.__dict__ = data class Model(DataManipulator): def z(self): """x+y""" return self.x+self.y z = AutoProperty(z) def z1(self): """Or any other useful information""" return self.z + self.x z1 = AutoProperty(z1) # You could automate these calls to AutoProperty in a metaclass >>> a = {'x':1, 'y':2} >>> b = {'x':3, 'y':3} >>> d = Model(a) >>> d.z 3 >>> d.z1 4 >>> a {'y': 2, 'x': 1, 'z': 3, 'z1': 4} >>> d= Model(b) >>> d.z1 9 >>> b {'y': 3, 'x': 3, 'z': 6, 'z1': 9} >>> Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: empty classes as c structs?
Nick Coghlan wrote: Steven Bethard wrote: Yes -- help me rally behind my generic object PEP which proposes a Bunch type (probably to be renamed) for the Python standard lib. =) Did you see the suggestion of 'namespace' as a name? Yup, it's in the current PEP draft. See the "Open Issues" section: PEP: XXX Title: Generic Object Data Type Version: $Revision: 1.0 $ Last-Modified: $Date: 2004/11/29 16:00:00 $ Author: Steven Bethard <[EMAIL PROTECTED]> Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 29-Nov-2004 Python-Version: 2.5 Post-History: 29-Nov-2004 Abstract This PEP proposes a standard library addition to support the simple creation of 'generic' objects which can be given named attributes without the need to declare a class. Such attribute-value mappings are intended to complement the name-value mappings provided by Python's builtin dict objects. Motivation == Python's dict objects provide a simple way of creating anonymous name-value mappings. These mappings use the __getitem__ protocol to access the value associated with a name, so that code generally appears like:: mapping['name'] Occasionally, a programmer may decide that dotted-attribute style access is more appropriate to the domain than __getitem__ style access, and that their mapping should be accessed like:: mapping.name Currently, if a Python programmer makes this design decision, they are forced to declare a new class, and then build instances of this class. When no methods are to be associated with the attribute-value mappings, declaring a new class can be overkill. This PEP proposes adding a simple type to the collections module of the standard library that can be used to build such attribute-value mappings. Providing such a type allows the Python programmer to determine which type of mapping is most appropriate to their domain and apply this choice with minimal effort. Some of the suggested uses include: Returning Named Results --- It is often appropriate for a function that returns multiple items to give names to the different items returned. The type suggested in this PEP provides a simple means of doing this that allows the returned values to be accessed in the usual attribute-style access:: >>> def f(x): ... return Bunch(double=2*x, squared=x**2) ... >>> y = f(10) >>> y.double 20 >>> y.squared 100 Representing Hierarchical Data -- The type suggested in this PEP also allows a simple means of representing hierarchical data that allows attribute-style access:: >>> x = Bunch(spam=Bunch(rabbit=1, badger=[2, 3, 4]), ham='neewom') >>> x.spam.badger [2, 3, 4] >>> x.ham 'neewom' Rationale = As Bunch objects are intended primarily to replace simple, data-only classes, simple Bunch construction was a primary concern. As such, the Bunch constructor supports creation from keyword arguments, dicts, and sequences of (attribute, value) pairs:: >>> Bunch(eggs=1, spam=2, ham=3) Bunch(eggs=1, ham=3, spam=2) >>> Bunch({'eggs':1, 'spam':2, 'ham':3}) Bunch(eggs=1, ham=3, spam=2) >>> Bunch([('eggs',1), ('spam',2), ('ham',3)]) Bunch(eggs=1, ham=3, spam=2) To allow attribute-value mappings to be easily combined, the Bunch type provides a update staticmethod that supports similar arguments:: >>> bunch = Bunch(eggs=1) >>> Bunch.update(bunch, [('spam', 2)], ham=3) >>> bunch Bunch(eggs=1, ham=3, spam=2) Note that update is available through the class, not through the instances, to avoid the confusion that might arise if an 'update' attribute added to a Bunch instance hid the update method. If Bunch objects are used to represent hierarchical data, comparison of such objects becomes a concern. For this reason, Bunch objects support object equality which compares Bunch objects by attributes recursively:: >>> x = Bunch(parrot=Bunch(lumberjack=True, spam=42), peng='shrub') >>> y = Bunch(peng='shrub', parrot=Bunch(spam=42, lumberjack=True)) >>> z = Bunch(parrot=Bunch(lumberjack=True), peng='shrub') >>> x == y True >>> x == z False Note that support for the various mapping methods, e.g. __(get|set|del)item__, __len__, __iter__, __contains__, items, keys, values, etc. was intentionally omitted as these methods did not seem to be necessary for the core uses of an attribute-value mapping. If such methods are truly necessary for a given use case, this may suggest that a dict object is a more appropriate type for that use. Examples = Converting an XML DOM tree into a tree of nested Bunch objects:: >>> import xml.dom.minidom >>> def getbunch(element): ... result = Bunch() ... if element.attributes: ... Bunch.update(result, element.attributes.items()) ... children = {} ... for child in element.childNodes: ... if child.nodeType == xml.dom.minidom.Node.TEXT_NODE: ...
Re: Alternative to standard C "for"
> First case looks quite nasty, because it's for more complicated > things, not numerical loops. Second is very nice, but with there's > problem. If i do ..in range(1, 1).. (what I really need > sometimes), it takes few hundred megs of memory and slows > down. Are there other good ways for this simple problem? Generators? Use xrange(). It computes the values as they are needed - not an entire list. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: empty classes as c structs?
Nick Coghlan wrote: Alex Martelli wrote: Nick Coghlan <[EMAIL PROTECTED]> wrote: ... Michael Spencer also posted an interesting idea recently about setting up a view of an existing dictionary, rather than as a separate object: class attr_view(object): def __init__(self, data): object.__setattr__(self, "_data", data) def __getattr__(self, attrname): return self._data[attrname] def __setattr__(self, attrname, value): self._data[attrname] = value Wasted indirection, IMHO. A better implementation: class attr_view(object): def __init__(self, data): self.__dict__ = data I think the idea definitely deserves mention as a possible implementation strategy in the generic objects PEP, with the data argument made optional: That's basically what the current implementation does (although I use 'update' instead of '='). The code is complicated because the implementation also takes all the argument types that dicts take. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Which IDE supports python and wxpython?
Hello all, Is there a good IDE on the market which supports python and wxpython. Goal is to use it in a big distributed project. Greetings -- http://mail.python.org/mailman/listinfo/python-list
Re: Alternative to standard C "for"
Georg Brandl <[EMAIL PROTECTED]> wrote: > Slight terminology glitch -- it does return an iterator, not a > generator. Generators are functions that return iterators. xrange returns an ITERABLE, not an ITERATOR. Videat: >>> a = xrange(23, 43) >>> a.next() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'xrange' object has no attribute 'next' >>> No next method -> not an iterator. iter(xrange(...)) DOES return an iterator, btw. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Which IDE supports python and wxpython?
I know of two: Boa Constructor: http://boa-constructor.sourceforge.net/ wxGlade: http://wxglade.sourceforge.net/ -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ -- http://mail.python.org/mailman/listinfo/python-list
access problem with DCOM server written in python
Hi, I have a problem with a DCOM server written in python. Here is my minimal test object: class TestObject: _reg_clsid_ = "{ECDBB3BC-F0BF-4eef-87C0-D179A928DAB5}" _reg_progid_ = "DComTest.Object" _reg_desc_ = "DComTest.Object" _public_methods_ = ['testit'] def __init__(self): pass def testit(self): pass if __name__=='__main__': # register object from win32com.server.register import UseCommandLine UseCommandLine(TestObject) The object is registered on server S and on client C. The user U exists on both machines with the same password. Accessing 'normal' C++ COM objects from C on S works fine, which means the DCOM is working at all. U is able to create the object localy, but accessing my test object via DCOM gives me an 'access denied'. I used dcomcnfg to grand U the right to start and access the object on S (same settings as for working C++ objects), but I still get 'access denied'. The server was newly setup. The script was working on another setup, but I have no idea what might be the differnce. BTW: Accessing the object with an admin account works just fine. Any hint on how to solve, or at least debug, the problem? regards, Achim -- http://mail.python.org/mailman/listinfo/python-list
Re: Alternative to standard C "for"
Alex Martelli wrote: > Georg Brandl <[EMAIL PROTECTED]> wrote: > >> Slight terminology glitch -- it does return an iterator, not a >> generator. Generators are functions that return iterators. > > xrange returns an ITERABLE, not an ITERATOR. Videat: > a = xrange(23, 43) a.next() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'xrange' object has no attribute 'next' > > No next method -> not an iterator. iter(xrange(...)) DOES return an > iterator, btw. Thanks! Somehow it's always these little corrections that contain errors. And, considering your other posts today, I got away quite well... Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: "Collapsing" a list into a list of changes
Alan McIntyre wrote: > Tony, > > Actually I only want to remove a certain kind of duplication; How about this one liner? def condense(m): print [m[0]]+[m[k] for k in range(1,len(m)) if m[k]!=m[k-1]] b=[1,1,1,2,2,2,1,1,1] condense(b) Tony Clarke -- http://mail.python.org/mailman/listinfo/python-list
Re: [EVALUATION] - E01: The Java Failure - May Python Helps?
On Sat, 05 Feb 2005 16:44:11 +0200, Ilias Lazaridis wrote: >> * Deployment: I don't generally have enough problems with this to be >> worth thinking about. I don't know what the state of the remote >> debugging is on Python; Google "remote debugging Python". > > [I like to avoid interaction with google.] OK, this, combined with a reputation that didn't quite precede you, but came close, leads me to say this: I've given you what you're going to get. You want more, you're going to have to put some effort into it. Lots of effort. But I can give you this: If you aren't already there, you're a textbook case of somebody heading for analysis paralysis. It's time to stop researching and start programming; grab Python, do a couple tutorials, and start acquiring the skills you're going to need to do these other tasks you want to do anyhow. Barring evidence that you are taking responsibility for yourself, I'm not inclined to help much more. -- http://mail.python.org/mailman/listinfo/python-list
Re: empty classes as c structs?
Alex Martelli wrote: Nick Coghlan <[EMAIL PROTECTED]> wrote: ... Michael Spencer also posted ... Wasted indirection, IMHO. A better implementation: class attr_view(object): def __init__(self, data): self.__dict__ = data Alex Indeed! A complete brain-blip Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: empty classes as c structs?
Steven Bethard wrote: Nick Coghlan wrote: class attr_view(object): def __init__(self, data): self.__dict__ = data I think the idea definitely deserves mention as a possible implementation strategy in the generic objects PEP, with the data argument made optional: That's basically what the current implementation does (although I use 'update' instead of '='). The code is complicated because the implementation also takes all the argument types that dicts take. STeVe Have you noted the similarity of bunch and types.ModuleType? perhaps module.__init__ could take an additional keyword argument to set its __dict__ Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Which IDE supports python and wxpython?
Try SPE, I just released (GPL) a new version: http://spe.pycs.net Stani http://www.stani.be -- http://mail.python.org/mailman/listinfo/python-list
Re: empty classes as c structs?
Steven Bethard said unto the world upon 2005-02-05 14:05: Nick Coghlan wrote: Steven Bethard wrote: Yes -- help me rally behind my generic object PEP which proposes a Bunch type (probably to be renamed) for the Python standard lib. =) Did you see the suggestion of 'namespace' as a name? Yup, it's in the current PEP draft. See the "Open Issues" section: PEP: XXX Title: Generic Object Data Type Version: $Revision: 1.0 $ Last-Modified: $Date: 2004/11/29 16:00:00 $ Author: Steven Bethard <[EMAIL PROTECTED]> Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 29-Nov-2004 Python-Version: 2.5 Post-History: 29-Nov-2004 Open Issues === What should the type be named? Some suggestions include 'Bunch', 'Record', 'Struct' and 'Namespace'. A quick check of the google groups archive didn't lead me to believe that I'm repeating old suggestions, so: how about 'Bag'? It's has the small virtue of being short and the great virtue of employing a good metaphor, I think. A (loose enough) bag takes whatever shape you impose on it by the things that you stick into it. If I understand the PEP draft aright, the idea is quite similar -- a python object with no internal structure other than that imposed by what the programmer decides to put into it. (I'm just a hobbyist, so if this suggestion clashes with some well established use of 'Bag' in CS terminology, well, never mind.) Best to all, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list