Re: Possibly dumb question about dicts and __hash__()
Joel Hedlund wrote: > There's one thing about dictionaries and __hash__() methods that puzzle > me. I have a class with several data members, one of which is 'name' (a > str). I would like to store several of these objects in a dict for quick > access ({name:object} style). Now, I was thinking that given a list of > objects I might do something like > > d = {} > for o in objects: > d[o] = o > > and still be able to retrieve the data like so: > > d[name] > > if I just defined a __hash__ method like so: > > def __hash__(self): > return self.name.__hash__() Just the hash is not enough. You need to define equality, too: >>> class Named(object): ... def __init__(self, name): ... self.name = name ... def __hash__(self): ... return hash(self.name) ... def __eq__(self, other): ... try: ... other_name = other.name ... except AttributeError: ... return self.name == other ... return self.name == other_name ... def __repr__(self): ... return "Named(name=%r)" % self.name ... >>> items = [Named(n) for n in "alpha beta gamma".split()] >>> d = dict(zip(items, items)) >>> d["alpha"] Named(name='alpha') Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: stripping unwanted chars from string
Bryan wrote: > >>> keepchars = set(string.letters + string.digits + '-.') Now that looks a lot better. Just don't forget the underscore. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Defining class methods outside of classes
Lord Landon wrote: > Hi, I'm working on a bot written in python. It will consist of a > mostly empty class that will then call a loader which in turn defines > functions and adds them to the class. At the moment, I do this by > using execfile(file,globals()) and calling a load(bot) method defined > in every "module" which takes the functions defined in that perticular > module and does bot.function=function. The problem with that is when I > call bot.function() self doesn't get passed as an argument to the > function. Is there anything I can do to sort this besides calling > bot.function(bot, ...) everytime? Either add the method to the class or make it an instance method. >>> class Bot(object): ... def __init__(self): ... self.name = "bot" ... >>> bot = Bot() >>> def method(self): print "hello from", self.name ... >>> Bot.greet = method >>> bot.greet() hello from bot >>> import new >>> bot.hello = new.instancemethod(method, bot) >>> bot.hello() hello from bot Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: basic python programing
gregarican wrote: >Ravi Teja wrote: > >>How To Ask Questions The Smart Way >>http://www.catb.org/~esr/faqs/smart-questions.html >> >> > >Actual the parent post on the thread wasn't asking a question. They >were making a somewhat puzzling dangling statement. > >"here we discuss the most basic concepts about python" > >Where is _here__? The comp.lang.python newsgroup? In the poster's head? >These are but a sampling of my own stoopid questions. > > The original poster is using the wrong etiquette. This is fairly common practice in an explicit flat-thread environment like PHP BB. I'm not sure it's particularly smart there either, but that is likely where he learned it. Either that or it's yet another email virus. Cheers, Terry -- Terry Hancock ([EMAIL PROTECTED]) Anansi Spaceworks http://www.AnansiSpaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Playability of a file in windows media player
The below code will catch the OnError event that's triggered when you specify a bad URL. import win32com.client class wmpevents: def OnOpenStateChange(self, NewState): """Sent when the control changes OpenState""" print 'OnOpenStateChange', NewState if NewState==win32com.client.constants.wmposMediaOpen: print "Media successfully opened" def OnError(self): """Sent when the control has an error condition""" print 'OnError' print self.Error.Item(0).errorCode, self.Error.Item(0).errorDescription self.Error.clearErrorQueue() win32com.client.gencache.EnsureDispatch('WMPlayer.OCX',0) w=win32com.client.DispatchWithEvents('WMPlayer.OCX', wmpevents) w.URL='some bad URL' Roger "sri2097" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Basically, > I want to check if a URL is playable or not (without actually playing > it). > i.e. given a URL I want to write an automation script to figure it out > for me > if it's playable or not. If you give a bad/invalid URL for windows > media > player to play a pop-up window shows us that it cannot be played. So > I would want to catch that event. > > I have found 2 ways to do this - > > 1) > > import win32com.client, win32api, sre, time > > data = file("webclips.txt") > web_clips = data.readlines () > > shell = win32com.client.Dispatch("WScript.Shell") > shell.Run("wmplayer.exe") > shell.AppActivate("Windows Media Player") > win32api.Sleep(100) > > print "Total :", len(web_clips) > > for webclip in web_clips: >shell.SendKeys("^u", 0) >shell.AppActivate("Open URL") > >shell.SendKeys("{DEL}") >shell.SendKeys(webclip) >shell.SendKeys("~") >time.sleep(25) > >if shell.AppActivate("Windows Media Player"): >webclip = webclip >not_there.append(webclip) >shell.SendKeys("~") > > print len(not_there) > print "Not here: ", not_there > ~ > > In this way I manually fire Windows media player and do the checking. > But It's a brute force way of solving the problem (since for every URL > I keep a > time-out of 25 seconds). As a result it takes a lot of time.I had to > look for a > better solution. My second solution uses Windows much hyped ActiveX > controls. > > 2) > > from win32com.client import Dispatch,DispatchWithEvents > > class WMPEvents: >def OnVisible(self,evt): >print "OnVisible changed:",evt >def OnError(self,evt=None): >print "OnError",evt >def OnMediaError(self,evt=None): >print "OnMediaError",evt >def OnDisconnect(self,evt): >print "OnDisconnect",evt >def OnStatusChange(self): >print "OnStatusChange" >def OnDisconnect(self,evt): >print "Disconnect",evt >def OnBuffering(self,evt): >print "OnBuffering changed:",evt >def OnOpenStateChange(self,evt=None): >print "OnOpenStateChange" ,evt > > mp = DispatchWithEvents("WMPlayer.OCX", WMPEvents) > mp.settings.autoStart = True > webclip_playlist = mp.newPlaylist('Web_Clips', "") > > raw_web_clips = [] > data = file("webclips.txt") > web_clips = data.readlines() > > for url in web_clips: >tune = mp.newMedia(url) >mp.currentPlaylist.appendItem(tune) >mp.controls.playItem (tune) >mp.controls.play() >mp.controls.stop() > > raw_input("Press enter to stop playing") > mp.controls.stop() > mp.close() > > This solution is much faster. But still I'm not able to solve it. > Initially I had > planned to use the "OnOpenStateChange" event to detect if a given URL > is in > a state just about to be opened. That's good enough for me to declare > that a > URL can be played. But as written in MSDN, they suggest not to rely on > state > changes as a definitive way to find details. So, I had to find an > alternative. > There is an event called "OnBuffering", i.e. when a link is found and > is just > about to be buffered this event (Boolean value) is triggered. But it > never seem > to happen. > > I would be truly grateful if you can help in any way. > -- http://mail.python.org/mailman/listinfo/python-list
Re: stripping unwanted chars from string
John Machin wrote: > [expletives deleted] and it was wrong anyway (according to your > requirements); > using \w would keep '_' which is *NOT* alphanumeric. Actually the perl is correct, the explanation was the faulty part. When in doubt, trust the code. Plus I explicitly allowed _ further down, so the mistake should have been fairly obvious. > >>> alphabet = 'qwertyuiopasdfghjklzxcvbnm' # Look, Ma, no thought > required!! Monkey see, monkey type. I won't dignify that with a response. The code that is, I could give a toss about the comments. If you enjoy using such verbose, error-prone representations in your code, god help anyone maintaining it. Including you six months later. Quick, find the difference between these sets at a glance: 'qwertyuiopasdfghjklzxcvbnm' 'abcdefghijklmnopqrstuvwxyz' 'abcdefghijklmnopprstuvwxyz' 'abcdefghijk1mnopqrstuvwxyz' 'qwertyuopasdfghjklzxcvbnm' # no fair peeking And I won't even bring up locales. > >>> keepchars = set(alphabet + alphabet.upper() + '1234567890-.') > >>> fixer = lambda x: ''.join(c for c in x if c in keepchars) Those darn monkeys, always think they're so clever! ;) if "you can" == "you should": do(it) else: do(not) >> Sadly I can find no such beast. Anyone have any insight? As of now, >> regexes look like the best solution. > > I'll leave it to somebody else to dredge up the standard riposte to your > last sentence :-) If the monstrosity above is the best you've got, regexes are clearly the better solution. Readable trumps inscrutable any day. > One point on your requirements: replacing unwanted characters instead of > deleting them may be better -- theoretically possible problems with > deleting are: (1) duplicates (foo and foo_ become the same) (2) '_' > becomes '' which is not a valid filename. Which is why I perform checks for emptiness and uniqueness after the strip. I decided long ago that stripping is preferable to replacement here. > And a legibility problem: if > you hate '_' and ' ' so much, why not change them to '-'? _ is allowed. And I do prefer -, but not for legibility. It doesn't require me to hit Shift. > Oh and just in case the fix was accidentally applied to a path: > > keepchars.update(os.sep) > if os.altsep: keepchars.update(os.altsep) Nope, like I said this is strictly a filename. Stripping out path components is the first thing I do. But thanks for pointing out these common pitfalls for members of our studio audience. Tell him what he's won, Johnny! ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: stripping unwanted chars from string
> >>> keepchars = set(alphabet + alphabet.upper() + '1234567890-.') or >>> keepchars = set(string.letters + string.digits + '-.') bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: stripping unwanted chars from string
On 4/05/2006 1:36 PM, Edward Elliott wrote: > I'm looking for the "best" way to strip a large set of chars from a filename > string (my definition of best usually means succinct and readable). I > only want to allow alphanumeric chars, dashes, and periods. This is what I > would write in (bless me father, for I have sinned...): [expletives deleted] and it was wrong anyway (according to your requirements); using \w would keep '_' which is *NOT* alphanumeric. > I could just use re.sub like the second example, but that's a bit overkill. > I'm trying to figure out if there's a good way to do the same thing with > string methods. string.translate seems to do what I want, the problem is > specifying the set of chars to remove. Obviously hardcoding them all is a > non-starter. > > Working with chars seems to be a bit of a pain. There's no equivalent of > the range function, one has to do something like this: > [chr(x) for x in range(ord('a'), ord('z')+1)] > ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', > 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] >>> alphabet = 'qwertyuiopasdfghjklzxcvbnm' # Look, Ma, no thought required!! Monkey see, monkey type. >>> keepchars = set(alphabet + alphabet.upper() + '1234567890-.') >>> fixer = lambda x: ''.join(c for c in x if c in keepchars) >>> fixer('[EMAIL PROTECTED]') 'qwe456.--Howzat' >>> > > Do that twice for letters, once for numbers, add in a few others, and I get > the chars I want to keep. Then I'd invert the set and call translate. > It's a mess and not worth the trouble. Unless there's some way to expand a > compact representation of a char list and obtain its complement, it looks > like I'll have to use a regex. > > Ideally, there would be a mythical charset module that works like this: > keep = charset.expand (r'\w.-') # or r'a-zA-Z0-9_.-' Where'd that '_' come from? toss = charset.invert (keep) > > Sadly I can find no such beast. Anyone have any insight? As of now, > regexes look like the best solution. I'll leave it to somebody else to dredge up the standard riposte to your last sentence :-) One point on your requirements: replacing unwanted characters instead of deleting them may be better -- theoretically possible problems with deleting are: (1) duplicates (foo and foo_ become the same) (2) '_' becomes '' which is not a valid filename. And a legibility problem: if you hate '_' and ' ' so much, why not change them to '-'? Oh and just in case the fix was accidentally applied to a path: keepchars.update(os.sep) if os.altsep: keepchars.update(os.altsep) HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question on code vetting
[EMAIL PROTECTED] wrote: > Hi. > > I have visited the Python web site and read some information on who the > commiters are and how to go about submitting code to them, but I have not > been able to locate any information regarding the process for vetting the > code to identify any possible IP infringement before it is committed. How do > the committers ascertain the originality of the code before it becomes part > of the base? They tell themselves very sternly not to commit code that isn't appropriately licensed. > Is there any use of tools like BlackDuck ProtexIP or the > competing Palamida product to scan for matches to code that is already > licensed elsewhere? No. > Also, is the same or a different standard of IP assurance practiced for the > Cheese Shop? There is no vetting for the Cheese Shop. Anyone can post packages there. If some illegal-to-redistribute code is discovered, it will probably be removed by the administrators. This hasn't come up, yet, I don't think. If you want the code to be vetted, you have to do it yourself. Besides, if you don't trust the commiters and the package authors not to infringe on other peoples' IP, why do you trust them to report infringement? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonic way to sort
On May 4, 2006, at 12:12 AM, [EMAIL PROTECTED] wrote: > hi > I have a file with columns delimited by '~' like this: > > 1SOME STRING ~ABC~12311232432D~20060401~ > 2SOME STRING ~DEF~13534534543C~20060401~ > 3SOME STRING ~ACD~14353453554G~20060401~ > > . > > What is the pythonic way to sort this type of structured text file? > Say i want to sort by 2nd column , ie ABC, ACD,DEF ? so that it becomes > > 1SOME STRING ~ABC~12311232432D~20060401~ > 3SOME STRING ~ACD~14353453554G~20060401~ > 2SOME STRING ~DEF~13534534543C~20060401~ > ? > I know for a start, that i have to split on '~', then append all the > second columns into a list, then sort the list using sort(), but i am > stuck with how to get the rest of the corresponding columns after the > sort > > thanks... > A couple ways. Assume that you have the lines in a list called 'lines', as follows: lines = [ "1SOME STRING ~ABC~12311232432D~20060401~", "3SOME STRING ~ACD~14353453554G~20060401~", "2SOME STRING ~DEF~13534534543C~20060401~"] The more traditional way would be to define your own comparison function: def my_cmp(x,y): return cmp( x.split("~")[1], y.split("~")[1]) lines.sort(cmp=my_cmp) The newer, faster way, would be to define your own key function: def my_key(x): return x.split("~")[1] lines.sort(key=my_key) The key function is faster because you only have to do the split("~")[1] once for each line, whereas it will be done many times for each line if you use a comparison function. Jay P. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question on code vetting
Edward, I agree with your point, which is why I asked the question. Risk cannot be eliminated, but it can be understood and managed so that useful work can still be done. If there is any way I can find out what the commiters do prior to reaching a decision to accept or reject a particular submission, I would like to know about it. Thanks in advance, Bill "Edward Elliott" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Dennis Lee Bieber wrote: > >> I work for a risk-averse company, and I want to compile a solid case for > >> obtaining and using Python at work. > >> > > Given the nature of the US Patent Office... You might as well lock > > the doors now... > > > > The Patent Office could issue a patent next week that makes all > > bytecode interpreted languages subject to some royalty... > > Risk isn't just what could happen, it's how likely it is and what effects it > would have. A patent affecting millions of installed interpreters is > pretty unlikely and would have many challengers. Even if it were upheld, > how many larger companies with deeper pockets would they go after before > his? And everyone stuck in the same boat would quickly work towards a > non-infringing solution. Cases like MS-EOLAS and RIM-NTP aren't exactly a > daily occurence. They also demonstrate why there really is safety in > numbers. > > Plus all the potential negatives have to weighed against the increased > productivity his company gains from using a scripting language. The gains > may more than offset any potential patent settlement. > > Risk-averse doesn't mean head-in-the-sand. > -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonic way to sort
[EMAIL PROTECTED] wrote: > hi > I have a file with columns delimited by '~' like this: > > 1SOME STRING ~ABC~12311232432D~20060401~ > 2SOME STRING ~DEF~13534534543C~20060401~ > 3SOME STRING ~ACD~14353453554G~20060401~ > > . > > What is the pythonic way to sort this type of structured text file? > Say i want to sort by 2nd column , ie ABC, ACD,DEF ? so that it becomes > > 1SOME STRING ~ABC~12311232432D~20060401~ > 3SOME STRING ~ACD~14353453554G~20060401~ > 2SOME STRING ~DEF~13534534543C~20060401~ > ? > I know for a start, that i have to split on '~', then append all the > second columns into a list, then sort the list using sort(), but i am > stuck with how to get the rest of the corresponding columns after the > sort In Python 2.4 and up, you can use the key= keyword to list.sort(). E.g. In [2]: text = """1SOME STRING ~ABC~12311232432D~20060401~ ...: 2SOME STRING ~DEF~13534534543C~20060401~ ...: 3SOME STRING ~ACD~14353453554G~20060401~""" In [3]: lines = text.split('\n') In [4]: lines Out[4]: ['1SOME STRING ~ABC~12311232432D~20060401~', '2SOME STRING ~DEF~13534534543C~20060401~', '3SOME STRING ~ACD~14353453554G~20060401~'] In [5]: lines.sort(key=lambda x: x.split('~')[1]) In [6]: lines Out[6]: ['1SOME STRING ~ABC~12311232432D~20060401~', '3SOME STRING ~ACD~14353453554G~20060401~', '2SOME STRING ~DEF~13534534543C~20060401~'] -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
pythonic way to sort
hi I have a file with columns delimited by '~' like this: 1SOME STRING ~ABC~12311232432D~20060401~ 2SOME STRING ~DEF~13534534543C~20060401~ 3SOME STRING ~ACD~14353453554G~20060401~ . What is the pythonic way to sort this type of structured text file? Say i want to sort by 2nd column , ie ABC, ACD,DEF ? so that it becomes 1SOME STRING ~ABC~12311232432D~20060401~ 3SOME STRING ~ACD~14353453554G~20060401~ 2SOME STRING ~DEF~13534534543C~20060401~ ? I know for a start, that i have to split on '~', then append all the second columns into a list, then sort the list using sort(), but i am stuck with how to get the rest of the corresponding columns after the sort thanks... -- http://mail.python.org/mailman/listinfo/python-list
Re: python strings
Gerhard Häring wrote: > Python 2.4.2 (#2, Sep 30 2005, 21:19:01) > [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. s = "\x000" s[0] == chr(0) > True > > - -- Gerhard this works too :) >>> s = '\x001' >>> s[0] == chr(0) True >>> s = '\x00abc' >>> s[0] == chr(0) True i think it would be more clear not to use 3 digits for this example since \x only uses the next two numbers, not 3. >>> s = '\x00' >>> s[0] == chr(0) True bryan -- http://mail.python.org/mailman/listinfo/python-list
Fwd: what is the 'host' for SMTP?
Uh, I don't sent to list :P -- Forwarded message -- From: Marco Carvalho <[EMAIL PROTECTED]> Date: May 4, 2006 12:45 AM Subject: Re: what is the 'host' for SMTP? To: John Salerno <[EMAIL PROTECTED]> On 5/3/06, John Salerno <[EMAIL PROTECTED]> wrote: > Steve R. Hastings wrote: > > Thanks for all the information. Very helpful. But I'm still a little > confused, because it seems like that's not enough information. If all I > put in is, for example, smtp.gmail.com, how is that directed to my own > email address? Do I still need to include other, more specific (i.e. > personal) information elsewhere? You need a little more than a smtp server address to send an e-mail. If you are using smtplib: import smtplib sender = "[EMAIL PROTECTED]" to = "[EMAIL PROTECTED]" message = "blablabla" smtplogin = "your_login_on_gmail" smtppasswd = "your_password_on_gmail" smtpserver = "smtp.gmail.com" smtp = smtplib.SMTP(smtpserver) smtp.login(smtplogin,smtppasswd) smtp.sendmail(sender, to, message) smtp.quit() I don't put the correct construction of the message's headers and body, it's another story :-) -- Marco Carvalho (macs) | marcoacarvalho(a)gmail.com http://arrakis.no-ip.info | http://cdd.debian-br.org Maceio - Alagoas - Brazil Debian GNU/Linux unstable (Sid) GNU-PG ID:08D82127 - Linux Registered User #141545 Notícias Semanais do Debian em Português: http://www.debian.org/News/weekly Alertas de Segurança Debian (DSA): http://www.debian.org/security -- Marco Carvalho (macs) | marcoacarvalho(a)gmail.com http://arrakis.no-ip.info | http://cdd.debian-br.org Maceio - Alagoas - Brazil Debian GNU/Linux unstable (Sid) GNU-PG ID:08D82127 - Linux Registered User #141545 Notícias Semanais do Debian em Português: http://www.debian.org/News/weekly Alertas de Segurança Debian (DSA): http://www.debian.org/security -- http://mail.python.org/mailman/listinfo/python-list
RE: Packet finding and clicking...
Grant Edwards wrote: > On 2006-05-04, klauts <[EMAIL PROTECTED]> wrote: > >> anyone have any help on this subjecT? > > I use tcpdump or ethereal for packet finding. > > For clicking, I use a logitech optical wheel mouse for desktops > or the integrated touchpoint/touchpad on my IBM ThinkPad. Or in other words ... http://www.catb.org/~esr/faqs/smart-questions.html Tim Delaney -- http://mail.python.org/mailman/listinfo/python-list
stripping unwanted chars from string
I'm looking for the "best" way to strip a large set of chars from a filename string (my definition of best usually means succinct and readable). I only want to allow alphanumeric chars, dashes, and periods. This is what I would write in Perl (bless me father, for I have sinned...): $filename =~ tr/\w.-//cd, or equivalently $filename =~ s/[^\w.-]// I could just use re.sub like the second example, but that's a bit overkill. I'm trying to figure out if there's a good way to do the same thing with string methods. string.translate seems to do what I want, the problem is specifying the set of chars to remove. Obviously hardcoding them all is a non-starter. Working with chars seems to be a bit of a pain. There's no equivalent of the range function, one has to do something like this: >>> [chr(x) for x in range(ord('a'), ord('z')+1)] ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] Do that twice for letters, once for numbers, add in a few others, and I get the chars I want to keep. Then I'd invert the set and call translate. It's a mess and not worth the trouble. Unless there's some way to expand a compact representation of a char list and obtain its complement, it looks like I'll have to use a regex. Ideally, there would be a mythical charset module that works like this: >>> keep = charset.expand (r'\w.-') # or r'a-zA-Z0-9_.-' >>> toss = charset.invert (keep) Sadly I can find no such beast. Anyone have any insight? As of now, regexes look like the best solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: Gettings subdirectories
Thank you all for the great info and education. rick -- http://mail.python.org/mailman/listinfo/python-list
Re: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled
Grant > Having sleep() take orders of magnitude longer than it should I seen a few times where sleep returns after some seconds or even after tens of seconds (my code above check for that). But most of the time it gets stuck forever. Olaf -- http://mail.python.org/mailman/listinfo/python-list
Re: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled
On 2006-05-04, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Please try. > > The sleep statement does not return! Never, or does it just take a long time? > And this should not happen. Dude, it's MS Windows. It does all _sorts_ of stuff that it shouldn't. Having sleep() take orders of magnitude longer than it should is not an uncommon complaint for MS Windows users. There was a fairly extensive thread in this group about that problem just a few weeks ago. IIRC, disabling some other program or service fixed it for one MS victem. > The code above does nothing special or unusual. The problem > only occurs if 2 threads use the sleep statement and > hyper-threading is enabled. That part is new. I'm pretty sure other people who complained about sleep() not returning in a reasonable amount of time saw it all of the time. -- Grant Edwards grante Yow! I was giving HAIR at CUTS to th' SAUCER PEOPLE visi.com... I'm CLEAN!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Packet finding and clicking...
On 2006-05-04, klauts <[EMAIL PROTECTED]> wrote: > anyone have any help on this subjecT? I use tcpdump or ethereal for packet finding. For clicking, I use a logitech optical wheel mouse for desktops or the integrated touchpoint/touchpad on my IBM ThinkPad. -- Grant Edwards grante Yow! I want a VEGETARIAN at BURRITO to go... with visi.comEXTRA MSG!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Any useful benefit to a tiny OS written in Python?
[EMAIL PROTECTED] wrote: > I was curious if there was any benefit to having an OS written > in Python. > > The only benefit I can think of is that maybe Python is easier > to audit for security bugs than C is. > > > Any other benefits? > > Chris > http://unununium.org/ -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: This coding style bad practise?
Am Donnerstag 04 Mai 2006 01:04 schrieb Martin P. Hellwig: > Because of: > id = IDGenerator("01",99) > id() > > > > Traceback (most recent call last): > > File "", line 1, in ? > > id() > > TypeError: 'IDGenerator' object is not callable > > But i do appreciate your comment, thanks! You need to define a __call__(self)-method on your class so that instances are callable... Basically, what Bruno was saying, is that you rename your __repr__(self) to __call__(self), and see what happens. --- Heiko. -- http://mail.python.org/mailman/listinfo/python-list
Any useful benefit to a tiny OS written in Python?
I was curious if there was any benefit to having an OS written in Python. The only benefit I can think of is that maybe Python is easier to audit for security bugs than C is. Any other benefits? Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled
Tim > I didn't run it for hours ;-) Please try. The sleep statement does not return! And this should not happen. The code above does nothing special or unusual. The problem only occurs if 2 threads use the sleep statement and hyper-threading is enabled. We discovered this bug perhaps a year ago. The only solution was to tell our customers to disable hyper-threading (you can imagine they did not like our "solution" very much). It then took many days of hard work to isolate the problem down to the code I posted above. > Where "hang" means they stop printing. Our Python code just stops running (locking up the entire application). We use Qt for our GUI. We have over a hundred .py files. We use a total of 4 threads (they get created once and stay running). One thread uses sockets. Once the application locks up (getting stuck in a sleep statement) all comes back to live if I pull the network cable out. So perhaps the socket thread returns from the sleep statement and other threads return to live because they were waiting for the socket thread. Our software runs on both Windows and Linux. We are not sure if the problem also happens on Linux. In any case, if someone else can confirm the bug then this is a serious problem meriting further investigation. We have searched the Internet far and wide and were not able to find any information that indicates that someone else has reported a similar problem (neither Python nor Windows Sleep related). Thank you for your help. Olaf -- http://mail.python.org/mailman/listinfo/python-list
Re: Packet finding and clicking...
anyone have any help on this subjecT? -- http://mail.python.org/mailman/listinfo/python-list
Re: Gettings subdirectories
Florian Lindner wrote: > Hello, > how can I get all subdirectories of a given directories? os.listdir() gives > me all entries and I've found no way to tell if an object is a file or a > directory. > > Thanks, > > Florian Here is a quick hack: import os import os.path givenDir = "/" listing = os.listdir(givenDir) for item in listing: joinPath = os.path.join(givenDir, item) normPath = os.path.normpath(joinPath) if os.path.isdir(normPath): print normPath -- http://mail.python.org/mailman/listinfo/python-list
Re: scope of variables
> is the code below correct? > > b = 3 > def adding(a) > print a + b > > it seams not to see the up-level scope where b is defined. Yes except for the missing : at the end of the "def" line. Rob -- http://mail.python.org/mailman/listinfo/python-list
Fastest quoting
What is the fastest way (execution speed) to backslash-escape characters from a specific set? Specifically: \r, \n and \0? (i.e. I need "some\r\nstring\0" to become "some\\r\\nstring\\0") -- http://mail.python.org/mailman/listinfo/python-list
OT: CAD
I am completely empty and shallow. I use no CAD package at all now. I would like to buy one for recreational use, instead of watching American Idol. What CAD package has integrated FEA and rigid body calculations so that I could design a bar stool, and easily determine: a) if it is top-heavy, so that drunken customers could easily tip it over, and b) if a fat drunken customer sat on it, which part would give way first. Also, are there such things as libraries of materials that I could specify, which the FEA would take into account, so that a bar stool made of PVC would bend differently from a bar stool made of tungsten? Also, what about Python and CAD? I've seen http://free-cad.sourceforge.net and pythoncad, but have any major CAD vendors incorporated Python, sort of the way that ESRI used Python in it's ArcView GIS product? -- http://mail.python.org/mailman/listinfo/python-list
Re: Can Python kill a child process that keeps on running?
Dennis Lee Bieber wrote: > On Tue, 02 May 2006 17:00:42 GMT, "I. Myself" <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > >> I'm an intermediate Python programmer. Can you explain to me how ctypes >> will let me kill a child process? >> >> > ctypes allows you to call functions within pretty much any DLL file > (whereas the ActiveState win32api module only calls some core functions) > Ok, I don't know which function to call in which .dll file, but perhaps I can find out. Will ctypes will be a module in Python 2.5? Thanks Mitchell Timin -- I'm proud of http://ANNEvolve.sourceforge.net. If you want to write software, or articles, or do testing or research for ANNEvolve, let me know. Humans may know that my email address is: (but remove the 3 digit number) zenguy at shaw666 dot ca -- http://mail.python.org/mailman/listinfo/python-list
Re: Gettings subdirectories
Sorry that I was unclear. I sorta know how os.walk works. It's the .next() trick that I had never seen before. For instance, if you run that statement without the .next() on it, it says "Too many items to unpack" but with the .next() it stops it somehow, right where I want it to stop. It's an iterator method, right? I found it in Beazely, now I'll try to understand it. Sorry to trouble you. rick -- http://mail.python.org/mailman/listinfo/python-list
Re: Gettings subdirectories
Ben Finney wrote: > We must be reading different Python websites. > > walk(top[, topdown=True [, onerror=None]]) > > walk() generates the file names in a directory tree, by walking > the tree either top down or bottom up. For each directory in the > tree rooted at directory top (including top itself), it yields a > 3-tuple (dirpath, dirnames, filenames). Maybe he meant os.path.walk, although that's still not quite what he had. -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question: "TypeError" wrong number of args
Ben Finney wrote: > As I understand it, the point was not what the code does, but to give > a sample input (a Python program) for the "simple text processor" you > described to wade through. Ah, well then, there's no need for a full-blown parser. It should suffice to recognize a class definition and modify the parameter list of every def indented one level further than that. Then pick out the static methods and 'undo' those. Can be done in one pass by keeping the class definition in memory until you've scanned the whole thing, then adding self where needed as you spit it back out. Implementation is left as an exercise for the reader. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python & SSL
Sybren Stuvel wrote: > I'm curious. Can you give me an example? AFAIK you need to know who > you're talking to before transmitting sensitive information, otherwise > you could be talking to anybody - and that's just what you wanted to > prevent with the encryption, right? Encryption has multiple meanings. In the general sense, it encompasses all of cryptography and the information security properties crypto provides. This meaning is rather imprecise and you run into problems using it to answer questions like yours. I won't encryption this way again in this post. In a more specific/technical sense, encryption protects the privacy of transmitted information, preventing third-party eavesdropping. It makes no guarantees who's on the other end of your encrypted pipe. Block cipher modes (CBC-DES, CTR-Rijndael/AES, etc) and asymmetric cipher modes (RSA-OAEP) are examples. Integrity guarantees that the data sent is the same as the data received. Authentication verifies the party on the other end of your pipe. This is the primary purpose of SSL certs, authenticating web sites to browsers (you get data encryption too, but that's somewhat less important). Note that it doesn't verify the party's identity or trustworthiness, only that they know a particular secret. The assumption is that if the certificate system is setup correctly, possession of that secret makes them trustworthy (or rather, you can trust the site because their secret proves that a cert authority somewhere trusts them in some fashion). Trustworthy for what is never defined. If that sounds convoluted or illogical, it is. "Ten Risk of PKI" is a good intro to why this chain of trust isn't all it's cracked up to be. It's good reading to understand exactly what you benefits you get from an SSL connection. http://www.schneier.com/paper-pki.html So in a long-winded way, I've answered your question. The short and sweet of it is, yes, SSL is meant to prevent you from "talking to anybody". In that it succeeds* -- but only so far as making sure the site you're talking to paid some money to one of the dozens of cert authorities for a minimal background check. You've gone from "anybody" to "anybody with a couple hundred bucks and spare time to blow". *at least, until the end user completely ignores the warning dialogs and accepts whatever invalid cert he's presented with. Of course if you control the server and serve a small clientele who already trust you, you can have clients import your own cert so they really can be sure who they're talking to -- as long as your master key remains secret. Watch out for hackers and disgruntled employees. The moral of this story is: computer security is an ugly, complex business. -- http://mail.python.org/mailman/listinfo/python-list
Re: milliseconds are not stored in the timestamp KInterbasDB + Firebird
to provide feedback: David Rushby (the autor of the KInterbasDB) has solved the problem applying such a future in the code. Thank you David. snapshots: http://kinterbasdb.sourceforge.net/snapshots/3.2/kinterbasdb-3.2_pre_20060503.src.tar.gz http://kinterbasdb.sourceforge.net/snapshots/3.2/kinterbasdb-3.2_pre_20060503.win32-FB-2.0-py2.4.exe Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: This coding style bad practise?
keirr wrote: > Martin P. Hellwig wrote: >> Hi all, >> >> I created a class which creates a relative unique id string, now my >> program just works fine and as expected but somehow I get the feeling >> that I misused the __repr__ since I guess people expect to 'execute' a >> function in an instance instead of using it's representation string of >> the instance itself, could you elaborate whether you find this bad >> practice and if yes what would have been a better way to do it? >> >> TIA >> > > Rather than comment on the style of using a class, I'll just suggest an > alternative. > You can use a generator function, which yields the next id when called; > at least that's > how I'd implement an IDgenerator. > > Cheers, > > Keir. > Thanks for your comment, I do use a generator in my class because I wanted to wrap my subversion when its on its end I had a choice of looping in with an if check or using a generator with try except, this time I choose a generator, though mostly I directly use a generator for these type of functions. -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: scope of variables
Gary Wessle wrote: > the example was an in-accuretlly representation of a the problem I am > having. my apologies. > > a = [] > def prnt(): >print len(a) > prnt > > > I expect to get 0 "the length of list a" You want prnt(), not prnt: >>> a = [] >>> def prnt(): ... print len(a) ... >>> prnt >>> prnt() 0 --Ryan -- http://mail.python.org/mailman/listinfo/python-list
Re: Gettings subdirectories
"BartlebyScrivener" <[EMAIL PROTECTED]> writes: > >> root, dirnames, filenames = os.walk(r"C:\").next() > > Wow. How does that work? Just point me to where I can read about it. I > don't see it under os.walk. We must be reading different Python websites. walk(top[, topdown=True [, onerror=None]]) walk() generates the file names in a directory tree, by walking the tree either top down or bottom up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). http://docs.python.org/lib/os-file-dir.html#l2h-1638> -- \ "Sittin' on the fence, that's a dangerous course / You can even | `\catch a bullet from the peace-keeping force" -- Dire Straits, | _o__) _Once Upon A Time In The West_ | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: This coding style bad practise?
Bruno Desthuilliers wrote: > > Why not just use the call operator instead ? ie: > > >>> id = IDGenerator(...) > >>> id() > 01_20060424_151903_1 > >>> id() > 01_20060424_151905_2 > Because of: id = IDGenerator("01",99) id() > Traceback (most recent call last): > File "", line 1, in ? > id() > TypeError: 'IDGenerator' object is not callable But i do appreciate your comment, thanks! -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__.py, __path__ and packaging
Sandro Dentella wrote: > The structure of my package: > > python/ > `-- dbg/ >|-- __init__.py >`-- lib >|-- __init__.py >|-- debug.py >`-- gtk_dbg.py > > my sys.path includes 'python' and I wanted that the content of debug.py was > simply included by: 'import dbg', so I wrote dbg/__init__.py as follows: > > import os > Dir = os.path.dirname(__file__) > __path__ = [os.path.join(Dir, 'lib')] > from debug import * What you probably want in python/dbg/__init__.py to get values is: from dbg.lib.debug import * > BUT, if I set some variables they are not correctly seen: > import dbg > dbg.DBG = 1 > function test included in debug.py raises NameError: > def test(): > print DBG > NameError: global name 'DBG' is not defined` > > What's happening? DBG seems to be set, as shown by dir(dbg)... any hints? You misunderstand modules and python variables. Each module has a dictionary associating the names of its globals and their current values. After: import dbg.lib.debug, dbg.lib.gtk_dbg you have four modules: dbg # Corresponds to python/dbg/__init__.py dbg.lib # Corresponds to python/dbg/lib/__init__.py dbg.lib.debug # Corresponds to python/dbg/lib/debug.py dbg.lib.gtk_dbg # Corresponds to python/dbg/lib/gtk_dbg.py Each has its own globals. after: dbg.DBG = 1 the dbg module's global dictionary contains an entry mapping 'DBG' to 1 after: dbg.DBG = 1+2 the dbg module's global dictionary contains an entry mapping 'DBG' to 3 In no case will an assignment to a global in dbg cause an assignment to anything in dbg.lib.debug. The "from dbg.lib.debug import *" statement can be seen as a module import followed by a fancy multiple assignment, where module dbg.lib.debug is first imported, then its globals are assigned to globals of the same names in module dbg. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: scope of variables
Gary Wessle wrote: > the example was an in-accuretlly representation of a the problem I am > having. my apologies. > > a = [] > def prnt(): >print len(a) > prnt > > > I expect to get 0 "the length of list a" Python requires parenthesis to call a function. >>> a = [] >>> def prnt(): ... print len(a) ... >>> prnt >>> prnt() 0 -- http://mail.python.org/mailman/listinfo/python-list
Re: scope of variables
Try >>> prnt() o.o' On 04 May 2006 08:25:01 +1000, Gary Wessle <[EMAIL PROTECTED]> wrote: > "Steve R. Hastings" <[EMAIL PROTECTED]> writes: > > > On Thu, 04 May 2006 07:02:43 +1000, Gary Wessle wrote: > > > b = 3 > > > def adding(a) > > > print a + b > > > > > > it seams not to see the up-level scope where b is defined. > > > > Assuming you put a ':' after the "def adding(a)", this should work in > > recent versions of Python. In Python 2.0 and older, this will not work. > > the example was an in-accuretlly representation of a the problem I am > having. my apologies. > > a = [] > def prnt(): >print len(a) > > >>> prnt > > > I expect to get 0 "the length of list a" > -- > http://mail.python.org/mailman/listinfo/python-list > -- Lord Landon rules over all! -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question: "TypeError" wrong number of args
Edward Elliott <[EMAIL PROTECTED]> writes: > Marc 'BlackJack' Rintsch wrote: > > Edward Elliott wrote: > >> I can prove that assertion too: make a simple text processor that > >> reads Python source code and outputs the same source code with > >> only one change: insert the string 'self" as the first parameter > >> of every "def somemethod". Next run the output source code with > >> the normal Python > > > > Okay, let's start with writing a simple text processor for this > > little mess:: > > I didn't even try to wade through that morass of monocharacter > variables. Anyone wanna summarize the point of that code? As I understand it, the point was not what the code does, but to give a sample input (a Python program) for the "simple text processor" you described to wade through. -- \"I always had a repulsive need to be something more than | `\ human." -- David Bowie | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Gettings subdirectories
>> root, dirnames, filenames = os.walk(r"C:\").next() Wow. How does that work? Just point me to where I can read about it. I don't see it under os.walk. That's cool. Thanks, Rick -- http://mail.python.org/mailman/listinfo/python-list
Re: Mutable String
Pierre Thibault wrote: > I would like to know if there are modules offering a mutable version of > strings in Python? Nope. But, for some uses: import array stringish = array.array{'c', 'Whatever, kiddo!') stringish[-6:-1] = array.array('c', 'dudes') print stringish.tostring() -- -Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question: "TypeError" wrong number of args
Marc 'BlackJack' Rintsch wrote: > Edward Elliott wrote: >> I can prove that assertion too: make a simple text processor that reads >> Python source code and outputs the same source code with only one change: >> insert the string 'self" as the first parameter of every "def >> somemethod". Next run the output source code with the normal Python > > Okay, let's start with writing a simple text processor for this little > mess:: I didn't even try to wade through that morass of monocharacter variables. Anyone wanna summarize the point of that code? -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question: "TypeError" wrong number of args
Ben Finney wrote: > My basis for rejecting the proposal is that it claims to offer net > simplicity, yet it breaks at least two of the admonishments that > simplify Python. As do other features of Python. Or did you forget the follow-up to the special cases "rule"? Special cases aren't special enough to break the rules. Although practicality beats purity. -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question: "TypeError" wrong number of args
Ben Finney wrote: > Edward Elliott <[EMAIL PROTECTED]> writes: >> As long as we're trotting out aphorisms > > The ones I quoted were from Python. > >>> import this Yes I know where it's from. > You've misunderstood "don't repeat yourself". It advocates *one* > definition of any given thing in the code. You are advocating *zero* > definitions of 'self' in the code. It's implicitly defined by the language/runtime, so I shouldn't need to define it in my code. Doing so is duplication of effort, aka DRY. An implicit definition is not an empty definition. Where do the semantics of 'while' and 'for' come from? Same thing, it's implicit in the language. -- http://mail.python.org/mailman/listinfo/python-list
Re: scope of variables
"Steve R. Hastings" <[EMAIL PROTECTED]> writes: > On Thu, 04 May 2006 07:02:43 +1000, Gary Wessle wrote: > > b = 3 > > def adding(a) > > print a + b > > > > it seams not to see the up-level scope where b is defined. > > Assuming you put a ':' after the "def adding(a)", this should work in > recent versions of Python. In Python 2.0 and older, this will not work. the example was an in-accuretlly representation of a the problem I am having. my apologies. a = [] def prnt(): print len(a) >>> prnt I expect to get 0 "the length of list a" -- http://mail.python.org/mailman/listinfo/python-list
Re: Because of multithreading semantics, this is not reliable.
Tim Peters wrote: > That puts them in the > "attractive nuisance" category for many people. Argh. That gives me bad flashbacks to my torts final from Mon, which had a bona-fide "attractive nuisance" problem on it. Damn you, Tim Peters! ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: scope of variables
Gary Wessle <[EMAIL PROTECTED]> writes: > is the code below correct? It's best to post an example that you've tried yourself, and that is small but completely demonstrates the issue in question. > b = 3 > def adding(a) > print a + b This, for example, would fail the syntax check (the 'def' statement needs a trailing colon). After that's fixed, the code runs, but shows no output. A complete, minimal, working example will help people answer your question. -- \ "[W]e are still the first generation of users, and for all that | `\ we may have invented the net, we still don't really get it." | _o__) -- Douglas Adams | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Python & SSL
John J. Lee enlightened us with: > Of course, remembering that the first thing to ask in response to > "is it secure?" is "against what?", for lots of purposes it just > doesn't matter that it ignores certificates. I'm curious. Can you give me an example? AFAIK you need to know who you're talking to before transmitting sensitive information, otherwise you could be talking to anybody - and that's just what you wanted to prevent with the encryption, right? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: This coding style bad practise?
Bruno Desthuilliers wrote: > Martin P. Hellwig a écrit : >>I created a class which creates a relative unique id string, now my >>program just works fine and as expected but somehow I get the feeling >>that I misused the __repr__ since I guess people expect to 'execute' a >>function in an instance instead of using it's representation string of >>the instance itself, could you elaborate whether you find this bad >>practice and if yes what would have been a better way to do it? > > Why not just use the call operator instead ? ie: > > >>> id = IDGenerator(...) > >>> id() > 01_20060424_151903_1 > >>> id() > 01_20060424_151905_2 because that shadows a builtin? sorry, could not resist :-) Cheers, Carl Friedrch Bolz -- http://mail.python.org/mailman/listinfo/python-list
Re: This coding style bad practise?
Bruno Desthuilliers wrote: > Martin P. Hellwig a écrit : >>I created a class which creates a relative unique id string, now my >>program just works fine and as expected but somehow I get the feeling >>that I misused the __repr__ since I guess people expect to 'execute' a >>function in an instance instead of using it's representation string of >>the instance itself, could you elaborate whether you find this bad >>practice and if yes what would have been a better way to do it? > > Why not just use the call operator instead ? ie: > > >>> id = IDGenerator(...) > >>> id() > 01_20060424_151903_1 > >>> id() > 01_20060424_151905_2 because that shadows a builtin? sorry, could not resist :-) Cheers, Carl Friedrch Bolz -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question: "TypeError" wrong number of args
Bruno Desthuilliers <[EMAIL PROTECTED]> writes: > Ben Finney a écrit : > > So now you're proposing that this be a special case when a > > function is declared by that particular syntax, and it should be > > different to when a function is created outside the class > > definition and added as a method to the object at run-time. > > > > Thus breaking not only "explicit is better than implicit", > > This one can be subject to discussion. All the assertions in 'import this' are subject to discussion. They're even contradictory. > > but also "special cases aren't special enough to break the rules". > > Yeps, I think this is what I don't like here. > > > Still -1. > > I'm not yet ready to vote for Edward's proposition - as you say, it > makes 'def statements into a class statement' a special case, and I > don't like special cases too much (OTOH, there actually *are* > special cases - __new__() being an example) - *but* it's not that > silly either IMHO, and I think this should not be dismissed on a > purely reactional basis. My basis for rejecting the proposal is that it claims to offer net simplicity, yet it breaks at least two of the admonishments that simplify Python. -- \"My house is made out of balsa wood, so when I want to scare | `\ the neighborhood kids I lift it over my head and tell them to | _o__) get out of my yard or I'll throw it at them." -- Steven Wright | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Python & SSL
Benji York <[EMAIL PROTECTED]> writes: > James Stroud wrote: > > I have been trying to make an https client with python > > You probably don't want to use the standard library for HTTPS; here's a > quote from the socket module docs about SSL: > > Warning: This does not do any certificate verification! [...] Of course, remembering that the first thing to ask in response to "is it secure?" is "against what?", for lots of purposes it just doesn't matter that it ignores certificates. John -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question: "TypeError" wrong number of args
Edward Elliott <[EMAIL PROTECTED]> writes: > As long as we're trotting out aphorisms The ones I quoted were from Python. >>> import this > how about DRY: Don't Repeat Yourself. The rule couldn't be clearer: > don't repeat your SELF. ;) Yet that's exactly what explicitly > declaring self does, forces me to needlessly repeat what everyone > already knows: methods take the object instance as their first > parameter. You've misunderstood "don't repeat yourself". It advocates *one* definition of any given thing in the code. You are advocating *zero* definitions of 'self' in the code. -- \ "No wonder I'm all confused; one of my parents was a woman, the | `\ other was a man." -- Ashleigh Brilliant | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled
>> What do you mean "stop responding"? [EMAIL PROTECTED] > Both threads print their thread numbers (either 1 or 2) approximately > every 10 seconds. However, after a while (minutes to hours) both > programs (see above) hang! Where "hang" means they stop printing. > Pressing ctrl-c (after the printing stops) causes the threads to "wake > up" from their sleep statement. And since the sleep took more than 1 > seconds the thread number and the duration of the sleep is printed to > the screen. > > Do you have a hyper-threading/dual/multi core CPU? Did you try this? I was using a 3.4 GHz Pentium 4 (single core) with hyper-threading enabled. I didn't run it for hours ;-) But supposing I do and see a hang, it's unlikely that will have anything to do with Python. On Windows, time.sleep() called from any thread other than the main thread just calls the Win32 API Sleep() function, after converting the argument to milliseconds. So it may be more fruitful to recode your test program in C (if there is a bug here, it's most likely in Microsoft's implementation of its Sleep() function). -- http://mail.python.org/mailman/listinfo/python-list
Defining class methods outside of classes
Hi, I'm working on a bot written in python. It will consist of a mostly empty class that will then call a loader which in turn defines functions and adds them to the class. At the moment, I do this by using execfile(file,globals()) and calling a load(bot) method defined in every "module" which takes the functions defined in that perticular module and does bot.function=function. The problem with that is when I call bot.function() self doesn't get passed as an argument to the function. Is there anything I can do to sort this besides calling bot.function(bot, ...) everytime? -- Lord Landon rules over all! -- http://mail.python.org/mailman/listinfo/python-list
Re: scope of variables
On Thu, 04 May 2006 07:02:43 +1000, Gary Wessle wrote: > b = 3 > def adding(a) > print a + b > > it seams not to see the up-level scope where b is defined. Assuming you put a ':' after the "def adding(a)", this should work in recent versions of Python. In Python 2.0 and older, this will not work. In Python 2.1, it will only work if you do this: from __future__ import nested_scopes When you first start Python interactively, it should print version information. Here's what my Python prints when I start it: Python 2.4.3 (#2, Apr 27 2006, 14:43:58) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. As you can see, I'm running Python 2.4.3. Make sure you aren't running an old version of Python, and that code should do what you expect. -- Steve R. Hastings"Vita est" [EMAIL PROTECTED]http://www.blarg.net/~steveha -- http://mail.python.org/mailman/listinfo/python-list
Re: Because of multithreading semantics, this is not reliable.
Tim and Grant >>> if q.empty(): return >>> Of course you explanation is understood and ideally should be included as a note in the Python documentation. And the "not reliable" should be removed from the documentation! Anyway, many thanks for your explanations (I feel "safer" now). Olaf -- http://mail.python.org/mailman/listinfo/python-list
Re: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled
Serge > I got bored and tried to stop it with ctrl-c ... Yes, you have to use the ctrl-break key to stop the first program. And neither program every hangs on a single core CPU. It also does not hang on a hyper-threading CPU if hyper-threading is turned off in the BIOS. Olaf -- http://mail.python.org/mailman/listinfo/python-list
Re: scope of variables
In <[EMAIL PROTECTED]>, Gary Wessle wrote: > is the code below correct? No... > b = 3 > def adding(a) ...a colon is missing at the end of the above line. > print a + b > > it seams not to see the up-level scope where b is defined. It does. And you could easily find out yourself by just trying that code. Running this:: b = 3 def adding(a): print a + b adding(5) Puts out 8 as expected. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: list*list
Ziga Seilnach: >c = map(operator.mul, a, b) Usually I like map a lot, but this time for me the l.c. version is a bit simpler to understand (even if it's longer, and maybe slower too): >>> from operator import mul >>> from itertools import izip >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> map(mul, a, b) [4, 10, 18] >>> [arow * brow for arow, brow in izip(a, b)] [4, 10, 18] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: This coding style bad practise?
Martin P. Hellwig wrote: > Hi all, > > I created a class which creates a relative unique id string, now my > program just works fine and as expected but somehow I get the feeling > that I misused the __repr__ since I guess people expect to 'execute' a > function in an instance instead of using it's representation string of > the instance itself, could you elaborate whether you find this bad > practice and if yes what would have been a better way to do it? > > TIA > Rather than comment on the style of using a class, I'll just suggest an alternative. You can use a generator function, which yields the next id when called; at least that's how I'd implement an IDgenerator. Cheers, Keir. -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question: "TypeError" wrong number of args
Marc 'BlackJack' Rintsch a écrit : (snip) > > Okay, let's start with writing a simple text processor for this little > mess:: > > def b(c): > def d(r, *s, **t): > print '***' > c(r, *s, **t) > return d > > What a nice, readable, highly pythonic code... (snip) -- http://mail.python.org/mailman/listinfo/python-list
Re: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled
[EMAIL PROTECTED] wrote: > > What do you mean "stop responding"? > > Both threads print their thread numbers (either 1 or 2) approximately > every 10 seconds. However, after a while (minutes to hours) both > programs (see above) hang! > > Pressing ctrl-c (after the printing stops) causes the threads to "wake > up" from their sleep statement. And since the sleep took more than 1 > seconds the thread number and the duration of the sleep is printed to > the screen. > > Do you have a hyper-threading/dual/multi core CPU? Did you try this? I don't have such CPU but I run the first program anyway. It printed C:\py>th.py thread 1 started sleep time: 0.01 3.63174649292e-006 8.43682646817e-005 0.000164825417756 thread 2 started sleep time: 0.003 0.000675225482568 0.000753447714724 0.00082943502596 1 1 1 2 1 1 1 2 1 1 1 2 1 1 1 1 2 1 1 1 2 1 I got bored and tried to stop it with ctrl-c but it didn't respond and kept running and printing the numbers. I had to kill it from task manager. -- http://mail.python.org/mailman/listinfo/python-list
Re: Because of multithreading semantics, this is not reliable.
[EMAIL PROTECTED] > Because of multithreading semantics, this is not reliable. This > sentence is found in the Python documentation for "7.8.1 Queue > Objects". > > This scares me! Why would Queue.qsize(), Queue.empty( ), and a > Queue.full() not be reliable? Because they may not be telling the truth at the instant the _caller_ tries to use the result. I'm not sure why, but people write code like if q.empty(): return in a thread, and then complain that "it's a bug" if some other thread of theirs happens to sneak in and add another item to the queue _between_ the time q.empty() correctly determined that q was empty, and the time the code generated for "if q.empty()" tests the result. There's no mutex to stop other threads from running between those times. The docs could be clearer about this, and "not reliable" had a stronger meaning in earlier versions of Python. > Looking at the source code of Queue.py, all 3 calls use a mutex (based > on thread.allocate_lock()). Does this mean that the > thread.allocate_lock() mechanism is not reliable (scary indeed) No. > or does this have to do with other implementation details? It just has to do with the way threads work, and with trying to disabuse newbies of faulty common beliefs. It's good to scare threading newbies away from these methods, because they _don't_ do what newbies typically assume they do. That puts them in the "attractive nuisance" category for many people. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled
Tim > Do you want someone running this test to hit the ENTER key, or not? The purpose of the "sys.stdin.read(1)" statement is simply to prevent the main thread from exiting and thus ending the test. And yes, I also get an exception when I press the enter key. Olaf -- http://mail.python.org/mailman/listinfo/python-list
Re: This coding style bad practise?
Martin P. Hellwig a écrit : > Hi all, > > I created a class which creates a relative unique id string, now my > program just works fine and as expected but somehow I get the feeling > that I misused the __repr__ since I guess people expect to 'execute' a > function in an instance instead of using it's representation string of > the instance itself, could you elaborate whether you find this bad > practice and if yes what would have been a better way to do it? Why not just use the call operator instead ? ie: >>> id = IDGenerator(...) >>> id() 01_20060424_151903_1 >>> id() 01_20060424_151905_2 -- http://mail.python.org/mailman/listinfo/python-list
Re: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled
Time >>> 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 >>> This is exactly what you should see. The problem I see is that after a while (minutes to hours) the printing of 1s and 2s stops! If you press ctrl-c at that point the threads will print how many seconds they were stuck in the sleep statements (proving that the threads were stuck in the sleep statement until you pressed ctrl-c). Could you please try again (perhaps let it run overnight)? Many, many thanks. Olaf -- http://mail.python.org/mailman/listinfo/python-list
scope of variables
Hi is the code below correct? b = 3 def adding(a) print a + b it seams not to see the up-level scope where b is defined. thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Possibly dumb question about dicts and __hash__()
Beautiful! But how come my attempt didn't work? I've seen docs that explain how __hash__() methods are used to put objects in dict buckets: http://docs.python.org/ref/customization.html#l2h-195 But if it's really hash(str(o)) that's used for dict keys, what good are __hash__() methods? Or am I reading the docs wrong? /Joel -- http://mail.python.org/mailman/listinfo/python-list
Re: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled
> What do you mean "stop responding"? Both threads print their thread numbers (either 1 or 2) approximately every 10 seconds. However, after a while (minutes to hours) both programs (see above) hang! Pressing ctrl-c (after the printing stops) causes the threads to "wake up" from their sleep statement. And since the sleep took more than 1 seconds the thread number and the duration of the sleep is printed to the screen. Do you have a hyper-threading/dual/multi core CPU? Did you try this? Olaf -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question: "TypeError" wrong number of args
In <[EMAIL PROTECTED]>, Edward Elliott wrote: > I can prove that assertion too: make a simple text processor that reads > Python source code and outputs the same source code with only one change: > insert the string 'self" as the first parameter of every "def somemethod". > Next run the output source code with the normal Python interpreter. > Everything functions *exactly* as before because the code is *exactly* the > same as what you would have written if you'd put the 'self's in there > manually. Now make the Python interpreter invoke this text processor as > the first step in processing source code. Voila, python + implicit self. Okay, let's start with writing a simple text processor for this little mess:: def b(c): def d(r, *s, **t): print '***' c(r, *s, **t) return d class A: @b def a(x, y, z): print y, z x.e(23) def e(u, v): print u, v class B: def e(v, w): print 'spam', v, w A.e = e x = A() x.a('answer', 42) e('eric', 'viking') A.a(x, 'ham', 'eggs') Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled
[EMAIL PROTECTED] > Below are 2 files that isolate the problem. Note, both programs hang > (stop responding) What does "stop responding" mean? > with hyper-threading turned on (a BIOS setting), but > work as expected with hyper-threading turned off. > > Note, the Windows task manager shows 2 CPUs on the Performance tab with > hyper-threading is turned on. > > Both Python 2.3.5 and 2.4.3 (downloaded from python.org) have this > problem. > The operating system is MS Windows XP Professional. > > winmsd.exe shows: > 2CPUs: x86 Family 15 Model 4 Stepping 1 GenuineIntel ~3000 MHz > Version: 5.1.2600 Service Pack 2 Build 2600 > > Could someone with a hyper-threading (or dual/multicore) CPU please > confirm this bug? I don't see anything unexpected (to me) on a WinXP Pro SP2 box with HT enabled, using 2.4.3, but I'm not sure what "not responding" means to you. > # testsleep.py > import threading > import time > > class Task(threading.Thread): > def __init__(self, n, t): > threading.Thread.__init__(self) > self.n = n > self.t = t > def run(self): > print 'thread %d started' % self.n > print 'sleep time:', self.t > print time.clock() > print time.clock() > print time.clock() > print > count = 0 > printCount = int(10 / self.t) > while True: > start = time.clock() > time.sleep(self.t) > stop = time.clock() > if stop - start > 1.0: > print 'thread', self.n, stop - start You don't _expect_ this print to execute, do you? It should trigger very rarely (if ever). > count += 1 > if count > printCount: > count = 0 > print self.n, > > def test(): > thread1 = Task(1, 0.01) > thread2 = Task(2, 0.003) > thread1.start() > thread2.start() > > test() This is what happened when I ran it, until I got tired of watching it and killed the job: C:\Python24>python test1.py thread 1 started sleep time: 0.01 7.8499538238e-007 4.42770924877e-005 8.62618455186e-005 thread 2 started sleep time: 0.003 0.000479349533238 0.000521904282916 0.000563649037359 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 > # testsleep2.py > import thread > import time > import sys > > def run(n, t): > print 'thread %d started' % n > print 'sleep time:', t > print time.clock() > print time.clock() > print time.clock() > print > count = 0 > printCount = int(10 / t) > while True: > start = time.clock() > time.sleep(t) > stop = time.clock() > if stop - start > 1.0: > print 'thread', n, stop - start See above. > count += 1 > if count > printCount: > count = 0 > print n, > > def test(): > thread.start_new_thread(run, (1, 0.01)) > thread.start_new_thread(run, (2, 0.003)) > > # Wait until the user presses the enter key. > sys.stdin.read(1) Do you want someone running this test to hit the ENTER key, or not? > > test() Works much the same for me, except I got bored quicker ;-): C:\Python24>python test2..py thread 1 started sleep time: 0.01 1.14999323533e-006 8.01271757225e-005 thread 2 started sleep time: 0.003 0.000395865318439 0.000474259857295 0.000559831706872 0.00071061346698 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 At that point I hit the ENTER key, and saw: Unhandled exception in thread started by Error in sys.excepthook: Original exception was: Unhandled exception in thread started by Error in sys.excepthook: Original exception was: That's unfortunate, but not unexpected either. The interpreter doesn't wait for a `thread` module thread to finish before tearing itself down, so the threads keep running after Python has torn so much of itself down that weird execptions occur -- and Python is _so_ torn down by that point it can't even display a useful error message. The interpreter does (by default) wait for `threading` module threads to exit before tearing itself down, so those kinds of useless exit messages weren't expected in the first test. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python & SSL
John J. Lee wrote: > James Stroud <[EMAIL PROTECTED]> writes: > > >>I have been trying to make an https client with python, but it seems > > > What exactly do you mean by "make an https client"? Something that can communicate with an https server. Fetch web pages, send POST and GET information securely. >>that, to do this, one needs to have the socket module compiled with ssl. >>This is not the default. So I have a couple of questions. >> >> 1. Where do I specify to compile socket with ssl? I found no >> obvious option in configure or setup.py or several other >> files I checked. > > > What OS are you on? Linux FC 4 with my self-compiled versions of just about everything. > >> 2. Is there a way to do this without re-compiling all of python? > > > Are you sure it's NOT compiled in? But, if it's not compiled, it's > not compiled. Its not compiled by default. I think I read this somewhere. I was thinking of compiling just the socket module rather than installing over my old version. > >>Also, I have done numerous combinations of searches with ssl, https, & >>python as terms, but I haven't found a page outlining the steps to make >>a certificate and key that python understands. Has anyone been >>successful at this? Did you use openssl? I want to make sure I am doing >>this part correctly. > > > Since you say "make a certificate", and mention "https client", it > sounds like you want to authenticate yourself to an HTTP server using > an SSL certificate? If so, I don't believe the issue Benji raised is > relevant (that issue is relevant for fetching HTTPS URLs rather than > authenticating yourself to a server using an SSL certificate, I > think). > > urllib claims to have support for this in the form of the key_file and > cert_file arguments to Urlopener constructor (UNTESTED): > > import urllib > opener = urllib.URLopener(key_file="/path/to/my_key_file", > cert_file="/path/to/my_cert_file") > response = opener.open(url) At this point, authenticating is not an issue, though it would be nice to know how to do. Mainly, I want to establish a secure connection for 2-way communication via https. At any rate, I was able to make M2Crypto do what I wanted last night, so I think I'll bypass the standard library route for now. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled
[EMAIL PROTECTED] wrote: > Below are 2 files that isolate the problem. Note, both programs hang > (stop responding) with hyper-threading turned on (a BIOS setting), but > work as expected with hyper-threading turned off. What do you mean "stop responding"? Not responding when you press ctrl-c? They stop printing? If you mean stop printing, try sys.stdout.flush() after each print -- http://mail.python.org/mailman/listinfo/python-list
Re: SciTE: Printing in Black & White
Alexander Anderson: > ...I like to study large files of (hobby) code on paper. I have a > black and white bubble-jet printer. However, my (Win NT4) screen > syntax-highlighting setup has a couple of problems when it comes to > doing print-outs. > > The _chief_ problem is that my on-screen background colour is not > bright white -- it's an off-white cream, which is so much easier on my > eyes: There are several properties that tweak printing listed in the documentation. Perhaps you want print.colour.mode=2. Neil [ copied from the SciTE-interest mailing list, http://mailman.lyra.org/mailman/listinfo/scite-interest ] -- http://mail.python.org/mailman/listinfo/python-list
Re: Because of multithreading semantics, this is not reliable.
On 2006-05-03, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Because of multithreading semantics, this is not reliable. > This sentence is found in the Python documentation for "7.8.1 > Queue Objects". > > This scares me! Why would Queue.qsize(), Queue.empty( ), and a > Queue.full() not be reliable? IIRC from the last time this question came up, what the doc means by "not reliable" is that the result you get is accurate at the time of the call (for the period the call is inside in the mutex-protected region), but the saved result may not be correct at some point in the future because some other thread may have done an operation on the queue. I've argued that the "not reliable" phrase is simply wrong: IMO the calls _are_ reliable: they always return the correct value at the time the call was made (for my previous definition of "at the time the call was made"). That's "reliable" in my book. I've no idea why anybody would ever expect Queue.qsize() to return the size of the queue as it was going to be at some undetermined point in the future. If we were to use the "not reliable" semantics that are used in the Queue docs, pretty much everything is "not reliable" in a multi-threading environment. For example binding a global name to an object is "not reliable" in a multi-threaded environment because another thread can re-bind it later to a different object. I think describing that problem as "global name binding is not reliable in a multi-threaded environment" is very misleading. > Looking at the source code of Queue.py, all 3 calls use a > mutex (based on thread.allocate_lock()). Does this mean that > the thread.allocate_lock() mechanism is not reliable (scary > indeed) or does this have to do with other implementation > details? IMO, it has to do with a poor choice of language. > Many thanks for explaining this mystery. No problem. -- Grant Edwards grante Yow! Mr and Mrs PED, can I at borrow 26.7% of the RAYON visi.comTEXTILE production of the INDONESIAN archipelago? -- http://mail.python.org/mailman/listinfo/python-list
Re: Possibly dumb question about dicts and __hash__()
Actually, come to think of it, __str__ works just as well. >>> class NamedThing(object): def __init__(self, name): self.name = name def __str__(self): return self.name >>> d = {} >>> d[a] = 1 >>> d[b] = 50 >>> d {<__main__.NamedThing object at 0x00C528D0>: 1, <__main__.NamedThing object at 0x00C529B0>: 50} >>> d[a] 1 >>> d[b] 50 This is what you should use, instead of my first answer. From the docs for __repr__: "If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form "<...some useful description...>" should be returned. ... This is typically used for debugging, so it is important that the representation is information-rich and unambiguous." [EMAIL PROTECTED] wrote: > Use __repr__. Behold: > > >>> class NamedThing(object): > def __init__(self, name): > self.name = name > def __repr__(self): > return self.name > > >>> a = NamedThing("Delaware") > >>> b = NamedThing("Hawaii") > >>> d = {} > >>> d[a] = 1 > >>> d[b] = 50 > >>> print d > {Delaware: 1, Hawaii: 50} > >>> d[a] > 1 > >>> d[b] > 50 > > Although this is a bit illegal, because repr is not supposed to be used > this way. > > Joel Hedlund wrote: > > Hi! > > > > There's one thing about dictionaries and __hash__() methods that puzzle me. > > I > > have a class with several data members, one of which is 'name' (a str). I > > would > > like to store several of these objects in a dict for quick access > > ({name:object} style). Now, I was thinking that given a list of objects I > > might > > do something like > > > > d = {} > > for o in objects: > > d[o] = o > > > > and still be able to retrieve the data like so: > > > > d[name] > > > > if I just defined a __hash__ method like so: > > > > def __hash__(self): > > return self.name.__hash__() > > > > but this fails miserably. Feel free to laugh if you feel like it. I cooked > > up a > > little example with sample output below if you care to take the time. > > > > Code: > > --- > > class NamedThing(object): > > def __init__(self, name): > > self.name = name > > def __hash__(self): > > return self.name.__hash__() > > def __repr__(self): > > return '' > > name = 'moo' > > o = NamedThing(name) > > print "This output puzzles me:" > > d = {} > > d[o] = o > > d[name] = o > > print d > > print > > print "If I wrap all keys in hash() calls I'm fine:" > > d = {} > > d[hash(o)] = o > > d[hash(name)] = o > > print d > > print > > print "But how come the first method didn't work?" > > --- > > > > Output: > > --- > > This output puzzles me: > > {'moo': , : } > > > > If I wrap all keys in hash() calls I'm fine: > > {2038943316: } > > > > But how come the first method didn't work? > > --- > > > > I'd be grateful if anyone can shed a litte light on this, or point me to > > some > > docs I might have missed. > > > > Also: > > Am I in fact abusing the __hash__() method? If so - what's the intended use > > of > > the __hash__() method? > > > > Is there a better way of implementing this? > > > > I realise I could just write > > > > d[o.name] = o > > > > but this problem seems to pop up every now and then and I'm curious if > > there's > > some neat syntactic trick that I could legally apply here. > > > > Thanks for your time! > > /Joel Hedlund -- http://mail.python.org/mailman/listinfo/python-list
Re: Possibly dumb question about dicts and __hash__()
Joel Hedlund a écrit : (snip) > How illegal is it? If I document it and put it in an opensource project, > will people throw tomatoes? Don't know, but they'll sure do if you insist on top-posting !-) -- http://mail.python.org/mailman/listinfo/python-list
This coding style bad practise?
Hi all, I created a class which creates a relative unique id string, now my program just works fine and as expected but somehow I get the feeling that I misused the __repr__ since I guess people expect to 'execute' a function in an instance instead of using it's representation string of the instance itself, could you elaborate whether you find this bad practice and if yes what would have been a better way to do it? TIA - script - > import string > import time > > class IDGenerator(object): > """(serverID,subversion_length) > Create an ID from the server name, datetimestamp and version number. > Calling the instance returns the ID using the __repr__ class function > > Example usage: > >>> id = idgen('01',4) > >>> id > 01_20060424_151903_1 > >>> id > 01_20060424_151905_2 > >>> id > 01_20060424_151905_3 > >>> id > 01_20060424_151906_4 > >>> id > 01_20060424_151907_1 > >>> > >>> id = idgen(04,100) > >>> id > 4_20060424_152043_001 > > """ > > def __init__(self,serverID,subversion_length): > self.ID = str(serverID) > self.length = int(subversion_length) > fill_length = len(str(self.length)) > > def fill(number): > return(string.zfill(number,fill_length)) > self.fill = fill > > > def __repr__(self): > # If the subversion length has been reached or the generator has not > # been defined, (re)define it, otherwise return the next value of the > # subversion. > try: > return_value = self.range_gen.next() > > except: > self.range_gen = ( number for number in range(1,self.length+1) ) > return_value = self.range_gen.next() > > # Create the version stamp. > return_value = self.ID +\ >time.strftime("_%Y%m%d_%H%M%S_",time.gmtime())+\ >self.fill(return_value) > > # And return it. > return(return_value) - script - -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question: "TypeError" wrong number of args
Edward Elliott a écrit : > bruno at modulix wrote: > >>Technically, they are still function objects. They are later wrapped >>into method descriptor objects (at lookup time IIRC, but ask a guru or >>read the doc to know for sure). And don't forget the case of nested >>functions... > > > I don't see how nested functions change anything. If they're nested in a > method, they can access self, but the name mapping is done at runtime. > Unless you mean a nested fucntion which is dynamically added as a method, > but that's the same case as the next one. > Nope. I just wanted to point out that just checking for def statements in the scope of a class statement is not enough to decide if it has to be treated as a method. (snip) > >>>Well I'm assuming the rules for when to put 'self' in the parameter list >>>are simple enough to be automated. >> >>They are still complex enough to require a real parser. And anyway, >>since this is a syntax change, this should be handled by the parser IMHO. > > I agree, but it's good to keep options in mind. regexp are not an option !-) > >>Honestly, I don't think it has much chance. I barely even notice typing >>'self' or 'cls', and I guess it's the same for most Python programmers >>- those who can't stand it probably use another language... And FWIW, I >>still prefer to keep consistency in functions definitions. > > I have no doubt that's true for a lot of people. Hell I probably prefer the > current approach because 1) it's not a big deal in practice, and 2) I can > use the shorter 'me' or 's' in place of self in my own code, which I > couldn't do under the change Now *this* would be a +1 !-) > (well, I could add 'me = self' as the first > statement of any method, but that's clumsy). My objections stem more from > an elegance standpoint. Of course elegance is in the eye of the beholder. Indeed... -- http://mail.python.org/mailman/listinfo/python-list
Re: list*list
Very useful comments... Thanks to all! Once again this community has demonstrated why Python is THE language. jab -- http://mail.python.org/mailman/listinfo/python-list
__init__.py, __path__ and packaging
Hi everybody, I'm trying to fix the packaging of a very simple package, but some problem show me that I have not well understood the whole mechanism The structure of my package (some debug functions) is as follows: python/ `-- dbg/ |-- __init__.py `-- lib |-- __init__.py |-- debug.py `-- gtk_dbg.py my sys.path includes 'python' and I wanted that the content of debug.py was simply included by: 'import dbg', so I wrote dbg/__init__.py as follows: import os Dir = os.path.dirname(__file__) __path__ = [os.path.join(Dir, 'lib')] from debug import * It seems to work: python$ python -c 'import dbg; print dir(dbg)' ['DBG', 'Dir', '__builtins__', '__doc__', '__file__', '__name__', \ '__path__', 'caller', 'debug', 'dshow', 'os', 're', 'show_caller', \ 'sql_debug', 'sys'] BUT, if I set some variables they are not correctly seen: import dbg dbg.DBG = 1 function test included in debug.py raises NameError: def test(): print DBG NameError: global name 'DBG' is not defined` What's happening? DBG seems to be set, as shown by dir(dbg)... any hints? I'd also accept a hint for a different approch, if it's the case, but I'd really would also understant this issue Thanks in advance sandro *:-) -- Sandro Dentella *:-) http://www.tksql.orgTkSQL Home page - My GPL work -- http://mail.python.org/mailman/listinfo/python-list
Re: Possibly dumb question about dicts and __hash__()
Hi! Thanks for the quick response! > Although this is a bit illegal, because repr is not supposed to be used > this way. How illegal is it? If I document it and put it in an opensource project, will people throw tomatoes? /Joel [EMAIL PROTECTED] wrote: > Use __repr__. Behold: > > class NamedThing(object): > > def __init__(self, name): > self.name = name > def __repr__(self): > return self.name > > a = NamedThing("Delaware") b = NamedThing("Hawaii") d = {} d[a] = 1 d[b] = 50 print d > > {Delaware: 1, Hawaii: 50} > d[a] > > 1 > d[b] > > 50 > > Although this is a bit illegal, because repr is not supposed to be used > this way. > > Joel Hedlund wrote: > >>Hi! >> >>There's one thing about dictionaries and __hash__() methods that puzzle me. I >>have a class with several data members, one of which is 'name' (a str). I >>would >>like to store several of these objects in a dict for quick access >>({name:object} style). Now, I was thinking that given a list of objects I >>might >>do something like >> >>d = {} >>for o in objects: >> d[o] = o >> >>and still be able to retrieve the data like so: >> >>d[name] >> >>if I just defined a __hash__ method like so: >> >>def __hash__(self): >> return self.name.__hash__() >> >>but this fails miserably. Feel free to laugh if you feel like it. I cooked up >>a >>little example with sample output below if you care to take the time. >> >>Code: >>--- >>class NamedThing(object): >> def __init__(self, name): >> self.name = name >> def __hash__(self): >> return self.name.__hash__() >> def __repr__(self): >> return '' >>name = 'moo' >>o = NamedThing(name) >>print "This output puzzles me:" >>d = {} >>d[o] = o >>d[name] = o >>print d >>print >>print "If I wrap all keys in hash() calls I'm fine:" >>d = {} >>d[hash(o)] = o >>d[hash(name)] = o >>print d >>print >>print "But how come the first method didn't work?" >>--- >> >>Output: >>--- >>This output puzzles me: >>{'moo': , : } >> >>If I wrap all keys in hash() calls I'm fine: >>{2038943316: } >> >>But how come the first method didn't work? >>--- >> >>I'd be grateful if anyone can shed a litte light on this, or point me to some >>docs I might have missed. >> >>Also: >>Am I in fact abusing the __hash__() method? If so - what's the intended use of >>the __hash__() method? >> >>Is there a better way of implementing this? >> >>I realise I could just write >> >>d[o.name] = o >> >>but this problem seems to pop up every now and then and I'm curious if there's >>some neat syntactic trick that I could legally apply here. >> >>Thanks for your time! >>/Joel Hedlund > > -- http://mail.python.org/mailman/listinfo/python-list
Because of multithreading semantics, this is not reliable.
Because of multithreading semantics, this is not reliable. This sentence is found in the Python documentation for "7.8.1 Queue Objects". This scares me! Why would Queue.qsize(), Queue.empty( ), and a Queue.full() not be reliable? Looking at the source code of Queue.py, all 3 calls use a mutex (based on thread.allocate_lock()). Does this mean that the thread.allocate_lock() mechanism is not reliable (scary indeed) or does this have to do with other implementation details? Many thanks for explaining this mystery. Olaf -- http://mail.python.org/mailman/listinfo/python-list
Re: Possibly dumb question about dicts and __hash__()
Use __repr__. Behold: >>> class NamedThing(object): def __init__(self, name): self.name = name def __repr__(self): return self.name >>> a = NamedThing("Delaware") >>> b = NamedThing("Hawaii") >>> d = {} >>> d[a] = 1 >>> d[b] = 50 >>> print d {Delaware: 1, Hawaii: 50} >>> d[a] 1 >>> d[b] 50 Although this is a bit illegal, because repr is not supposed to be used this way. Joel Hedlund wrote: > Hi! > > There's one thing about dictionaries and __hash__() methods that puzzle me. I > have a class with several data members, one of which is 'name' (a str). I > would > like to store several of these objects in a dict for quick access > ({name:object} style). Now, I was thinking that given a list of objects I > might > do something like > > d = {} > for o in objects: > d[o] = o > > and still be able to retrieve the data like so: > > d[name] > > if I just defined a __hash__ method like so: > > def __hash__(self): > return self.name.__hash__() > > but this fails miserably. Feel free to laugh if you feel like it. I cooked up > a > little example with sample output below if you care to take the time. > > Code: > --- > class NamedThing(object): > def __init__(self, name): > self.name = name > def __hash__(self): > return self.name.__hash__() > def __repr__(self): > return '' > name = 'moo' > o = NamedThing(name) > print "This output puzzles me:" > d = {} > d[o] = o > d[name] = o > print d > print > print "If I wrap all keys in hash() calls I'm fine:" > d = {} > d[hash(o)] = o > d[hash(name)] = o > print d > print > print "But how come the first method didn't work?" > --- > > Output: > --- > This output puzzles me: > {'moo': , : } > > If I wrap all keys in hash() calls I'm fine: > {2038943316: } > > But how come the first method didn't work? > --- > > I'd be grateful if anyone can shed a litte light on this, or point me to some > docs I might have missed. > > Also: > Am I in fact abusing the __hash__() method? If so - what's the intended use of > the __hash__() method? > > Is there a better way of implementing this? > > I realise I could just write > > d[o.name] = o > > but this problem seems to pop up every now and then and I'm curious if there's > some neat syntactic trick that I could legally apply here. > > Thanks for your time! > /Joel Hedlund -- http://mail.python.org/mailman/listinfo/python-list
OT: SourceForge Tracker offline?
Is anybody else also experiencing the SourceForge tracker to be offline? I can't log in at the moment, and can't view any tracker items... --- Heiko. -- http://mail.python.org/mailman/listinfo/python-list
Re: python strings
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 [EMAIL PROTECTED] wrote: > Is it possible for python strings to contain a zero byte? Yes. Here's how to produce one: [EMAIL PROTECTED]:~$ python Python 2.4.2 (#2, Sep 30 2005, 21:19:01) [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> s = "\x000" >>> s[0] == chr(0) True >>> - -- Gerhard -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFEWQjRdIO4ozGCH14RAsf4AJ4xdbT/FQTSzfciijgVBEfMyTH8SQCeJP39 xzJxWxlAnRgKimsKSKWhSQ0= =Dd3B -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question: "TypeError" wrong number of args
bruno at modulix wrote: > Technically, they are still function objects. They are later wrapped > into method descriptor objects (at lookup time IIRC, but ask a guru or > read the doc to know for sure). And don't forget the case of nested > functions... I don't see how nested functions change anything. If they're nested in a method, they can access self, but the name mapping is done at runtime. Unless you mean a nested fucntion which is dynamically added as a method, but that's the same case as the next one. >> If you're declaring >> methods outside the class and adding them dynamically, I think you would >> need to declare 'self' explicitly. > > Of course. Virtually *any* function can be set as a method[1] outside > the class statement scope, either directly on the class object or - with > manual wrapping - on an individual instance. And it's important to keep > this feature. I wouldn't dream otherwise. >> Well I'm assuming the rules for when to put 'self' in the parameter list >> are simple enough to be automated. > > They are still complex enough to require a real parser. And anyway, > since this is a syntax change, this should be handled by the parser IMHO. I agree, but it's good to keep options in mind. > Honestly, I don't think it has much chance. I barely even notice typing > 'self' or 'cls', and I guess it's the same for most Python programmers > - those who can't stand it probably use another language... And FWIW, I > still prefer to keep consistency in functions definitions. I have no doubt that's true for a lot of people. Hell I probably prefer the current approach because 1) it's not a big deal in practice, and 2) I can use the shorter 'me' or 's' in place of self in my own code, which I couldn't do under the change (well, I could add 'me = self' as the first statement of any method, but that's clumsy). My objections stem more from an elegance standpoint. Of course elegance is in the eye of the beholder. -- http://mail.python.org/mailman/listinfo/python-list
Re: python strings
On 2006-05-03, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Is it possible for python strings to contain a zero byte? Yes. -- Grant Edwards grante Yow! Actually, what at I'd like is a little toy visi.comspaceship!! -- http://mail.python.org/mailman/listinfo/python-list
Possibly dumb question about dicts and __hash__()
Hi! There's one thing about dictionaries and __hash__() methods that puzzle me. I have a class with several data members, one of which is 'name' (a str). I would like to store several of these objects in a dict for quick access ({name:object} style). Now, I was thinking that given a list of objects I might do something like d = {} for o in objects: d[o] = o and still be able to retrieve the data like so: d[name] if I just defined a __hash__ method like so: def __hash__(self): return self.name.__hash__() but this fails miserably. Feel free to laugh if you feel like it. I cooked up a little example with sample output below if you care to take the time. Code: --- class NamedThing(object): def __init__(self, name): self.name = name def __hash__(self): return self.name.__hash__() def __repr__(self): return '' name = 'moo' o = NamedThing(name) print "This output puzzles me:" d = {} d[o] = o d[name] = o print d print print "If I wrap all keys in hash() calls I'm fine:" d = {} d[hash(o)] = o d[hash(name)] = o print d print print "But how come the first method didn't work?" --- Output: --- This output puzzles me: {'moo': , : } If I wrap all keys in hash() calls I'm fine: {2038943316: } But how come the first method didn't work? --- I'd be grateful if anyone can shed a litte light on this, or point me to some docs I might have missed. Also: Am I in fact abusing the __hash__() method? If so - what's the intended use of the __hash__() method? Is there a better way of implementing this? I realise I could just write d[o.name] = o but this problem seems to pop up every now and then and I'm curious if there's some neat syntactic trick that I could legally apply here. Thanks for your time! /Joel Hedlund -- http://mail.python.org/mailman/listinfo/python-list
Ann: pyDia2Code
Hello,This is a GUI program for Dia2Code lib under GPL licence: "Dia2Code basically reads a Dia diagram file that contains an UML class diagram and creates files in the language of choice that contain the bare bones of the classes represented in the diagram...""Generates code for: Ada, C, C++, Java, PHP, Python, shapefile, SQL and C#"Build in Python with the same function like gDia2Code and Kaptain (obsolete) This is a Beta stage, please send me any comments or suggest.I search help for i18n, for translate into english the interface, right now its only available in spanish.The website: http://sourceforge.net/projects/pydia2code/Thanks in advance!!-- Saludos / Best regardsMario LacunzaDesarrollador de Sistemas - WebmasterTeléfono: 51-1-242-0058Celular: 51-1-9310-0386 (Tim) Email: [EMAIL PROTECTED]Email: [EMAIL PROTECTED]Messenger MSN: [EMAIL PROTECTED] Website: http://www.lacunza.tkLima - Peru -- http://mail.python.org/mailman/listinfo/python-list
python strings
Is it possible for python strings to contain a zero byte? -- http://mail.python.org/mailman/listinfo/python-list
python modules for openAFS client functionalities
Did anybody try to provide python modules for the openAFS (http://www.openafs.org/) client functionalities (C API)? I think that there are already bindings available for Perl and Java. What could be the best aproach to provide bindings for Python? Using Swig? -- http://mail.python.org/mailman/listinfo/python-list
Re: Recommended data structure for newbie
"Paul McGuire" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > "manstey" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > Hi, > > > > I have a text file with about 450,000 lines. Each line has 4-5 fields, > > separated by various delimiters (spaces, @, etc). > > > > I want to load in the text file and then run routines on it to produce > > 2-3 additional fields. > > > > > > Matthew - > > If you find re's to be a bit cryptic, here is a pyparsing version that may > be a bit more readable, and will easily scan through your input file: > Lest I be accused of pushing pyparsing where it isn't appropriate, here is a non-pyparsing version of the same program. The biggest hangup with your sample data is that you can't predict what the separator is going to be - sometimes it's '[', sometimes it's '^'. If the separator character were more predictable, you could use simple split() calls, as in: data = "blah blah blah^more blah".split("^") elements = data[0].split() + [data[1]] print elements ['blah', 'blah', 'blah', 'more blah'] Note that this also discards the separator. Since you had something which goes beyond simple string split()'s I thought you might find pyparsing to be a simple alternative to re's. Here is a version that tries different separators, then builds the appropriate list of pieces, including the matching separator. I've also shown an example of a generator, since you are likely to want one, parsing 100's of thousands of lines as you are. -- Paul = data = """gee fre asd[234 ger dsf asd[243 gwer af as.:^25a""" # generator to process each line of data # call using processData(listOfLines) def processData(d): separators = "[^" #expand this string if need other separators for line in d: for s in separators: if s in line: parts = line.split(s) # return the first element of parts, split on whitespace # followed by the separator # followed by whatever was after the separator yield parts[0].split() + [ s, parts[1] ] break else: yield line # to call this for a text file, use something like # for lineParts in processData( file("xyzzy.txt").readlines() ) for lineParts in processData( data.split("\n") ): print lineParts print # rerun processData, augmenting extracted values with additional # computed values for lineParts in processData( data.split("\n") ): toks = lineParts tokens = toks[:] tokens.append( toks[0]+toks[1] ) tokens.append( toks[-1] + toks[-1][-1] ) #~ tokens.append( str( lineno(start, data) ) ) print tokens prints: ['gee', 'fre', 'asd', '[', '234'] ['ger', 'dsf', 'asd', '[', '243'] ['gwer', 'af', 'as.:', '^', '25a'] ['gee', 'fre', 'asd', '[', '234', 'geefre', '2344'] ['ger', 'dsf', 'asd', '[', '243', 'gerdsf', '2433'] ['gwer', 'af', 'as.:', '^', '25a', 'gweraf', '25aa'] -- http://mail.python.org/mailman/listinfo/python-list
Re: simultaneous assignment
On Wed, 03 May 2006 17:51:03 +, Edward Elliott wrote: > Steve R. Hastings wrote: >> You could also use a function that counts all different values in a list, >> reducing the list to a dictionary whose keys are the unique values from >> the list. > > Wouldn't reducing to a set instead of a dict make more sense if all you want > to do is count uniq elements? My apologies for not explaining tally() better. The dict has one key for each unique element, and the value associated with each key is a count of how many times that element appeared in the original list. lst = ['a', 'b', 'b', 'c', 'c', 'c'] d = iterwrap.tally(lst) print d # prints something like: {'a': 1, 'c': 3, 'b': 2} If you didn't care how many times the values appeared in the original list, and just just wanted the unique values, then a set would be perfect. If you happen to have tally(), it is an easy way to solve the original problem: figure out whether a list has exactly one true value in it. d = tally(bool(x) for x in lst) if d[True] == 1: print "and there was much rejoicing" -- Steve R. Hastings"Vita est" [EMAIL PROTECTED]http://www.blarg.net/~steveha -- http://mail.python.org/mailman/listinfo/python-list