Re: . is a good idea! (OT, was: Re: do you master list comprehensions?)
I wrote: Kent Johnson wrote: You can do the same thing using a PYTHONSTARTUP file - see http://docs.python.org/tut/node4.html#SECTION00424 You can change the prompts with import sys sys.ps1 = ' ' sys.ps2 = ' ... ' Very cool. I didn't know about this. Does anyone know how to make it work with Pythonwin[1]? Solved my own problem here. For anyone else out there using PythonWin, the solution that worked for me is to put the following (or whatever customizations you want) in a sitecustomize.py somewhere on my PYTHONPATH: import sys sys.ps1 = 'py ' sys.ps2 = '... ' PythonWin (as well as my Command Prompt python) now has the above prompts. Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Complementary language?
Mike Meyer [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] (Alex Martelli) writes: Objective-C is cool... on the Mac; I'm not sure how well-supported it is elsewhere, though. In addition to C's advantages, it would let you make Cocoa GUIs on the Mac easily (with PyObjC c). But then, the right way to study Obj-C from scratch is no doubt to start with C, anyway. Objective-C is part of the Gnu Compiler Collection. As such, it's probably easy to find a working compiler. But I agree - you probably want to start with C. BTW, I wouldn't give the same advice re C++ -- if C++ is what you want to know you're probably better off studying C++ itself. But ObjC is neatly partitioned into two sublanguages... C plus a smalltalk-like OO part... and it seems to me that this makes C the natural starting point. As an aside, if you want to study Eiffel, the book to buy is _Object Oriented Software Construction_, second edition, by Bertrand Meyer. Everybody doing OO software should read this book, as the lessons about constructing inheritance hierarchies are invaluable, even if the language won't enforce them for you. Even though I'm not enthusiastic about Eiffel per se, I can second the recommendation about Meyer's book; it's interesting and instructive as one very thorough and well-developed vision of OOP. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Are tuple really immutable?
Chris wrote: 1) Given a tuple, how can I know if it can be a dictionnary key or not? Of course I could call __hash__ and catch for a TypeError exception, but I'm looking for a better way to do it. calling hash(obj) is the only sane way to figure out if calling hash(obj) will work. 2) Would it be possible to have a ismutable function or method? objects are mutable only if they have some method (visible or __hidden__) that can be used to modify their contents. from the Python runtime perspec- tive, objects are objects. 3) In this example, is t considered mutable or not? Tuple are immutable says the doc, but: t[0].append(0) t ([1, 0], [2]) The tuple is immutable but its elements can be mutable: I tend to think that it means that the tuple is mutable. Indeed, it changed! as map(id, t) can tell you, the tuple object itself wasn't modified. 4) Even more confusing: I had the following strange result: (with both Python 2.3.3 and 2.4) t[0]+=[1] Traceback (most recent call last): File stdin, line 1, in ? TypeError: object doesn't support item assignment t ([1, 0, 1], [2]) There was an exception, but the list was still changed!? that's a silly side-effect of how += is defined for lists; the + part of the expression works, and modifies the target object, but the = part fails. /F -- http://mail.python.org/mailman/listinfo/python-list
built-in 'property'
Title: Message Hi Can any one explain how property works. It seems to be fine if executed on import i.e. if the property statement is at class scope. If I put the statement inside __init__() then it appears to work ok but when I try to access the property by e.g. klass.x it just tells me it is a property object. Is this statement only designed to work at class scope? I really want to set these properties per instance. Thanks Bob Bob Cowdery CGI Senior Technical Architect +44(0)1438 791517 Mobile: +44(0)7771 532138 [EMAIL PROTECTED] *** Confidentiality Notice *** Proprietary/ConfidentialInformation belonging to CGI Group Inc. and its affiliatesmay be contained in this message. If you are not a recipientindicated or intended in this message (or responsible fordelivery of this message to such person), or you think forany reason that this message may have been addressed to youin error, you may not use or copy or deliver this messageto anyone else. In such case, you should destroy thismessage and are asked to notify the sender by reply email. -- http://mail.python.org/mailman/listinfo/python-list
Re: Improving Python (was: Lambda going out of fashion)
Dima Dorfman wrote: I happen to not mind the ''.join syntax, but if I did, I would use str.join('', seq) which is just like a join builtin except that it's not as easy to make it work on pre-string-method Pythons. just like join, except that it isn't: string.join(seq, sep) u'axbxc' sep.join(seq) u'axbxc' str.join(sep, seq) Traceback (most recent call last): File stdin, line 1, in ? TypeError: descriptor 'join' requires a 'str' object but received a 'unicode' /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional Static Typing - Haskell?
Donn Cave [EMAIL PROTECTED] wrote: ... And you probably think Eiffel supports fully modular programming, as I thought Objective CAML did. But Alex seems not to agree. Rather, I would say it's Dr Van Roy and Dr Haridi who do not agree; their definition of truly open programming being quite strict, based on modules not having to know anything about each other. BTW, while I have looked into Alice yet, some people posting on this thread apparently have -- I know the Alice whitepaper claims Alice adds to ML just what is needed to support truly open programming -- features that OCAML doesn't have, so, if the Alice researchers are right, your assessment of OCAML is wrong; OTOH, since Alice _is_ statically typed like any other ML dialect, they'd appear to rebut Van Roy and Haridi's contention, too. VR H do mention Alice at the end of their pages about static vs dynamic typing but they don't appear to acknowledge the claim. Maybe it all boils down to both Oz and Alice being still open research efforts, making it difficult to assess fully what results they can eventually achieve. The way I understand it, his criteria go beyond language level semantics to implementation details, like whether a change to a module may require dependent modules to be recompiled when they don't need to be rewritten. Ah yes, definitely: Lakos' Large Scale C++ Software Design was the first place where I met a thorough exposition of the evil effects that come from modules just needing to be recompiled, not rewritten as soon as the number of modules becomes interestingly large, at least with the kind of dependency graphs that naturally emerge when designers are focused on all other important issues of software design rather than dependency control. Basically, what emerges from Lakos' analysis, and gets formalized in Robert Martin's precious dependency inversion principle, is the equivalent of the interface/implementation separation that you always get e.g. in Corba, by writing the interface in IDL and the implementation in whatever language you wish: both implementation and client modules depend on an abstract-interface module, so the dependency arrows go the right way (concrete depends on abstract) and the cycle is more tractable. But if you proceed by extracting the abstract interface from a concrete implementation, that's a dependency too (albeit for a tool that's not the compiler), and it's the wrong way around... abstract depends on concrete. (Main hope being that the abstract part changes VERY rarely -- when it DOES change, the rebuild cost is still potentially out of control). You may use a separate language to express the interface (IDL, whatever), you may use a subset of the implementation language with strict constraints, but one way or another, if you want to control your dependency graph and avoid the ills Lakos points out so clearly, dependency inversion is an indispensable (perhaps not sufficient) tool. Mike points out this breaks once and only once, but then that same principle is broken in any language where you express the type of a variable twice -- in declaring AND in using it -- as is typical of most statically-typed languages (even where the language does not mandate the redundancy, as in *ML or Haskell, typical style in such languages is to have the redundancy anyway; and AFAIK Eiffel _does_ mandate the redundancy, just like C++ or Java do). Dynamic languages have dependencies too, maybe not reified but conceptually, _operationally_ there. For example, if you consider the contract (as in DbC) to be part of a type, that's how Eiffel works: it diagnoses the type violation (breach of contract) dynamically, at runtime. And that's how's Oz, Python, Ruby, Erlang, etc etc, work too: no type (signature, contract, ...) violation along any dependency arrow need pass silently, they're diagnosed dynamically just like DbC violations in Eiffel or more generally violations of other constraints which a given language chooses not to consider type-related (e.g., if the positive-reals are a separate type from general reals, sqrt(x) with x0 is a type violation -- if there's only a general reals type, it's not -- hopefully, it's diagnosed at runtime, though). Robert Martin's Dynamic Visitor design pattern is, I believe, an instructive case. The classic Visitor, per se, has intractable dependency problems and cannot possibly respect fully the open/closed principle; Dynamic Visitor uses the escapes to dynamic typing allowed by such tools as C++'s dynamic_cast (and Java's own casts, which work quite similarly) to ensure a sane dependency structure. If you don't have or don't allow any escape from static typing, Visitor is somewhat of a nightmare DP as soon as the kinds of visitors and visitees start multiplying -- at the very least it's a build-time nightmare, even if your language has tricks to save the need to change the code. Martin does a much more thorough job of exploring these issues and I'll point to his
Re: Unicode entries on sys.path
On Thu, 23 Dec 2004 19:24:58 +0100, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= [EMAIL PROTECTED] wrote: Thomas Heller wrote: It seems that Python itself converts unicode entries in sys.path to normal strings using windows default conversion rules - is this a problem that I can fix by changing some regional setting on my machine? You can set the system code page on the third tab on the XP regional settings (character set for non-unicode applications). This, of course, assumes that there is a character set that supports all directories in sys.path. If you have Japanese characters on sys.path, you certainly need to set the system locale to Japanese (is that CP932?). Changing this setting requires a reboot. Hm, maybe more a windows question than a python question... The real question here is: why does Python not support arbitrary Unicode strings on sys.path? It could, in principle, atleast on Windows NT+ (and also on OSX). Patches are welcome. What about removable drives? And mountable multiple file system types? Maybe some collections of potentially homogenous file system references such as sys.path need to be virtualized to carry relevant file system encoding and protocol info etc. That could cover synthetic or compressed info sources too, IWT. Homogeneous package representation could be a similar problem, I guess. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricks to install/run Python on Windows ?
It's me a écrit : Try running with the latest version of Python 2.3 instead of 2.4. May be you would have better luck. I've found similar stability problems with some of the tools (eventhough they have 2.4 releases) as well. I switched back to 2.3 and so far I have no complains. So far i remember, I'll have no prob. using Python 2.3 (and the PythonWin distro for 2.3), yes. For now, I'm trying WingIDE, and all seems good. A little slow, but for now, it works without surprise. Thanks a lot to all of you. PS:I'll also have a look at DrPython later. StepH [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hi, I'm new to Python. I'm working under XP, and I've alot of prob. (not with the langage itself, but with the tools): I've install Pyhton 2.4 in C:\Python24, using the .msi windows installer. Then, I've install PythonWin (the last build-203). I'll try to summerize my prob.: 1./ The PythonWin IDE is not stable at all. Sometimes it exit without reason, or don't stop on breakpoint, etc... Are some of you aware of bugs in the last PyhtonWin IDE release ? I've to open the TaskManager. AT some point, i'm not able to (p.e.) open a file under it !!! 2./ I've try to download Komode (he 3.1 personnal). I've also prob. with it ! Also, the breakpoint seems to not always work... 3./ So, i've try to use the command line, but i've to manualy change the code page od my dos box from 437 to 1252 (i'm live in belgium). And i've not try how to do that permanently ! 4./ Before, I had Python23 and it seems that when unstalling it, all the keys in the registry are not removed at all. When i've install the 2.4, I had a mismatch which force me to complety re-install the machine (I'm not an expert of the registry)... 5./ Installing komodo seems to block pythonwinIDE completly... What's wrong ? Python seems terific, but the tools... So... maybe i've to try BlackAdder ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Are tuple really immutable?
Chris [EMAIL PROTECTED] wrote: ... 3) In this example, is t considered mutable or not? Tuple are immutable says the doc, but: t[0].append(0) t ([1, 0], [2]) The tuple is immutable but its elements can be mutable: I tend to think that it means that the tuple is mutable. Indeed, it changed! Maybe the last page of http://mail.python.org/pipermail/python-list/2002-April/099227.html can help with this conceptual issue. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: AttributeError of a module instance
Terry Reedy wrote: I'd like to catch AttributeError on the module level,so that I can declare default bindings for useds defore definition.How is this to be done? 'defore' is obviously 'before', but what is 'useds'? In and case... Unresolved bindings,possibly like _rdf_type Traceback (most recent call last): File stdin, line 1, in ? NameError: name '_rdf_type' is not defined If you are asking for the module equivalent of __getattr__ class methods, there is none. Modules are namespaces. They are like dicts but minus the dict methods and with .attribute instead of ['attribute'] access. This is possible because all 'keys' are names (hence 'namespace'). In the previous example I'd like to see an answer like 'rdf:type' even if I never defined it.Is this not possible?I use __getattr__ in other situations,and it's very useful for proxying procedures,I was hoping on a real objectivation of a module. Why the language should not consider a module as a 'normal' instance with 'normal' attributes? Sorry for my language skills.Paolino -- http://mail.python.org/mailman/listinfo/python-list
Re: list IndexError
Scott David Daniels [EMAIL PROTECTED] wrote: Ishwor wrote: On Thu, 23 Dec 2004 13:57:55 -0300, Batista, Facundo [EMAIL PROTECTED] wrote: #- True, true. Maybe you could lobby for copy as a builtin in #- Python 3000? That's a good idea to me. But copy() as a builtin is not clear if it's shallow or deep. IMHO its preferable to use shallow one as the built-in because deep is expensive op. for CPU. ~;-) deepcopy is an operation that is less well defined than shallow copy anyway (and hence shouldn't be a default). Objects representing constants may contain a cache (for example) as an efficiency measure, and deepcopy needn't copy such objects. The only way to safely do deepcopy is to copy down to immutables, but usually there is a shallower and faster implementation that depends on application semantics. Well, that's what methods __copy__ and __deepcopy__, or the often-preferable __getstate__ and __setstate__, are all about -- letting your classes explicitly define what IS the state (that needs to be copied) of their instances. I don't see how that changes between copy/deepcopy being built-ins or being in a standard library module like today. Yes, deep copy is way more involved and expensive that shallow copy, etc, etc, but, again, this holds whether they're built-ins or come from a standard library module. I guess I must be missing something...? Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Mike Meyer wrote: Yup. Thank you. This now reads: Regarding str() and repr() behaviour, repr() will be either ''rational(num)'' if the denominator is one, or ''rational(num, denom)'' if the denominator is not one. str() will be either ''num'' if the denominator is one, or ''(num / denom)'' if the denominator is not one. Is that acceptable? Sounds fine to me. On the str() front, I was wondering if Rational(x / y) should be an acceptable string input format. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Improving Python
Aahz wrote: In article [EMAIL PROTECTED], Fredrik Lundh [EMAIL PROTECTED] wrote: func(*arg) instead of apply() is a step back -- it hides the fact that functions are objects, and it confuses the heck out of both C/C++ programmers and Python programmers that understand the def func(*arg) form, because it looks like something it isn't (there's a false symmetry between the call-form and the def-form). For me, it works the other way around, but I can see how you perceive it that way. and I still do enough 1.5.2-programming to use x = x + y; when I find myself in a situation where my code would benefit a lot from being able to write x += y instead, I go back and fix the design. Okay, it wasn't clear in your original post that you're still stuck with 1.5.2. That makes a huge difference in the convenience of newer features. I haven't corresponded specifically with Fredrik about this, bit I get the impression he *chooses* to continue to produce 1.5.2-compatible products. I for one, having suffered at the hands of modules that *claim* 1.5.2 compatibility (and then screw you by using dict()!), appreciate the time he takes to do so. A summary of how to maintain such compatibility might make Python apps more accessible - how many of us can say that our code would run on a Red Hat 7 system any more? The sad thing is that it's often fairly trivial changes that remove backwards-compatibility. string methods are nice, but nothing groundbreaking, and their niceness is almost entirely offset by the horrid .join(seq) construct that keeps popping up when people take the the string module is deprecated yada yada too seriously. and what do the python-devers do? they add a sum built-in, but no join? hello? Well, I guess we have to accept that not every change to the language is going to be well-thought-out and completely desirable. While I'm in complete agreement about the .join() construct on the basis of looks, I have come to appreciate the fact that I *never* mess up the order of arguments any more. Personally that's one of the changes I managed to take in my stride, and I've never really felt it was a biggie. Maybe my code is just so ugly that a little extra ugliness isn't noticeable? horses-for-courses-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating Image Maps
Aaron wrote: Thanks for the responses guys! The first option you provided sounds great, Steve. I think I'm gonna try it that way. OK. It's usually the easiest way if the subsections are at all regular. If they are irregular it's often the *only* way! This is a technique that can also be used on the web (Google for client-side image map), but it's very little-used there. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
RE: A Revised Rational Proposal
Title: RE: A Revised Rational Proposal [Mike Meyer] #- When combined with a floating type - either complex or float - or a #- decimal type, the result will be a TypeError. The reason for this is #- that floating point numbers - including complex - and decimals are #- already imprecise. To convert them to rational would give an I'm ok with raising TypeError when mixing with float. Bu tI think that it should interact with decimal, as decimal is not imprecise: you can go Decimal-Rational and viceversa without losing information. As I posted in a previous message: To convert a Decimal to Rational, just take the number and divide it by 1E+n: Decimal(5) - Rational(5) Decimal(5.35) - Rational(535, 100) To convert a Rational to a Decimal, it would be a good idea to have a method that converts the Rational to a Decimal string... Rational(5).tostring(6) - 5.0 Rational(4, 5).tostring(3) - 0.80 Rational(5321351343, 2247313131).tostring(5000) - whatever ... and then take that string as input to Decimal and it will work. #- - Should raising a rational to a non-integer rational #- silently produce #- a float, or raise an InvalidOperation exception? I think that it never should decay into float silently. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. -- http://mail.python.org/mailman/listinfo/python-list
RE: A Revised Rational Proposal
Title: RE: A Revised Rational Proposal [Dan Bishop] #- I disagree with raising a TypeError here. If, in mixed-type #- expressions, we treat ints as a special case of rationals, it's #- inconsistent for rationals to raise TypeErrors in situations #- where int #- doesn't. I think it never should interact with float. Rational is being precise by nature, and it should be made explicit when losing information (by the user, using float() to the Rational or str() or repr() to the float). . Facundo Bitácora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional Static Typing
Robert Kern wrote: Starkiller, at least, can deal with cases where a variable might be one of a set of types and generates code for each of this set. Explicit type declarations can help keep these sets small and reduces the number of times that Starkiller needs to fall back to PyObject_* calls. Will we be able to see it anytime soon? I'm eagerly waiting for its release. -- http://mail.python.org/mailman/listinfo/python-list
RE: A Revised Rational Proposal
Title: RE: A Revised Rational Proposal [Dan Bishop] #- * Binary operators with one Rational operand and one float or Decimal #- operand will not raise a TypeError, but return a float or Decimal. I think this is a mistake. Rational should never interact with float. #- * Expressions of the form Decimal op Rational do not work. This is a #- bug in the decimal module. Can you tell me where? (or submit a bug in SF). Thanks. #- * The constructor only accepts ints and longs. Conversions #- from float #- or Decimal to Rational can be made with the static methods: #- - fromExactFloat: exact conversion from float to Rational What ExactFloat means to you? For example, what should Rational.fromExactFloat(1.1) should return? And we starting here the same long discussion that lead decimal to not be created from float because it never would be clear what it will do. #- - fromExactDecimal: exact conversion from Decimal to Rational Rational already is created from strings like 2.33, so use str() over the Decimal, not a special method: import decimal decimal.Decimal(3.44) Decimal(3.44) str(decimal.Decimal(3.44)) '3.44' import rational rational.Rational(str(decimal.Decimal(3.44))) Rational(344 / 100) . Facundo Bitácora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
[EMAIL PROTECTED] wrote: Hi David, I'd be happy to post it to python-win32 but don't know how. Ian Send mail to [EMAIL PROTECTED] If you want to see it arrive you might join the list beforehand - go to www.python.org and follow the Mailing Lists link to find out how to subscribe. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting if a program is currently running.
Thanks, that does the trick. Mike Meyer [EMAIL PROTECTED] wrote in news:[EMAIL PROTECTED]: Yeah, but it takes work on both ends. You could wrap your mpg123 in a shell script like so: #!/bin/sh mpg123 $@ echo $! /tmp/mpg123.pid Or in python 2.4: #!/usr/bin/env python from subprocess import Popen p = Popen('mpg123') pidfile = file('/tmp/mpg123.pid', 'w') pidfile.write(%d % p.pid) pidfile.close() Then have your check program do (again, using the 2.4 subprocess module) from subprocess import Popen, PIPE try: pidfile = file('/tmp/mpg123.pid') except IOError: print 'mpg123 is dead' else: pid = pidfile.read() t = Popen('ps p %s' % pid, shell=True, stdout=PIPE).stdout if t.readlines() 2: print 'mpg123 is dead' os.remove('/tmp/mpg123.pid') return 0 return 2 Basically, instead of trusting grep to find mpg123, save the pid in a file and let ps find it (or not) by pid. mike -- http://mail.python.org/mailman/listinfo/python-list
Customizing interpreter behavior [was: Clearing the screen]
John Machin wrote: Ishwor wrote: i was just tinkering with it actually. ;-) In your command prompt just do Pythonwin.exe /run C:\Python24\file\PyFiles\clear.py It's not a very good idea to store your own scripts in the PythonXY directory -- other than tested working modules which you install in PythonXY\lib\site-packages. E.g. what will you do when Python 2.5 arrives? As has been recently pointed out in another thread, the interpreter (actually, code in the site module) searches for a sitecustomize module when starting up. This is the easiest way to implement required startup behavior no matter what environment the interpreter's running in. For more information, RTFM concerning the site module, whose documentation includes the following: After these path manipulations, an attempt is made to import a module named sitecustomize, which can perform arbitrary site-specific customizations. If this import fails with an ImportError exception, it is silently ignored. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: WxListBox
LutherRevisited wrote: I'm wanting to put a listbox in the place of a textctrl I'm using in my application because I'm running out of space in my textctrl. The online documentation is down at wxpython.org so I have no idea how to construct this control or anything. Can someone help me out. Here's what I'm doing with the WxTextCtrl: self.text_ctrl_4 = wx.TextCtrl(self, -1, , style=wx.TE_MULTILINE) sizer_1.Add(self.text_ctrl_4, 6, wx.LEFT|wx.RIGHT|wx.EXPAND, 80) self.text_ctrl_4.AppendText(str(count) + '\t\t' + str(address) + '\t\t' + str(pageNumber) + '\t\t' + str(pageArray[pageNumber, 1]) +'\r\n') I'm wanting to implement something similar with a listbox, any thoughts? Well, my *first* thought was Isn't a listbox supposed to allow choice between alternative? How can that substitute for what looks like a very complex text input? My second thought was It's not very helpful to use a name like 'text_ctrl_4' in the code. I'm also not really sure what the double-tabs are supposed to do. Perhaps you could explain exactly what you'd like your program to do here, as at present it's not even clear whether this code is intended to act as input as well as output? What's wrong with what happens now, and how would you like to change it? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: SimpleHTTPServer, queries unhandled?
Bryan Rasmussen wrote: Hey just doing some preliminary testing with SimpleHTTPServer, and i noticed that when i request a resource with a query string parameters that this was not handled. is this correct, or is there a method to set query string handling? Well, since SimpleHTTPServer doesn't implement CGIs, the only stuff it can serve up is static content, which clearly can't use any query string input anyway. You probably want CGIHTTPServer. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: Jython IronPython Under Active Development?
HackingYodel wrote: Cameron Laird wrote: In article [EMAIL PROTECTED], Robert Kern [EMAIL PROTECTED] wrote: . . . It should be noted that Jim Hugunin no longer works on Jython although he did start the project (possibly with others, I'm not sure). . . . Mostly he started it with others discouraging him, arguing, *That*'s one project that'll never fly. Short story at http://hugunin.net/story_of_jython.html from Jim himself. :) Just a little further background. The Python Software Foundation recently awarded a grant to help to bring Jython into line with the current CPython release. Jim Hugunin now works for Microsoft, and hopes to promote Python as a full member of the .NET environment. He'll be speaking at PyCon DC 2005 in March this year, and I hope that his talk will include some details of his experiences at Microsoft (though that's entirely up to Jim). regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Dan Bishop wrote: Steven Bethard wrote: Dan Bishop wrote: Mike Meyer wrote: PEP: XXX I'll be the first to volunteer an implementation. Very cool. Thanks for the quick work! For stdlib acceptance, I'd suggest a few cosmetic changes: No problem. Implementation of rational arithmetic. [Yards of unusable code] I'd also request that you change all leading tabs to four spaces! regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: Jython IronPython Under Active Development?
Steve Holden wrote: Just a little further background. The Python Software Foundation recently awarded a grant to help to bring Jython into line with the current CPython release. Is information publicly available about this and other PSF grants? I don't see any announcement on the PSF web site or in the grants-discuss mail list. Thanks, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Jython IronPython Under Active Development?
Kent Johnson wrote: Steve Holden wrote: Just a little further background. The Python Software Foundation recently awarded a grant to help to bring Jython into line with the current CPython release. Is information publicly available about this and other PSF grants? I don't see any announcement on the PSF web site or in the grants-discuss mail list. Thanks, Kent I know an announcement is to be made, but I can't tell you when to expect it. Certainly the intention is to be as open as possible about the grants process. hoping-i-haven't-jumped-the-gun-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on Linux
On Red Hat 9, Python is installed by default and it's version is 2.2.2 If I want to upgrade Python to 2.3.4(newer version), how could I do? If I compile source code of Python, how do I uninstall the old version? I tried rpm packages but failed with dependence. I didn't try the rpm's. Just get the source tarball, configure, make, and make install. That is also what I had to do under mdk, I then had to rename/hide the old executables and libraries -- http://mail.python.org/mailman/listinfo/python-list
Red Robin Jython JDK classes
I am trying to set up the Red Robin Jython Development Tools for Eclipse. It finds the Python libraries of Jython and my own jars. It does not find the JDK classes. If I try to add classes.jar from the JDK to the Jython Class Path of the project, the plug-in no longer finds even my own Java classes. How do I make the plug-in see the JDK classes? I am using Eclipse 3.0.1, Mac OS X 10.3.7, Java 1.4.2_05, Jython 2.1 and Red Robin Jython Development Tools 1.3.9. -- Henri Sivonen [EMAIL PROTECTED] http://iki.fi/hsivonen/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Interactive Shell - outputting to stdout?
Steve Holden wrote: Avi Berkovich wrote: Hey, I can't make it work, I don't get any data from either stdout nor stderr. If I send lines and then close the stdin pipe, I may get an exception message from several lines up. I tried manually reading from the stdout pipe, but it just blocks and hangs no matter what I send over via the stdin pipe. This behavior isn't presented by the command line interpreter by any chance. Any suggestions? Yes: post your code along with messages (if any)! regards Steve Sorry, for some reason I can no longer find the message you posted the code in -- it didn't get correctly threaded in Mozilla. Anyway, I can't say that I exactly understand what's going on, but here are a couple of observations: 1. The interpreter performs buffering even when running in interactive mode unless it can see a terminal (which here it can't). Hence adding a -u to the interpreter command line is useful. 2. There's a problem with your stop condition, which is why the attached modified version sleeps before closing the pipe to the interpreter. import threading import sys import popen2 class Piper(threading.Thread): def __init__(self, readPipe, output): threading.Thread.__init__(self) if not isinstance(readPipe, file): raise TypeError, readPipe parameter must be of File type #if not isinstance(output, file): #raise TypeError, output parameter must be of File type self.readPipe = readPipe self.output = output self.toStop = False def run(self): print Running while not self.toStop and not self.readPipe.closed: read = self.readPipe.readline() self.output.write(read) self.output.flush() print Stopped def stop(self): self.toStop = True if __name__ == __main__: r, w = popen2.popen4('c:\\python24\\python.exe -u') piper = Piper(r, sys.stdout) piper.start() w.write(print 'Hello!'\r\n) w.flush() w.write(print 'Goodbye!'\r\n) w.flush() import time; time.sleep(2) w.close() #import time; time.sleep(3) #r.close() piper.stop() Various other bits and pieces of messing about didn't really yield any useful conclusions, so I pass this on only in the hope that you may be more motivated to follow up now you can actually see some interpreter output. I would have thought the flush() calls would have made output appear one line at a time, but sadly they do not. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Mike ... or making them old-style classes, which is discouraged. Since when is use of old-style classes discouraged? Skip -- http://mail.python.org/mailman/listinfo/python-list
MDaemon Warning - virus found: Returned mail: see transcript for details
*** WARNING ** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. AttachmentVirus name Action taken -- mail.zip I-Worm.Mydoom.m Removed ** The original message was included as attachment -- http://mail.python.org/mailman/listinfo/python-list
RE: Best GUI for small-scale accounting app?
Title: RE: Best GUI for small-scale accounting app? From: Paul Rubin [mailto:http://phr.cx@NOSPAM.invalid] Dave Cook [EMAIL PROTECTED] writes: You might not care. And in that case Tk is much simpler than just about anything else, unless looks are really important. I've used tk and I don't think it's simpler than html. I've been doing webapps for 5 years now. *THE* thing that make it's worthless: after you've sent the data, your program loose all ability to deal with user interface. After you send the form to the user, you loose ALL habilities of python, php, mysql, etc... and are solely on the _javascript_ fields. And that _javascript_ will have only the provided data of that session to get things done, so you can't send all the DB to the client :) Nowadays that you can use and trust user requests, as widely advertised by google sugest, you can overcome one of the pitfalls of html: the responsiveness to user input. Now, the second one: responsiveness to server envents, still has to rely on non-standard xml streams or third party hacks using macromedia crap. take for example gMail. A program like that had at least 60% of it's development made on the _javascript_ side. And it still doens't solve the second issue. So, as i said in my 1st post in this thread: both have their problems, but it's all about what you need to get done. so, get used to both. If you can use one-shot pages, go for html, since all the toolkit is easily available in the browser, the network hassle is also done by the browser, the input history... also done by the browser! yada yada yada Now, if you need interactivity, say a game for example, then run away from html like hell. Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Skip Montanaro wrote: Mike ... or making them old-style classes, which is discouraged. Since when is use of old-style classes discouraged? Well, since new-style classes came along, surely? I should have thought the obvious way to move forward was to only use old-style classes when their incompatible-with-type-based-classes behavior is absolutely required. Though personally I should have said use of new-style classes is encouraged. I agree that there's no real need to change existing code just for the sake of it, but it would be interesting to see just how much existing code fails when preceded by the 1.5.2--to-2.4-compatible (?) __metaclass__ = type guessing-not-that-much-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Nick Coghlan [EMAIL PROTECTED] writes: Mike Meyer wrote: Yup. Thank you. This now reads: Regarding str() and repr() behaviour, repr() will be either ''rational(num)'' if the denominator is one, or ''rational(num, denom)'' if the denominator is not one. str() will be either ''num'' if the denominator is one, or ''(num / denom)'' if the denominator is not one. Is that acceptable? Sounds fine to me. On the str() front, I was wondering if Rational(x / y) should be an acceptable string input format. I don't think so, as I don't see it coming up often enough to warrant implementing. However, Rational(x / y) will be an acceptable string format as fallout from accepting floating point string representations. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Skip Montanaro [EMAIL PROTECTED] writes: Mike ... or making them old-style classes, which is discouraged. Since when is use of old-style classes discouraged? I was under the imperssion that old-style classes were going away, and hence discouraged for new library modules. However, a way to deal with this cleanly has been suggested by Steven Bethard, so the point is moot for this discussion. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode entries on sys.path
Martin v. Löwis [EMAIL PROTECTED] writes: Thomas Heller wrote: It seems that Python itself converts unicode entries in sys.path to normal strings using windows default conversion rules - is this a problem that I can fix by changing some regional setting on my machine? You can set the system code page on the third tab on the XP regional settings (character set for non-unicode applications). This, of course, assumes that there is a character set that supports all directories in sys.path. If you have Japanese characters on sys.path, you certainly need to set the system locale to Japanese (is that CP932?). Changing this setting requires a reboot. Hm, maybe more a windows question than a python question... The real question here is: why does Python not support arbitrary Unicode strings on sys.path? It could, in principle, atleast on Windows NT+ (and also on OSX). Patches are welcome. How should these patches be approached? On windows, it would probably be easiest to use the MS generic text routines: _tcslen instead of strlen, for example, and to rely on the _UNICODE preprocessor symbol to map this function to strlen or wcslen. Is there a similar thing in the non-windows world? Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: program in interactive mode
John Machin [EMAIL PROTECTED] writes: Mike Meyer wrote: I've discovered a truly elegant trick with python programs that interpret other data. Q0. Other than what? Other than Python code. You make them ignore lines that start with # at the beginning of the line, Q1. After the first user accidentally gets a # at the start of a real data line, a few hundred lines into their file, then what will you do? Fix your script to detect this error and re-issue your documentation, emphasising that this is not a general comment convention? Depends on how you implement it. Possibly issue an error message. Possibly treat this as data. Possibly treat this as a comment. Q2. Then when users 2+ steam up complaining that they have stacks of files containing lines like Next section is frappenwanger readings in picoHertz , and the script is printing out a whole lot of what they regard as gobbledegook followed by HashmarkAtStartOfOtherThanLineZeroError, and then stopping, what do you do? You don't implement the hashmark that way, of course. and accept the name of a file to be interpreted as a first argument. Your users can then put #!/usr/bin/env mycode.py Q3. Will that work on 'Doze? Probably not. I don't know if this is part of the Posix compatability level or not. Q4. Doesn't that tie their file to your script, or force other scripts to ignore the first line? This trick is really only applicable to data where you control the file format. As I mentioned, I use it to treat pickled program configuration files as executables. at the top of their files, and then treat their files as normal executables. mycode.py has to be on their path; if not, they need to plug in the full path to mycode.py. Q5. For comparison purposes, could you please post an example of what you regard as a filthy ugly trick? f = __import__(__name__) f.__dict__['name'] = value mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional Static Typing - Haskell?
Donn Cave [EMAIL PROTECTED] writes: Quoth Mike Meyer [EMAIL PROTECTED]: | [EMAIL PROTECTED] (Alex Martelli) writes: ... | But then, the above criticism applies: if interface and implementation | of a module are tightly coupled, you can't really do fully modular | programming AND static typing (forget type inferencing...). | | I beg to differ. Eiffel manages to do this quite well. Then again, | every Eiffel environment comes with tools to extract the interface | information from the code. With SmartEiffel, it's a command called | short. Doing short CLASSNAME is like doing pydoc modulename, | except that it pulls routine headers and DbC expression from the code, | and not just from comments. And you probably think Eiffel supports fully modular programming, as I thought Objective CAML did. But Alex seems not to agree. The way I understand it, his criteria go beyond language level semantics to implementation details, like whether a change to a module may require dependent modules to be recompiled when they don't need to be rewritten. I don't know whether it's a reasonable standard, but at any rate hopefully he will explain it better than I did and you can decide for oneself whether it's an important one. I read through his explanation. And the answer for Eiffel is, of course, it depends. There's an optimization that embeds a class data directly in the cilent class - the expanded keyword. If you have an expanded variable or type in your client class, then changing the implementation of the provider may require recompilation of the client. On the other hand, that's pretty much an optimization, and so you shouldn't run into it during development. SmartEiffel, on the other hand, always does full-source analysis. It drops class features that aren't used by any client, so changing the client can cause the provider to be recompiled. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
RE: A Revised Rational Proposal
Title: RE: A Revised Rational Proposal [Mike Meyer] #- I don't think so, as I don't see it coming up often enough to warrant #- implementing. However, Rational(x / y) will be an acceptable #- string format as fallout from accepting floating point string #- representations. Remember that repr() should comply with eval() to assure that x == eval(repr(x)). 'Rational(x / y)' won't comply it, as eval will raise TypeError: unsupported operand type(s) for /: 'str' and 'str'. . Facundo Bitácora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. -- http://mail.python.org/mailman/listinfo/python-list
python metrics program/script sample
Hi, I am looking for an eric3/linux compatible alternative to checking code metrics (ex: true lines of code count) Regards, Philippe -- http://mail.python.org/mailman/listinfo/python-list
RE: Tutorial problem
Title: RE: Tutorial problem [Rÿe9veillÿe9] #- The problem is that it doesnt print the #- #- [ choice = input ('Pick a number:') ] #- #- command. It just runs thru the whole thing without #- allowing the user a selection. Are you sure? It should raise a NameErrorin the while, because the name 'choice' is not defined before. . Facundo Bitácora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tutorial problem
On Mon, 27 Dec 2004 08:15:51 -0800, Rÿe9veillÿe9 wrote: The problem is that it doesnt print the [ choice = input ('Pick a number:') ] command. It just runs thru the whole thing without allowing the user a selection. Are you running it from the command line ? Some editors do not 'work' properly with command line input (redirection issues). -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode entries on sys.path
Thomas Heller wrote: How should these patches be approached? Please have a look as to how posixmodule.c and fileobject.c deal with this issue. On windows, it would probably be easiest to use the MS generic text routines: _tcslen instead of strlen, for example, and to rely on the _UNICODE preprocessor symbol to map this function to strlen or wcslen. No. This fails for two reasons: 1. We don't compile Python with _UNICODE, and never will do so. This macro is only a mechanism to simplify porting code from ANSI APIs to Unicode APIs, so you don't have to reformulate all the API calls. For new code, it is better to use the Unicode APIs directly if you plan to use them. 2. On Win9x, the Unicode APIs don't work (*). So you need to chose at run-time whether you want to use wide or narrow API. Unless a) we ship two binaries in the future, one for W9x, one for NT+ (I hope this won't happen), or b) we drop support for W9x. I'm in favour of doing so sooner or later, but perhaps not for Python 2.5. Regards, Martin (*) Can somebody please report whether the *W file APIs fail on W9x because the entry points are not there (so you can't even run the binary), or because they fail with an error when called? -- http://mail.python.org/mailman/listinfo/python-list
Re: More elegant way to cwd?
Kamilche wrote: Is there a more elegant way to change the working directory of Python That depends on how you define elegant, I guess. to the directory of the currently executing script, and add a folder called 'Shared' to the Python search path? This is what I have. It seems like it could be shorter, somehow. It could be shorter if you were willing to combine several function calls on the same line, but I get the impression you wouldn't consider that more elegant... # Switch Python to the current directory import os, sys pathname, scriptname = os.path.split(sys.argv[0]) pathname = os.path.abspath(pathname) os.chdir(pathname) s = os.path.realpath('..') s = os.path.join(s, 'Shared') sys.path.append(s) Thanks for any enhancements you can suggest! Other than using os.pardir instead of '..', and possibly adding an os.path.abspath() call to the last bit (or does realpath already do that? It's unclear from the docs), I can't see anything fundamental I'd do differently... except package these functions up as nice clean subroutines, possibly in a library package, that I could then use in code that would magically become elegant (IMHO) by avoiding the repetition of all that non-elegant stuff above... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: where is ctypes.py?
[EMAIL PROTECTED] wrote: I'm a complete newbie in learning python. I was testing some sample codes I found in this newsgroup and seems it could not locate the module ctypes.py. I installed python 2.4, wxPython and pywin32. Just could not find this file. I thought it should be in Lib/site-packages/ directory but it is not there. Where can I find this file? I see others have pointed you to the module, but nobody has yet told you how you could have found it yourself. ctypes and many other such modules are third-party packages which do not come with Python itself. In almost all cases, you should be able to use Google quite easily to find such a module by typing python ctypes (or substitute the appropriate name in place of ctypes) in a Google search. Quite often the home page of the package (where you'll find instructions on downloading) will be the first result Google provides. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: python metrics program/script sample
Philippe C. Martin wrote: I am looking for an eric3/linux compatible alternative to checking code metrics (ex: true lines of code count) I don't know what eric3/linux compatible might be, I'm not sure what this would be an alternative _to_, and I don't know what you mean by true lines of code count, but the only thing I've noticed lately that counts lines of Python code, and I'm fairly sure it would run fine on Linux, is pycount. Google for it... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional Static Typing - Haskell?
Neal D. Becker [EMAIL PROTECTED] wrote: I've just started learning about Haskell. I suggest looking at this for an example. A good intro: http://www.haskell.org/tutorial I've always found that with Haskell, if I can get my program to compile without error, it usually runs flawlessly. (Except for the occasional off-by-one error. :-) I don't know if that's due to the fact that Haskell enforces pure functional programming, or if it's due to Haskell's strict static typing, or the combination of the two. But if anyone ever demanded that I wrote code that absolutely positively has to work, no matter the cost, I would probably choose Haskell. Tying Haskell back to Python, if static type checking ever is grafted on to Python, I would propose that it uses type inference, a la Haskell or O'Caml, and raise an Error only when it detects a truly unmistakable type error. This may be easier said than done, however, given Python's dynamic nature. For example, a class's method may be re-bound to any other function at runtime, which would wreak havoc on any static type checker. - Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: SimpleHTTPServer, queries unhandled?
Try this in IDLE: import CGIHTTPServer CGIHTTPServer.test() This starts serving right away. You can also look at CGIHTTPServer.py in your Python/Lib to see how test() has been implemented. test() starts serving from the current directory (of running python). If you create a folder called cgi-bin and put a testcgi.py, this module executes the .py file and displays the contents in the browser :-) Thanks, --Kartic PS: You can handle query strings accordingly now. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tutorial problem
Rÿe9veillÿe9 wrote: Hello, I have just started doing the python tutorials and i tried to modify one of the exercises, it has to to with defining functions. I wanted the user to be able to enter an option and then get a print of the selected option. I also wanted to have an exit for the user. This is the code def PU(): print 'To have a ...' def Python(): print 'To create a programme ...' def overall(): print 'To make .' def motv(): print 'I know you can do it!' def menu(): print ' GOALS IN... ' print '' print '1.Pick up' print '2.Python Programming' print '3.Overall' print '4.Motivation' print '5.Exit' print '' menu() while choice != 5: choice = input ('Pick a number:') if choice == 1: PU() elif choice == 2: Python() elif choice == 3: overall() elif choice == 4: motv() else: print 'Bye' The problem is that it doesnt print the [ choice = input ('Pick a number:') ] command. It just runs thru the whole thing without allowing the user a selection. No, it doesn't. It prints: Traceback (most recent call last): File test97.py, line 24, in ? menu() NameError: name 'menu' is not defined There's a good reason for this, too: you define motv(), and inside that function you define the menu() function. Since the menu() function is defined inside the body of motv(), its definition is only created when motv() is callinside the *local* namespace of the invocation of motv(). ed. The call to motv() returns, and everything the function knew is forgotten. I suggest you change the indentation of the menu() definition so it's at the same level as your other functions. That was a lucky problem, however, because it stopped a later error from occurring. That while choice != 5 will fail the first time it is executed, since you haven't actually set the value of choice to be anything. Now, quite why you chose to misinform us as to the behavior of your program I can't really divine. I'll be charitable, and assume that you are actually referring to some earlier version. But a sound rule for getting help is always post the code AND the error traceback. Also, note that when you type in the digit 1 in response to your program's prompt (when you eventually see it), that will become the string value 1 in the choice variable. Since 1 is not equal to 1 you will always fall off the end and print Bye. Perhaps you'd like to try again after you've attempted to remedy some of the deficiencies I have pointed out? There's plenty of help available here, and you aren't far from a working program. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional Static Typing
In article [EMAIL PROTECTED], [EMAIL PROTECTED] (Alex Martelli) wrote: John Roth [EMAIL PROTECTED] wrote: ... question: static typing is an answer. What's the question? (That's a paraphrase.) The answer that everyone seems to give is that it prevents errors and clarifies the program. ... Most of the kinds of error that static typing is supposed to catch simply don't persist for more than a minute when you do test driven development. ...which is exactly the point of the famous post by Robert (Uncle Bob) Martin on another artima blog, http://www.artima.com/weblogs/viewpost.jsp?thread=4639 . Wait a minute, isn't he same fellow whose precious dependency inversion principle shows us the way to support fully modular programming? What would he say about unit testing to catch up with changes in dependent modules, do you think? Do we have a combinatorial explosion potential here? Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: where is ctypes.py?
Peter, Thank you very much. I'll keep that in mind. - wcc -- http://mail.python.org/mailman/listinfo/python-list
Re: list addition methods compared.
Le 27/12/04 1:03, « Ishwor » [EMAIL PROTECTED] a écrit : so indeed method 2 (l2.extend() ) is the fastest ?? In 2/3 times, method 3 (l3 += [x] seems faster than method 1/2 in my P2.4GHZ machine with 512mb??? :-( Could u run the code in your machine and perhaps and let me know what the average speed is?? On a iBook G4 à 1.2 Ghz loaded with tons of other softwares running. fgranger:/develop/python scripts fgranger$ python listspeed.py @@@ Method 1 done in (average finish time(out of 3)) - 5.6365475655 Method 2 done in (average finish time(out of 3)) - 0.0562076569 Method 3 done in (average finish time(out of 3)) - 0.0455052853 @@@ fgranger:/develop/python scripts fgranger$ python listspeed.py @@@ Method 1 done in (average finish time(out of 3)) - 6.1534483433 Method 2 done in (average finish time(out of 3)) - 0.0637686253 Method 3 done in (average finish time(out of 3)) - 0.0500767231 @@@ fgranger:/develop/python scripts fgranger$ python listspeed.py @@@ Method 1 done in (average finish time(out of 3)) - 5.5850391388 Method 2 done in (average finish time(out of 3)) - 0.0594174862 Method 3 done in (average finish time(out of 3)) - 0.0549054146 @@@ -- François Granger [EMAIL PROTECTED] + 33 6 61 36 96 17 (mobile) + 33 1 47 35 00 16 (home) -- http://mail.python.org/mailman/listinfo/python-list
help - problem installing pywin32
Hello, I was trying to install pywin32 on one computer which has Python 2.4 installed and it failed. The error message I got was Can't load Python for pre-install script. I tried unintalling reinstalling python and that didn't fix the problem. What might be the problem? Thank you very much. - wcc -- http://mail.python.org/mailman/listinfo/python-list
Re: python metrics program/script sample
pylint looks good! thanks Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: test
Tim Peters wrote: try: sdfdsafasd except NameError: pass else: True = None is None and 1 != 2 False = None is not None or 1 == 2 A simple Google search reveals that sdfdsafasd is misspelled, and helpfully gives the correct spelling: Did you mean: sdfasdfasd http://www.google.com/search?complete=1hl=enq=sdfdsafasdbtnG=Google+Search Should you wish to view the man pages on line, man sdfasdfasd turns up plenty of hits: http://www.google.com/search?complete=1hl=enlr=safe=activec2coff=1q=man+sdfasdfasdbtnG=Search -- http://mail.python.org/mailman/listinfo/python-list
Re: Complementary language?
In article [EMAIL PROTECTED], [EMAIL PROTECTED] (Alex Martelli) wrote: Robin Becker [EMAIL PROTECTED] wrote: Alex Martelli wrote: . If you're looking for SERIOUS multiparadigmaticity, I think Oz may be best -- http://www.info.ucl.ac.be/people/PVR/book.html (the book's authors critique the vagueness of the paradigm concept, and prefer model, but that's much the same thing). according to the language shootout at http://shootout.alioth.debian.org/benchmark.php?test=alllang=allsort=cpu Mozart/Oz comes last in cpu score. I suspect that may be due to unfamilarity or poor implementation of the test codes. Everybody 'knows' that benchamrks are always wrong, but which score moves this language to the top in your opinion? Hmmm, I'm not sure how to parse this question. Robert Kern claimed: You could very easily learn more approaches to programming through Common Lisp than three other languages, and I'm pointing out that, if what you're after is to learn more approaches to programming via the built-in features of a single language, Oz (with the CTMCP book) may well be numero uno. Judging from the blurb on the book's back, as I also mentioned, Norvig, hardly a slouch when it comes to Lisp, appears to share this assessment. What the language shootout can possibly have to do with this issue entirely escapes me. Quite apart from benchmarks are always wrong, I don't think they're even _remotely_ trying to benchmark how much does learning this language teach you about different approaches to programming -- it would seem to be a mighty tall order to even set up a controlled experiment to measure _that_ quantitatively! I can't disagree very much with that, but in the vein of answering the original question I think it's fair to assign some weight to a language's practical utility. For me, anyway, a language will be more instructive if it really is a practical alternative, because then I will obviously be much more motivated to use it. Accordingly I should put in a vote here for Objective CAML. Cf. http://caml.inria.fr/ . (Note the separate documentation for Camlp4, specifically the revised syntax. Objective CAML's original syntax has some bad warts, but it's optional.) It's a modern functional programming language, so it's good for knowing what you're missing when people talk about using Python for FP. There's also a rigorously typed OOP layer, which introduces a few issue that Python sort of ducks. (I haven't spent a lot of time in the OOP layer, but I believe in a way it formalizes duck typing, rather than the inheritance based type system that some languages are saddled with.) So for a Python programmer it's all about learning different approaches to programming, but this one is also a really competitive language for software development. Not a gem, but not a toy. Someone who already has Objective CAML and Python on hand might be interested in Felix, http://felix.sourceforge.net. I haven't actually used it, and for all I know it fails my utility test since it is not a very mature language, but I mention in in case anyone is interested in what the author of the vyper Python implementation is up to these days. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: python metrics program/script sample
Philippe C. Martin wrote: true lines of code meant no blanks or comment - pycount calls those normal source code: Pycount does not treat a blank line as normal source code, at least in the version I'm using. It quite clearly differentiates between various types of lines, including a header in the output which reads as follows: linescode doc comment blank file (doc and comment are two separate columns, as it distinguishes between doc-comments, which are comments only by convention, and real comments). There are a couple of minor known bugs with pycount like: Doc strings must be tripple-quoted ones otherwise they are classified as normal source code. Interesting, but I believe it's a nearly universal convention to use triple-quoted strings for doc-comments. I guess if you don't do that, however, pycount might not be for you. Continuation lines ending with a backslash are not treated at all. Complex regular expressions (as in pycount itself) can knock the parser down, quickly. There is a built-in quick-and-dirty solution to this which might work whenever the problem is on one line only. But in most cases it works... In areas like this, I consider most attempts to make a line counter more sophisticated are, while well-meaning, often a waste of time. For example, if I have a line that is long enough (read complex enough) to warrant a line-continuation, I'm quite happy if a simple line counter decides to call it two lines (or three, or whatever). Or one. It shouldn't be that big a deal. Source lines of code has at best a tenuous connection to complexity or other abstract characteristics of code, so I don't see any reason to spend time on making a line counter perfect. It should probably be used only for comparative analysis anyway, so as long as it does the same thing on your entire code base, it ought to be good enough, IMHO. I'll try pycount but the above bugs might mean a lot of rewriting. I've been using it for quite some time, successfully, without even being aware there were problems with certain types of source. Maybe my code is just relatively standard-looking, so pycount doesn't have trouble with it... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional Static Typing
Michael Hobbs [EMAIL PROTECTED] wrote: Your proposition reminds me very much of Design by Contract, which is a prominent feature of the Eiffel programming language. Considering that Python is an interpreted language where type checking would naturally occur at runtime, I think Design by Contract would be more appropriate than static typing. I entirely agree with this opinion. In a function's contract, not only could it state that its parameter must be an integer, I'd like to be able to state something about the *INTERFACE* of the parameter, to the rigorous exclusion of its *TYPE* (which is an implementation detail). I doubt it's really feasible, but, in Haskell terms, I'd love for such assertions to be always and necessarily about _typeclasses_ rather than _types_... but also that it must be 50 and be divisible by 7. If a value is passed to the function that violates the contract, it raises an exception. In Eiffel, contract checking can be turned on or off based on a compiler flag or a runtime switch. I've always liked the (theoretical) idea that assertions (including of course contracts) could be used as axioms used to optimize generated code, rather than (necessarily) as a runtime burden. E.g. (and I don't know of any implementation of this concept, mind you), inferring (e.g. from such assertions) that x=0, and that y0, the compiler could simply cut away a branch of dead code guarded by if xy: (maybe with a warning, in this case;-)... Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: PHP vs. Python (speed-wise comparison)
[EMAIL PROTECTED] wrote: Anyone know which is faster? I'm a PHP programmer but considering getting into Python ... did searches on Google but didn't turn much up on this. Thanks! Stephen If you're talking about usage as a server side scripting language, then PHP will likely give better page serving throughput for the same hardware configuration versus even something that is mod_python based (but I believe the speed diff would be well under 100%). However, Python is just so much superior as a language (I was deep into PHP before I tried out Python and I always hate having to go back to PHP nowadays in the cases where it is unavoidable) that you will still want to use Python even if PHP requires lower server specs to handle the same throughput. Also, if you have a more complex application for which pooled variable reuse is an important performance-determining factor, Python-based server-side scripting solutions might offer better control of this aspect and may thus yield superior performance to a PHP-based one. The real problem with Python is not speed but _availability_. The number of hosting services out there supporting mod_php completely outstrips those supporting mod_python. Moreover, they are significantly cheaper, and offer a lot more features (Fantastico, etc...). The python-based hosting solutions out there tend to be dedicated to Python and thus do not offer these solutions. If this is not an issue (i.e. you will be running your own server), then I highly recommend going the Python route using something like Spyce (which is the closest thing to PHP in the Python world). -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3000, zip, *args and iterators
Raymond Hettinger wrote: [...] Not everything that can be done, should be done. ... and not everything that should be done, can be done. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: Are tuple really immutable?
Chris [EMAIL PROTECTED] wrote: ... 3) In this example, is t considered mutable or not? Tuple are immutable says the doc, but: t[0].append(0) t ([1, 0], [2]) The tuple is immutable but its elements can be mutable: I tend to think that it means that the tuple is mutable. Indeed, it changed! No, not in the way intended by the word 'mutable'. A tuple is like an ordered club roster written in indelible ink before the time of whiteout. The members of the club may change (change jobs, residence, relationships, etc) but the roster remains the same: same members, same ranking. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
PyHeartBeat Client in PERL?
Hello Everyone. Whil e reading the Python Cookbook as a means of learning Python, I came across the script by Nicola Larosa. Not knowing anything about PERL, I was wondering if there were a translation in PERL so I could have my Netware servers send heartbeats to the heartbeat server? Thanks! Dave Title: PyHeartbeat - detecting inactive computers Submitter: Nicola Larosa # Filename: HeartbeatClient.py Heartbeat client, sends out an UDP packet periodically import socket, time SERVER_IP = '127.0.0.1'; SERVER_PORT = 43278; BEAT_PERIOD = 5 print ('Sending heartbeat to IP %s , port %d\n' 'press Ctrl-C to stop\n') % (SERVER_IP, SERVER_PORT) while True: hbSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) hbSocket.sendto('PyHB', (SERVER_IP, SERVER_PORT)) if __debug__: print 'Time: %s' % time.ctime() time.sleep(BEAT_PERIOD) -- http://mail.python.org/mailman/listinfo/python-list
Re: where is ctypes.py?
Peter Hansen I see others have pointed you to the module, but nobody has yet told you how you could have found it yourself. ctypes and many other such modules are third-party packages which do not come with Python itself. In almost all cases, you should be able to use Google quite easily to find such a module by typing python ctypes (or substitute the appropriate name in place of ctypes) in a Google search. Quite often the home page of the package (where you'll find instructions on downloading) will be the first result Google provides. If one does not already know the name of what one is searching for, there is also the PythonPackageIndex PyPI at python.org. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: PyHeartBeat Client in PERL?
Dave While reading the Python Cookbook as a means of learning Python, I Dave came across the script by Dave Larosa. Not knowing anything about Dave PERL, I was wondering if there were a translation in PERL so I Dave could have my Netware servers send heartbeats to the heartbeat Dave server? There is no doubt a way to do it (you're just sending out udp packets to a remote server, after all). Wouldn't it be better to ask Perl people how to write Perl though? Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional Static Typing - Haskell?
Michael Hobbs wrote: I've always found that with Haskell, if I can get my program to compile without error, it usually runs flawlessly. (Except for the occasional off-by-one error. :-) Then you need Scott and Dave's Programming Language -- SAD/PL. By providing separate data types for even and odd numbers, you can avoid off-by-one errors ;-) --Tongue-in-cheek-ily-yours, Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional Static Typing
Luis M. Gonzalez wrote: Robert Kern wrote: Starkiller, at least, can deal with cases where a variable might be one of a set of types and generates code for each of this set. Explicit type declarations can help keep these sets small and reduces the number of times that Starkiller needs to fall back to PyObject_* calls. Will we be able to see it anytime soon? I'm eagerly waiting for its release. It's been about a month away for at least 4 months now. I don't know what the holdup has been. I know that Michael has graduated and so he's probably been busy with a new job. -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Reading a HP Printer Web Interface
Hello there, Depending on the firmware version of the HP printer and the model type, one will encounter a myriad of combinations of the following strings while reading the index page: hp HP color Color Printer Printer Status Status: Device: Device Status laserjet LaserJet How can I go about determining if a site is indeed the Web interface to a HP printer? The goal is to remove all HP printers from a list of publicly available Web sites... I've tried this approach, but it gets messy quickly when I attempt to account for all possible combinations that HP uses: f = urllib2.urlopen(http://%s; %host) data = f.read() f.close() if 'hp' or 'HP' and 'color' or 'Color' and 'Printer' or 'Printer Status' in data: DISREGARD THE IP I'm sure there's a more graceful way to go about this while maintaining a high degree of accuracy and as few false positives as possible. Any tips or pointers? Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list
Re: need some help with threading module...
chahnaz.ourzikene wrote: M.E.Farmer [EMAIL PROTECTED] a écrit dans le message de news: [EMAIL PROTECTED] Just a warning! Threads and newbies don't mix well, many pitfalls and hard to find bugs await you. I would avoid using threads if at all possible. Indeed :). But how will i learn using threads if i avoid using them :) ?? That was the point , you probably don't need them, and if so avoid them. If you want to learn how to use them , go for it! That is an excellent reason to mess with them, it was just a warning because you WILL be bitten by them, just a matter of time ;) Now we have all that over lets see some code. py import threading py class Test(threading.Thread): ...def run(self): ... x = 0 ... while x 10: ... print x ... x += 1 ... print Ending Use it like this: py Test().start() Your example is interristing...somehow this is not exactly what i want to realise. I have exposed the problem in an earlier reply... Yacine Chaouche -- France. I should have mentioned this was an attempt to show you how to make a thread 'exit' after it reached 10. You are having problems with the controller class, please look again at what I gave you this as an example. Did you run it? It was specific to your question. You were having problems making the controller exit. It should explain where you are lost, notice I inherit from Thread and not object, notice a much simpler way to write the thread You also mention the MVC pattern. If you are trying to implement MVC with threads you are going about it the wrong way ;) Hth, M.E.Farmer -- http://mail.python.org/mailman/listinfo/python-list
RFC 2965 cookies, cookielib, and mailman.
Hi all, just spent some time playing with cookielib in Python 2.4, trying to get the cookielib example [0] to work with my mailman admindb page. The problem was that cookies weren't getting saved. The issue turned out to be that mailman sends out RFC 2965 [1] cookies, which are by default rejected by cookielib. I don't remotely pretend to understand the issues involved; hence my post ;). A few questions for those more clued in than me: * what is the difference between RFC 2965 cookies and others? * why would mailman implement RFC 2965 cookies over the old format? (I'm guessing simply because it's the latest/best/format?) * why would cookielib NOT accept RFC 2965 cookies by default? * my reference good implementation that worked with the urllib2/cookielib is Quixote, which seems to send out cookies in the older (Netscape?) style. Should this be changed or updated in Quixote? The obvious google searches found an awful lot of information but nothing obviously pertinent. In any case, the way to make the cookielib example work for mailman is like so: policy = cookielib.DefaultCookiePolicy(rfc2965=True) cj = cookielib.LWPCookieJar('cookies.lwp', policy=policy) thanks, --titus [0] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302930 [1] http://www.faqs.org/rfcs/rfc2965.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional Static Typing
Alex == Alex Martelli [EMAIL PROTECTED] writes: Alex I've always liked the (theoretical) idea that assertions Alex (including of course contracts) could be used as axioms used Alex to optimize generated code, rather than (necessarily) as a Alex runtime burden. E.g. (and I don't know of any Alex implementation of this concept, mind you), inferring (e.g. Alex from such assertions) that x=0, and that y0, the compiler Alex could simply cut away a branch of dead code guarded by if Alex xy: (maybe with a warning, in this case;-)... I realize that your example is theoretical, but efficiency impact of such optimizations would be dwarfed (speedwise) by optimization on type, so that if x y yields native object code for integer comparison. Also, to get real benefits the functions called would need to be inline-expanded so that the implications of x y are taken in account deeper in the call chain; a programmer that does def f(x,y): assert x y if x y: blah(y,x) needs a slap on the wrists anyway. Doing if x y in blah() would make sense, but then there would need to be a special version of blah()... I could think of one worthwhile example as well: def foo(l): assert issorted(l) if hi in l: # in does a bsearch because the list is sorted blah() but things like this probably belong to languages like Lisp where the user gets to expand and mess with the compiler. -- Ville Vainio http://tinyurl.com/2prnb -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional Static Typing - Haskell?
Scott David Daniels wrote: Then you need Scott and Dave's Programming Language -- SAD/PL. By providing separate data types for even and odd numbers, you can avoid off-by-one errors ;-) mmmhhh off by two-licious -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Mike Meyer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Nick Coghlan [EMAIL PROTECTED] writes: Mike Meyer wrote: Yup. Thank you. This now reads: Regarding str() and repr() behaviour, repr() will be either ''rational(num)'' if the denominator is one, or ''rational(num, denom)'' if the denominator is not one. str() will be either ''num'' if the denominator is one, or ''(num / denom)'' if the denominator is not one. Is that acceptable? Sounds fine to me. On the str() front, I was wondering if Rational(x / y) should be an acceptable string input format. I don't think so, as I don't see it coming up often enough to warrant implementing. However, Rational(x / y) will be an acceptable string format as fallout from accepting floating point string representations. How would that work? I though the divide would be evaluated before the function call, resulting in an exception (strings don't implement the / operator). John Roth mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
objects as mutable dictionary keys
There was a huge and sometimes heated debate about tuples, lists and dictionaries recently, and the mainstream opinion was that dictionary keys must not be mutable, so lists are not allowed as dictionary keys. BUT: objects are allowed as dictionary keys, aren't they? See the interpreter session below: class x(object): ... pass ... x1 = x() x1.prop = 'a' d = {} d[x1] = 'x1' for i in d.iteritems(): ... if i[0].prop == 'a': ... print i ... (__main__.x object at 0x011AC330, 'x1') x1.prop = 'b' for i in d.iteritems(): ... if i[0].prop == 'b': ... print i ... (__main__.x object at 0x011AC330, 'x1') This strikes me because if one can do this with instances of user defined classes why not with lists? Trying to use lists as dict keys yields TypeError: list objects are unhashable. So why are list objects unhashable and user defined objects hashable? For user defined objects hash(x1) = id(x1), why not do the same with lists? I think it's because of the existence of list literals. If you would use id() as a hash function for lists how should d[[1,2,3]] be stored? For instances of user defined classes there is no literal and accordingly no problem to use id() as a hash function and instances as dictionary keys. Is that correct? -- --- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') --- -- http://mail.python.org/mailman/listinfo/python-list
Re: Best GUI for small-scale accounting app?
McBooCzech schreef: IMHO this is the worst think for the Python community: you can find one Python only with an excellent support. Great But on the other hand it is possible to find plenty of GUI tools and for the beginner (and may be not just for the beginner) it is so hard to choose the proper one! The field of GUI tools is so fragmented I think the field of GUI frameworks / tools for Python is fragmented because it's fragmented outside of Python too... -- JanC Be strict when sending and tolerant when receiving. RFC 1958 - Architectural Principles of the Internet - section 3.9 -- http://mail.python.org/mailman/listinfo/python-list
Re: objects as mutable dictionary keys
Peter Maas wrote: This strikes me because if one can do this with instances of user defined classes why not with lists? Trying to use lists as dict keys yields TypeError: list objects are unhashable. So why are list objects unhashable and user defined objects hashable? For user defined objects hash(x1) = id(x1), why not do the same with lists? I think it's because of the existence of list literals. If you would use id() as a hash function for lists how should d[[1,2,3]] be stored? For instances of user defined classes there is no literal and accordingly no problem to use id() as a hash function and instances as dictionary keys. Is that correct? Well, there's no problem getting an id of a list without a name if that's what you mean: py lst = [[1,2,3]] py id(lst[0]) 12456424 If lists were hashable, new programmers to Python would almost certainly make mistakes like: py d = {[1, 2, 3]: 'abc'} The coder here almost certainly *doesn't* want that list to be compared by id. The only way to get a binding for that list would be using the dict's keys or __iter__ methods. The coder here almost certainly wants to compare by value so that the following code works: py d[[1, 2, 3]] Of course, this is what tuples are for -- Python even supports special syntax for using them this way: py d[1, 2, 3] So my suspicion is that lists are not hashable because it prevents what would be a very easy mistake to make. Yes, it means you can't use your lists as keys to a dict, but how often do you want to do that anyway? I don't think I've ever wanted to do that. If I ever do, I'll probably just do something like: py lst1, lst2 = [1, 2, 3], 'a b c'.split() py d = {id(lst1):100, id(lst2):200} py d[id(lst1)] 100 py d[id(lst2)] 200 Certainly I don't mind having to be explicit for an unusual case if it saves me a little trouble for the more common cases. Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: PHP vs. Python (speed-wise comparison)
Dnia Tue, 28 Dec 2004 02:54:13 +0800, Jon Perez napisa(a): If you're talking about usage as a server side scripting language, then PHP will likely give better page serving throughput for the same hardware configuration versus even something that is mod_python based (but I believe the speed diff would be well under 100%). I have different experience. When I moved from PHP to Webware and I compared its performance with (similar scale) php appplications, my webware was almost 6 times faster! Application servers are always faster because they use compiled scripts stored in memory. They do not need to load files from filesystem nor parse them. PHP is faster only for trivial, useless benchmarks like Hello world. For bigger code Python is faster than PHP. The real problem with Python is not speed but _availability_. You have rigth here. -- JZ -- http://mail.python.org/mailman/listinfo/python-list
Re: objects as mutable dictionary keys
Andrew Koenig schrieb: This strikes me because if one can do this with instances of user defined classes why not with lists? Trying to use lists as dict keys yields TypeError: list objects are unhashable. So why are list objects unhashable and user defined objects hashable? For user defined objects hash(x1) = id(x1), why not do the same with lists? If d is a dict and t1 and t2 are tuples, and t1 == t2, then d[t1] and d[t2] are the same element. If lists used the id as the hash, this property would not hold for lists. This leads to the question: Why does (t1 == t2 = d[t1] identical to d[t2]) hold for user defined objects and not for lists? My answer: because the cmp function looks at id() for user defined objects and at list content for lists. Why does the cmp function _have_ to look at lists contents? My answer: because of the existence of list literals. Can you give me an example of a program for which you consider such behavior to be useful? I'm not interested in using lists as dict keys. I was just searching for an explanation why user defined objects can be used as dict keys contrary to lists. -- --- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') --- -- http://mail.python.org/mailman/listinfo/python-list
Re: objects as mutable dictionary keys
Andrew Koenig: If d is a dict and t1 and t2 are tuples, and t1 == t2, then d[t1] and d[t2] are the same element. So long as the elements of t1 and t2 are well-behaved. class Spam: ... def __hash__(self): ... return id(self) ... def __eq__(self, other): ... return True ... t1 = (Spam(),) t2 = (Spam(),) t1 == t2 True hash(t1) == hash(t2) False d = {t1: T1, t2: T2} d[t1] 'T1' d[t2] 'T2' d[t1] == d[t2] False d[t1] is d[t2] False Dictionaries have the extra requirement that if k1 == k2 then hash(k1) == hash(k2). Andrew [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional Static Typing
On Thu, 23 Dec 2004 01:49:35 -0800, bearophileHUGS wrote: Adding Optional Static Typing to Python looks like a quite complex thing, but useful too: http://www.artima.com/weblogs/viewpost.jsp?thread=85551 I wrote a blog post this morning in which I briefly argue using DbC and predicate based argument constraints instead of static typing. Take a look if you are interested. It also contains a link to a wiki page where I have been producing a more refined specification complete with good examples: http://www.cixar.com/segphault/pytype.html I would appreciate some feedback, I want to know what other python programmers think about DbC and arg constraints. -- SegPhault -- http://mail.python.org/mailman/listinfo/python-list
Re: objects as mutable dictionary keys
Steven Bethard schrieb: If lists were hashable, new programmers to Python would almost certainly make mistakes like: py d = {[1, 2, 3]: 'abc'} The coder here almost certainly *doesn't* want that list to be compared by id. The only way to get a binding for that list would be using the dict's keys or __iter__ methods. That's what I meant when I said that for lists id() doesn't make sense as hash because of the list literals. For user defined objects id() can be used as hash because there are no literals for user defined objects. -- --- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') --- -- http://mail.python.org/mailman/listinfo/python-list
Re: objects as mutable dictionary keys
Peter Maas [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] There was a huge and sometimes heated debate about tuples, lists and dictionaries recently, and the mainstream opinion was that dictionary keys must not be mutable, so lists are not allowed as dictionary keys. BUT: objects are allowed as dictionary keys, aren't they? See the interpreter session below: ... This strikes me because if one can do this with instances of user defined classes why not with lists? Trying to use lists as dict keys yields TypeError: list objects are unhashable. So why are list objects unhashable and user defined objects hashable? For user defined objects hash(x1) = id(x1), why not do the same with lists? I think it's because of the existence of list literals. If you would use id() as a hash function for lists how should d[[1,2,3]] be stored? For instances of user defined classes there is no literal and accordingly no problem to use id() as a hash function and instances as dictionary keys. Is that correct? No. The basic answer is that it's up to the object whether it will allow itself to be used as a dictionary key. In other words, if the designer of an object thinks it makes sense for instances to be dictionary keys, then he can supply a __hash__() method. If he doesn't, then he doesn't supply such a method, and it won't work. Each class gets to make its own decision. If a class has a __hash__() method defined, then it can be used as a dictionary key. If it doesn't, then it can't. There are no other constraints on the class designer; in particular, global logical considerations simply don't apply. It's the designer's whim, and nothing more. The designers of the list object decided not to allow it to be used as a dictionary key. That was their choice, and I pretty much agree with it. John Roth -- --- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') --- -- http://mail.python.org/mailman/listinfo/python-list
Re: objects as mutable dictionary keys
Peter Maas [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] This leads to the question: Why does (t1 == t2 = d[t1] identical to d[t2]) hold for user defined objects and not for lists? My answer: because the cmp function looks at id() for user defined objects and at list content for lists. Yes. Why does the cmp function _have_ to look at lists contents? My answer: because of the existence of list literals. No. The reason is that lists are containers, and it it is reasonable to define container equality recursively as element equality. There are no set literals, but that doesn't mean that set equality should be identity. -- http://mail.python.org/mailman/listinfo/python-list
Re: Complementary language?
HackingYodel [EMAIL PROTECTED] writes: Does any single language do a better job in Python's weaker areas? Would anyone care to suggest one to supplement Python. My first real OO language was Smalltalk. But the existing Smalltalk implementations all have some severe shortcomings. Either they are incomplete (Squeak), have no active community (Smalltalk/X) or they are real expensive and bulky (VisualWorks, VisualAge). But conceptually all these Smalltalk systems give me the feeling thats what OO should be like. Python OTOH was the best compromise I could find, beeing reasonably OO, fairly complete and free - and I am very happy with it. I am one order of magnitude more productive in Python than in Java but a little less productive than in Smalltalk. To wet your appetite let me telly you, that in Python you have much shorter turnaround times than in Java, because you don't have to compile your code after you fixed a bug. In Smalltalk you don't even have to restart your application, i.e. developping and running an application melts together. It's like doing brain surgery to yourself as someone said. So if you are interested to look at something even more radically OO than Python you might want to give Squeak (http://www.squeak.org) a try. Alan Kay, the guy wo coined the term Object oriented is one if its fathers. -- http://mail.python.org/mailman/listinfo/python-list
wxTreeCtrl checking for valid IDs
I have run across a weired problem: I am using a wxTreeCtrl with a model for each tree node. The tree expands lazily and each time a node is expanded, its children (Views) are completely rebuilt, creating new IDs. The children register their respecive models using two self written classes Model and View. I should note, that when collapsing, I delete children in a brute-force way, using CollapseAndReset(). Each time a node is collapsed and expanded old nodes are deleted and new nodes (Views) are created, but the old ones are still registered as views for their models. When such a model issues a self.changed() all their views try to update themselves. But some of them are already gone and no longer tree nodes of my tree. Trying to update their labels gives me a SIGSEGV. I had similar problem with other widgets, but there I get a wx._core.PyDeadObjectError which I could handle easily. But the tree just gives me a SIGSEGV. So I have two options: either delete tree nodes more gently doing all the cleanup work, or figure out if a tree item is still part of the tree before the SIGSEGV gets me. The first will definitely require some sort of tree traversal, the second maybe not. But I haven't found a way to do this. If I am totally off the paved road, please tell me so. -- http://mail.python.org/mailman/listinfo/python-list
Re: Are tuple really immutable?
Terry Reedy wrote: No, not in the way intended by the word 'mutable'. A tuple is like an ordered club roster written in indelible ink before the time of whiteout. The members of the club may change (change jobs, residence, relationships, etc) but the roster remains the same: same members, same ranking. Good analogy. -- Brian Beck Adventurer of the First Order -- http://mail.python.org/mailman/listinfo/python-list
Re: objects as mutable dictionary keys
Peter Maas wrote: Steven Bethard schrieb: If lists were hashable, new programmers to Python would almost certainly make mistakes like: py d = {[1, 2, 3]: 'abc'} The coder here almost certainly *doesn't* want that list to be compared by id. The only way to get a binding for that list would be using the dict's keys or __iter__ methods. That's what I meant when I said that for lists id() doesn't make sense as hash because of the list literals. As Andrew Koenig said, this has less to do with the fact that lists can be written with list literals, and more to do with the fact that lists are mutable containers. Because they're containers, it makes sense to compare them by comparing their contents. But because they're mutable, a hash value based on their contents cannot be guaranteed to be stable. Hashing them by their id would force the user to mentally switch between thinking of lists as containers and thinking of lists as non-container objects. Note that there is no such thing as a 'set literal', yet sets exhibit the same behavior: py d = {set([1, 2]):100, set('a b'.split()):200} Traceback (most recent call last): File interactive input, line 1, in ? TypeError: set objects are unhashable Sets are containers, and thus should be comparable by their contents. But sets are mutable, so they cannot be hashed by their contents. Rather than force the user to do the mental mind-switch between container and non-container, Python opts to make sets unhashable. Note that, much as tuples are to lists, frozensets are to sets: py d = {frozenset([1, 2]):100, frozenset('a b'.split()):200} py d[frozenset([2, 1])] 100 py d[frozenset(['b', 'a'])] 200 Because frozensets are immutable, they can not only be compared by their contents, but they can be hashed by these contents as well. Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: More elegant way to cwd?
Peter Hansen wrote: [snip] Other than using os.pardir instead of '..', and possibly adding an os.path.abspath() call to the last bit (or does realpath already do that? It's unclear from the docs) [snip] I believe os.path.abspath and os.path.realpath are the same. realpath is just an alias for abspath. Using pydoc on os gives this: pyrealpath = abspath(path) pyReturn the absolute version of a path M.E.Farmer -- http://mail.python.org/mailman/listinfo/python-list
Re: WxListBox
I think he is using an GUI editor wxGlade or BOA. He has two problems he is trying to figure out wxPython and he is trying to figure out his drag and drop editor. On top of that he seems to be having a design problem. I am gonna let him stew in it, it will be good for him ;) He will get more out of it. hint: SEARCH GOOGLE / READ DOCS / WRITE CODE Ahh the joy of learning frameworks.(and GUI editors) M.E.Farmer -- http://mail.python.org/mailman/listinfo/python-list
Confusion About Classes
Hi, I've been playing like mad with all sorts of python modules..but I still can't seem to get my head around the proper use of a class and self. The question stems from this code I made(snippet): -- import httplib, ftplib, urllib2, exPyCrypto, score_configurations #custom class create_server: def __init__(self, domain, servername, master_ftpUSER, master_ftpPASS, score_ftpUSER, score_ftpPASS, httpport=None, ftpport=None): self.domain = domain if httpport is None: self.__httpport = '80' else: self.__httpport = httpport if ftpport is None: self.__ftpport = '21' else: self.__ftpport = ftpport if servername is None: self.__servername = 'SCORE-SERVER' else: self.__servername = servername self.master_ftpUSER = master_ftpUSER self.master_ftpPASS = master_ftpPASS self.score_ftpUSER = score_ftpUSER self.score_ftpPASS = score_ftpPASS self.parser = ConfigParser.ConfigParser() def createUniversalConfig(self, score_domain, score_servername, score_port): '' self.parser.add_section('score') self.parser.set('score', 'domain', self.score_domain) self.parser.set('score', 'server', self.score_servername) self.parser.set('score', 'server', self.score_port) - The goal is to create a create_server object with the given parameters, and then call the method createUniversalConfig() without passing and parameters to it. So here are my questions: 1) in the function parameter heading def createUniversalConfig(self, score_domain, score_servername, score_port): do I need to include those parameters as written, like this-- def createUniversalConfig(self, self.score_domain, self.score_servername, self.score_port): or not pass any parameters at all? 2) Do I reference the body of the function like I originally wrote it: self.parser.add_section('score') self.parser.set('score', 'domain', self.score_domain) self.parser.set('score', 'server', self.score_servername) self.parser.set('score', 'server', self.score_port) or, like this self.parser.add_section('score') self.parser.set('score', 'domain', score_domain) self.parser.set('score', 'server', score_servername) self.parser.set('score', 'server', score_port) (if the goal is to call the method from the object without any parameters) 3) Can I create a configParser object and just call self.parser.set() inside the function without passing it as a parameter, or do I pass it as a parameter and call it as parser.set (without the 'self' statement.) Basically..I'm confused on the proper use of 'self' in this type of situation, even after going through all these different tutorials. Any ideas? -thanks in advance\ -- http://mail.python.org/mailman/listinfo/python-list
Re: Confusion About Classes
flamesrock wrote: Hi, I've been playing like mad with all sorts of python modules..but I still can't seem to get my head around the proper use of a class and self. The question stems from this code I made(snippet): [snip misaligned code] When posting to c.l.py it's greatly appreciated if you use spaces instead of tabs in your code. Many newsreaders strip out tabs. The goal is to create a create_server object with the given parameters, and then call the method createUniversalConfig() without passing and parameters to it. Sounds like you want to write: def createUniversalConfig(self): '' self.parser.add_section('score') self.parser.set('score', 'domain', self.score_domain) self.parser.set('score', 'server', self.score_servername) self.parser.set('score', 'server', self.score_port) Then you can do something like: cs = create_server(... appropriate arguments ...) cs.createUniversalConfig() However, this will only work if somewhere previously (probably __init__), you wrote assignment statements like: self.score_domain = ... self.score_servername = ... self.score_port = ... Looking at your code, I don't see that you've done this anywhere. Where should score_domain, score_servername and score_port be coming from? Are they the same as the 'domain', 'servername' and 'httpport' parameters to __init__? If so, you should write your code like: def createUniversalConfig(self): '' self.parser.add_section('score') self.parser.set('score', 'domain', self.domain) self.parser.set('score', 'server', self.servername) self.parser.set('score', 'server', self.__httpport) As an aside, there's probably no need to prefix your variables with double-underscores -- this causes name mangling that's generally not necessary in a we're all consenting adults language like Python. Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: built-in 'property'
[EMAIL PROTECTED] wrote: Hi Can any one explain how property works. It seems to be fine if executed on import i.e. if the property statement is at class scope. Properties are meant to be used at the class scope. A property is a kind of descriptor. See http://users.rcn.com/python/download/Descriptor.htm for details of descriptors. If I put the statement inside __init__() then it appears to work ok but when I try to access the property by e.g. klass.x it just tells me it is a property object. Please show us the code of what you are doing and describe what you are trying to do. There are a lot many things one could do with a property in __init__(). Mostly properties are just defined at the class scope. And rarely would you access klass.x (where x is a property object), mostly you would do instance.x. Is this statement only designed to work at class scope? I really want to set these properties per instance. Again, what exactly are you trying to do? The link above has some simple examples of how to use properties. -- Shalabh -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Interactive Shell - outputting to stdout?
Avi Berkovich wrote: Hey, I can't make it work, I don't get any data from either stdout nor stderr. If I send lines and then close the stdin pipe, I may get an exception message from several lines up. I tried manually reading from the stdout pipe, but it just blocks and hangs no matter what I send over via the stdin pipe. This behavior isn't presented by the command line interpreter by any chance. Any suggestions? Well, I didn't manage to get the pipes working, and finally decided to embed the interpreter into the program, though another option is to embed it into a simple console program consisting of the interpreter initialization and input reading, and just pipe into that. Code for simple interpreter embedded program: #include stdio.h #include python.h int main() { char execString[128]; Py_Initialize(); while (1) { gets(execString); if (!strcmp(execString, QUIT PROGRAM)) break; PyRun_SimpleString(execString); } Py_Finalize(); } This program works well with pipes, though in order to issue the command I have to write \n\r\n (not \r\n or \n ?!) to the pipe. Avi. -- http://mail.python.org/mailman/listinfo/python-list
Tkinter vs wxPython
Greetings all. I will have about 2 weeks to pursue some Python related activities and would like to learn more about the graphical end of things. In that vein I would like some opinions regarding Tkinter and wxPython. (The previously recommended PyGame is appropriate for me for now, but I am looking ahead) I am especially interested in terms of learning curve, documentation, portability across platforms Linux/Windows and anything else you care to add. As I know only what I have read on this forum surfing the web I would really appreciate the input of those who have used both, or decided to use one over the other. Thanks a bunch, Esmail ps: this is basically the same query as posted December 10 Re: GUIs: wxPython vs. Tkinter (and others) -- http://mail.python.org/mailman/listinfo/python-list
Is it possible to open a dbf
Hi, I'm wondering if there is a module available that will open a dbf (actually sco foxpro 2.6) file under linux. Hopefully it will be DAPI 2.0 but I'll accept anything at this point. John -- http://mail.python.org/mailman/listinfo/python-list
Mixing metaclasses and exceptions
In writing the next version of Jpype (Python to Java bridge), I have hot a rather unpleasant wall ... Hopefully it is I who is doing something wrong and i can be fixed ... Since I am bridging Java classes and presenting them as Python classes, I decided to try to create a corresponding python class for every Jva classes accessed inside the python program. So far, everything is great .. until we get to exception handling. Since I am creating classes, on the fly, I thought the easiest and most pythonic way to do it would be to create a metaclass. This is true also for the Java exception classes. The problem arises when I try to raise one of those exception classes ... it sems Python will not allow classes that have a custom metaclass to be raised as exceptions! Even though those classes derive from Exception! To illustrate, try the following snippet : class mc(type) : pass class foo(Exception, object) : __metaclass__ = mc pass try : raise foo, 'ex' except Exception, ex : print ex.__class__, ex Note the above code has nothing to do with JPype. When I try to run the above, I get the following error : exceptions.TypeError exceptions must be classes, instances, or strings (deprecated), not mc Is there anything I can do to raise exception that have metaclasses? Maybe I can make my metaclass acceptable to raise somehow? Thanks for any help anyone can provide. Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it possible to open a dbf
John Fabiani [EMAIL PROTECTED] writes: I'm wondering if there is a module available that will open a dbf (actually sco foxpro 2.6) file under linux. Hopefully it will be DAPI 2.0 but I'll accept anything at this point. Yes, there is, I found such a thing with a minute or so of Google searching when I needed one a while back. I don't have the url any more but I'm sure you can find it the same way I did. -- http://mail.python.org/mailman/listinfo/python-list
Re: argument type
It's me wrote: How do I know if arg1 is a single type (like a number), or a list? isinstance is probably good enough for your needs. if isinstance(arg1, (list, tuple, dict)): print arg1 is a container else: print arg1 is (probably) not a container -- Brian Beck Adventurer of the First Order -- http://mail.python.org/mailman/listinfo/python-list
Re: WxListBox
This was the aforementioned doublepost guys, thanks for all the help though. At that point I was using WxGlade if you were wondering, that's why my controls have such funny names, glade did it!..lol I've since then got my gui to a point where I can live with it, other than the sizing problem when a scroll bar appears, don't believe that will ever be satisfactorily solved. You can either make everything fit perfectly, then it no longer fits when the vertical scroll appears causing you to need a horizontal scroll bar, or have it not fit as well to accomodate the horizontal scroll, or write a function to resize your columns appropriately when needed. None of those solutions is very appealing visually to me, so I'm just gonna let that one slide. Now if there's a plan B on resizing columns in a listctrl somebody tell me, because I can't think of any other way. -- http://mail.python.org/mailman/listinfo/python-list
Re: FutureWarning
On Fri, 24 Dec 2004 10:10:38 -0500, Peter Hansen [EMAIL PROTECTED] wrote: Egor Bolonev wrote: = C:\Documents and Settings\ÕÀ³\My Documents\Scripts\octopus_eye\1\oct_eye_db.py: 213: FutureWarning: hex()/oct() of negative int will return a signed string in P ython 2.4 and up if hex(binascii.crc32(data))[0] == '-': = hex() will return numbers like -0xa1? Python 2.4 is out already, so it's easy to check: c:\python 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. hex(-55) '-0x37' Something has been lost in going to this format, namely the convenient use of 'hex' to represent the abstract bit pattern of a two's complement representation of a signed integer. The only question is how important this will turn out to be. There is no problem generating any of several unambigous representations, but there is a problem deciding which might be the best, e.g. if we want to add a new format to the ones in http://docs.python.org/lib/typesseq-strings.html This bugs me, so I'll say it again: http://mail.python.org/pipermail/python-list/2003-August/178830.html The hex problem is a base-16 analogue to representing negative numbers in complement form in any other base (though even bases provide special possibilities). E.g., for base B we can just ensure that the leading digit is either 0 or B-1, i.e., for base 10 that would be 0 or 9: 0 = 0 1 = 01 -1 = 9 -2 = 98 Not very tested: def basecompl(x, B=10, digits='0123456789abcdefghijklmnopqrstuvwxyz'): ... if not x: return digits[0] ... s = [] ... while x and x != -1: ... x, r = divmod(x, B) ... s.append(digits[r]) ... if not s or s[-1] not in (digits[0], digits[B-1]): ... s.append(digits[x0 and B-1 or 0]) ... return ''.join(s[::-1]) ... basecompl(0) '0' basecompl(1) '01' basecompl(-1) '9' basecompl(-2) '98' basecompl(0, 16) '0' basecompl(1, 16) '01' basecompl(-1, 16) 'f' basecompl(-2, 16) 'fe' basecompl(0, 8) '0' basecompl(1, 8) '01' basecompl(-1, 8) '7' basecompl(-2, 8) '76' Left-padding by repeating the leftmost digit does not change the value, if you decode it consistently, I think: def bcdecode(s, B=10, digits='0123456789abcdefghijklmnopqrstuvwxyz'): ... if s == digits[0]: return 0 ... acc = s[0].lower() == digits[B-1] and -B**len(s) or 0 ... for i, c in enumerate(s[::-1]): ... acc += digits.index(c)*B**i ... return acc ... bcdecode('0') 0 bcdecode('7', 8) -1 bcdecode('777', 8) -1 bcdecode('999', 10) -1 bcdecode('99', 10) -1 bcdecode('099', 10) 99 bcdecode('98') -2 bcdecode('9') -1 bcdecode('01001', 2) 9 bcdecode('1', 2) -1 bcdecode('0', 2) -2 bcdecode('0', 2) 15 bcdecode('1', 2) -1 bcdecode('11', 2) -1 bcdecode('01', 2) 1 bcdecode('0f', 16) 15 bcdecode('f', 16) -1 bcdecode('', 16) -1 bcdecode('fffe', 16) -2 bcdecode('fe', 16) -2 If you wanted to use these as a new format for integer literals you'd have to prefix something to indicate how to interpret, like the old 0x prefix, but not 0x obviously. '0b' for binary would be nice and concise, but maybe something that could express the base value easily would be good too. Since there's no upper case '0' or '1' we could use '0Bn:d' -- which would make int('0B2:10') == int('0B8:76') == int('0B10:98') == int('0B16:fe') == -2 '0b' could be a synonym for '0B2:' and '0h' for '0B16:' Perhaps there could be string formatting to match, e.g., '%width.baseb' # or B for uppercase. So '%.2b'%3 = '011' and '%04.16B'%-3 = 'FFFD' and if you wanted to create literals, you would write '0b2:%.2b'%3 = '0b2:011' and '0b16:%04.16B'%-3 = '0b16:FFFD' respectively. Etc., etc. Oops, that ... acc += digits.index(c)*B**i above should have been ... acc += digits.index(c.lower())*B**i It's obviously not optimized, and there may be bugs, but this should at least communicate the idea (a little modified from Aug 2003 ideas ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list