[Tutor] Trying to get mp3play-0.1.15 module to work on Windows 7
I read Practical Programming, chapter 4 and I know how to write and use my own modules on IDLE for Python 3.2 but now I switched to version 2.7 and I don't know how to use a downloaded module such as mp3play-0.1.15 written by Michael Gundlach. I got Python 2.5, 2.7 and 3.2 on my computer at home and I prefer 2.7 for it's modern use (esp. with Csound). I'm using this computer in a coffee shop for internet. I can make small downloads onto my pen drive and transfer them to my laptop at home (well "so-called" home; It's a sober house and I've been sober for a month except for nicoteen, coffee and meds. All I need is one more month in Port Hardy, I believe.). The zip archive contains py files example.py and setup.py in the root directory of the zip including another folder called mp3play containing __init__.py and windows.py including matching pyc files for __init__ and windows. I could e-mail Gundlach himself but I thought I'd ask at least one of you first. Couldn't figure it out even with the documentation yesterday so please teach me as if I know nothing about it. I just want to see If I can play an mp3 in Python. even though I know the/some basics of IDLE, I still have a fair guessing time with the Wing 101 IDE (lite/light version). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How does formatted printing work?
I believe it's % string interpolation where % formats strings I'm reading Practical Programming and I'm stuck on page 35, question 6. b) where: "___" % 34.5 => "3.45e+01" On Sat, Jun 8, 2013 at 11:03 AM, Steven D'Aprano wrote: > On 09/06/13 01:58, Michael Sparks wrote: > >> You can explain it yourself or just drop me a link (or both). >> Right now I'm learning Python 2.x but I plan on learning Python 3.x as >> well. >> > > > Formatted printing? First you format something, then you print it. > > Other than that, you will need to explain your question in more detail. I > can't read your mind, so I don't know if you're having trouble > understanding "formatting" (which formatting? there are at least four > things which might be described as "formatting") or "printing" (which > printing? there are at least three things which might be described as > "printing"). > > So please don't assume that just because a question is clear and obvious > in your mind, it is necessarily clear and obvious to everyone else. > > > And for the record: > > 1) format() built-in function; > 2) str.format() method; > 3) % string interpolation; > 4) string templates; > > and > > 1) printing to an actual printer; > 2) print statement; > 3) the pprint ("pretty printing") module. > > > > -- > Steven > > __**_ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] How does formatted printing work?
You can explain it yourself or just drop me a link (or both). Right now I'm learning Python 2.x but I plan on learning Python 3.x as well. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] I think I found what I'm looking for.
speech.py is a Python module that provides a clean interface to Windows's voice recognition and text-to-speech capabilities. But it requires Windows XP or Vista, and Python 2.4 or 2.5. I use Windows 7. another one I found; Dragonfly is a speech recognition framework. It is a Python package which offers a high-level object model and allows its users to easily write scripts, macros, and programs which use speech recognition. I think that I'm satisfied with speech.py but it might not work on Windows 7. I'm very interested in Dragonfly but I don't think that I've ever used a framework or even know what a framework is. before you answer my question. I'm going to sourceforge to see if there is any speech recognition software out there. I'm in a coffee shop right now and I seem to have no internet access at home, the sober/recovery house, and I'm not sure if this computer will allow me to download software onto my pen drive. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Security [Was: Re: Decoding]
On Tuesday 14 August 2007 16:48, Eric Brunson wrote: ... > The only thing I can imagine is > that you're stuck in some DOS mindset that if you're able to type into > "the console" then you have ultimate access to the machine, which is not > the case when using a true multi-user operating system like *nix or VMS. > > But, most strange to me is why you're this fired up over such a simple > issue. It seems to me like just a misunderstanding. I'm not particularly fired up, text comes across much harsher than it looks. (Also people being particularly patronising, like you have above, is particularly irritating. Last time I used VMS was 12 years ago. I'm not missing your point or anyone else's, and I've not used DOS for 10 years so I'm hardly stuck in a DOS mindset (been developing under linux for over 10 years). Yes, there are a tiny set of scenarios where doing eval(raw_input(...)) could be a problem. The idea that its always a gaping security hole is completely bogus. The scenario's raised I've never once seen happen. Despite having seen a number of systems where you either ssh in or telnet into a specialise console (routers and other network appliances). What was irritating was I was saying: * Scenario A (and only that scenario) is hardly a risk considering in >99% of cases where the user can type something in response to eval(raw_input(...)) they have FAR more ways of causing problems. * The response I was getting a told was that this was wrong because *other scenarios* were dangerous. Yes, other scenarios are wrong. Denouncing a piece of code as a gaping security hole without discussing the context is irresponsible. That and being taught to suck eggs is irritating. I've been evaluating security of network systems for 10 years and coding for 25 years. After all piece of code is never a security risk by itself. It's how that code is deployed and used that _can_ be. Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Security [Was: Re: Decoding]
Tiger12506, You are COMPLETELY missing the point. The __following__ code > >> > foo = raw_input(...) > >> > x = eval(foo) ONLY works if the user has console access to the machine. If they have console access to the machine AND you're worried about them damaging it THEN an eval(raw_input( ...)) construct is the least of your worries. I'm not referring to text taken from * a network connection * a file * a web form * a P2P network I was JUST referring to the ONE context of immediately eval'ing user input. (an unlikely one at that) Where you say this: > But if you parse a text file that you haven't reviewed... that's possible. You're talking about a completely different context. Taking data from a network socket and using eval there is again a different context from above. Using it as a generic data conversion tool is again a different context. In those 3 contexts, yes, anyone would agree that using eval is extremely unwise at best. In the context of evaluating something which someone types at a console though? On Tuesday 14 August 2007 02:28, Tiger12506 wrote: > > On Monday 13 August 2007 22:39, Tiger12506 wrote: > >> > foo = raw_input(...) > >> > x = eval(foo) > > > > ... > > > >> Let your program run on your machine and I'll walk by, type in this > >> string, > >> and hit enter. We'll see how much of an exception it is when you can't > >> boot > >> your XP machine anymore. > >> ;-) > > > > Who cares? I don't run XP :-D > > I'm sure the equivalent can be done on different operating systems. Actually, decent operating systems prevent that sort of problem. A way to trash a linux machine would be to wipe /lib/libc.* on Mac OS X , wipe /usr/lib/libc.dylib . Let's see if it works on a linux machine: >>> file("/lib/libc.so.6","w").close() Traceback (most recent call last): File "", line 1, in IOError: [Errno 13] Permission denied: '/lib/libc.so.6' How about on a Mac OS X machine: >>> file("/usr/lib/libc.dylib", "w").close() Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 13] Permission denied: '/usr/lib/libc.dylib' Yes, of course if I was logged in as root on either it'd work. I could do far more damage far more easily though if I was. > > Seriously though, if typing: > >> "file('boot.ini','w').close()" > > > > Into an "eval prompt" worked then equally leaving a python interpreter > > open > > would be dumb, let alone a console. > > It does work. Try it with a simple file "temp.txt" for example. You can run > any function call if the string is parsed with eval. Notice I did not say > "type into an eval prompt type loop" I mean entirely if the string is > parsed with eval. I know just how powerful eval is. It's damn usefully powerful. You have changed the context here from the context I was talking about. I was stating that *IF* the following can cause damage: > >> > foo = raw_input(...) > >> > x = eval(foo) *AND* you are worried about that damage *BECAUSE* you believe the user is malicious, THEN the above code is the least of your worries. > > Quite frankly anyone getting worried about this: > >> > foo = raw_input(...) > >> > x = eval(foo) > > > > Is pretty over anxious IMO. "Gosh, the person at the console might be > > able to > > get python do something which they can do anyway". > > Again. Anytime the function is parsed with eval, you can run *any* python > function that is in the scope that the eval function is being executed > from. Security risks are never simple. Of course they can do it with a > python console window open. But if you are worried about security you don't > allow them access to the python console. You ecapsulate it. Yes, I know. I was talking solely about a context where they clearly DO have access to the console, and that worrying about this was the least of your worries. It's like saying "you left the door unlocked, you're going to get robbed", when you're missing that the people you're not trusting are inside the house watching the TV & drinking your coffee and you're leaving them there alone. Leaving the doors on a house unlocked is generally unwise when you go out (not least due to invalidating insurance). It's totally irrelevant if you leave it with people in the house you expect to rob you. > But what if you > use eval in a library function you write, which is used to parse some > input? Peer to peer networks, http servers, even text files that you try to > parse could be corrupted to cause your computer damage. These are ALL different contexts from the one I was talking about. None of these example are this context: > >> > foo = raw_input(...) > >> > x = eval(foo) I maintain that this: eval(raw_input(...)) in the vast majority of cases is as safe as letting the user have access to the machine in the first place. Your examples here: > use eval in a library function you write, which is used to parse some > input? Peer to peer networks, http servers, even text files that you try to > parse coul
Re: [Tutor] Security [Was: Re: Decoding]
On Monday 13 August 2007 22:39, Tiger12506 wrote: > > foo = raw_input(...) > > x = eval(foo) > > ... > Let your program run on your machine and I'll walk by, type in this string, > and hit enter. We'll see how much of an exception it is when you can't boot > your XP machine anymore. > ;-) Who cares? I don't run XP :-D Also, a broken XP machine is an opportunity anyway, not a problem. Seriously though, if typing: > "file('boot.ini','w').close()" Into an "eval prompt" worked then equally leaving a python interpreter open would be dumb, let alone a console. Oddly my desktop machine often has a shell open, and often has a python interpreter running as well. Indeed at present it has 11 shells open. The non graphical console is a root shell (accessible by alt-f1). My work machines likewise have around a dozen shells open each. However, when I leave my machine alone the display locks itself, and its normally behind a locked door (unless I'm with it). Quite frankly anyone getting worried about this: > > foo = raw_input(...) > > x = eval(foo) Is pretty over anxious IMO. "Gosh, the person at the console might be able to get python do something which they can do anyway". (This is rather distinct from taking random crap from someone not on the local console and just doing it (eg from a network connection/external resource)) If the user wishes to trash their own machine, using an eval prompt is a rather bizarre way to go about it. Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Security [Was: Re: Decoding]
On Monday 13 August 2007 21:53, Kent Johnson wrote: > Hmm...could be a remote connection such as ssh, which precludes the > sledgehammer though probably not the sort of mischief you can get into > with eval()...perhaps there are untrusted remote connections where > eval() would still be a significant risk, I don't know... If they can ssh into a box, the likelihood of that ssh connection *only* allowing them access to run that single python program strikes me as vanishingly small :-) Generally speaking I agree that eval is a good opportunity for problems, but if its in response to raw_input, I think the likelihood of it being the biggest potential security problem is low :) (After all, if they're ssh'ing in, they're more likely to ssh in, *then* run the code. They could happily delete and trash all sorts of things either inside or outside python. They could even write their own scripts to assist them in their devilish plans too, far exceeding the minor demon of eval ;-) Eval can however be an amazingly useful function, especially when combined with exec. Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Security [Was: Re: Decoding]
On Monday 13 August 2007 15:28, Kent Johnson wrote: > > The original poster posted a post with the following function: ... > > message=raw_input("Enter the message to decode: ") > > result='' > > for x in string.split(message): > > result=result+chr(eval(x)) > Anything where user input is executed as code is a security hole and > should never be opened to untrusted users. foo = raw_input(...) x = eval(foo) Is an exception, in almost[*] every scenario I can think of. (and is the context eval was being used as far as I can see without reading the whole thread) [*] One scenario that seems unlikely but possible is a scenario where a machine has been put into a form of kiosk mode where the *only* thing they can do is type responses to the raw_input prompt. Given where raw_input runs, this strikes me as highly unrealistic/unlikely. Why? Because if they can type on the keyboard of a machine that's running raw_input they have the ability to do far more damage that way than any other. (ability to use a real sledgehammer on the machine springs to mind :-) Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Losing the expressiveness ofC'sfor-sta tement?/RESENDwith example
Stephen, I've come into this thread late, but it looks like you're lamenting the fact you can stipulate complex iterations on a single line, which can be nice. I'd not really missed this in several years of programming with python. However, Your post is interesting because it raises a point I've personally not considered before. Your example loops are: for (node=start; valuenext) { ... } for (i=3; i>0; i=i/2) { ... } The argument you got back is that this is just syntactic sugar for logic along the lines of: node=start; while valuenext Which of course is true. However simply saying that does miss the fact that it is syntactic sugar with a purpose. Syntactic sugar is generally added for one of two reasons - speed of coding, or clarity of coding. In this case it can be argued it does both, since it spells out the iterator algorithm clearly on a single line. Specifically you can look at one line and see the loop logic. This is nowhere near as clear with this form: node=start; while valuenext And its certainly not on one line. If you still want to spell out the iteration in one location, then you're right you do have to use a generator. However the fact that you can put a def anyway means you can do this: start = getNodesFromSomewhere() def traverseNodes(start): node = start yield node while node.next: node = node.next yield node for node in traverseNodes(start): ... Similarly you can do this: def bisectdown(i=3): while i >0: yield i i = i/2 for node in bisectdown(3): ... That said, I agree that its not as nice perhaps as C's compact one liner for each of these. HOWEVER, you can rebuild C's version: (or something close) import compiler def cfor(iter_name, args,locals): Y=[x.strip().rstrip() for x in args.split(";")] Y[0] = compiler.compile(Y[0], "__main__.py", "exec") Y[1] = compiler.compile(Y[1], "__main__.py", "eval") Y[2] = compiler.compile(Y[2], "__main__.py", "exec") Y.append( compiler.compile(iter_name, "__main__.py", "eval")) exec(Y[0],locals,locals) while eval(Y[1],locals,locals): yield eval(Y[3],locals,locals) exec(Y[2],locals,locals) You can then use this as follows: max = 10 for i in cfor("i", "i=3; i>max; i=i/2",locals()): print i And also: start = getNodesFromSomewhere() for node in cfor("n", "n=start; n.next is not None; n = node.next", locals()): ... That's potentially quite useful. Yes there's a little cruft there (locals()), but its not hideously inefficient either because I've made sure we compile the code fragments and run those. Personally I think its not a huge loss, but if you do, then you can always reuse this cfor iterator if you like. I disagree though regarding the idea that C's for syntax is a universal syntax. It isn't. It's a commonly understood syntax due to C derived languages (C/C++/Java), but far from universal. I've had to learn many different "for" syntaxes over many years for different languages. Even then where a C-type loop is availabe, it isn't always idiomatic to use it. For example perl (which does have a C-type for loop) idiomatically uses foreach extensively. And you also get *very* different iterative behaviour in ruby. Different languages have different concepts. Just because you can write one language like another doesn't mean you should. That said, given that maxim, it sounds like your beef with more with docs rather than the lack of the construct, asking "is this a problem normally", to which the answer is most definitely not, "what do people normally do", to which you have numerous replies - people either create an iterator (as you often would in C++ and Java) or use a while loop. As for rudeness, bear in mind that text is a naturally harsh medium, and also cultural norms are very different for different posters. One man's polite behaviour is another man's gravest insult. No one means to be rude, so it's worth remembering that. (And yes, I know, merely saying that can be considered rude in itself in some cultures :-) You found people rude, they found you rude. None of you intended to be, and probably weren't from your own perspectives, that's what really matters. Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple way to compare Two lists
Hi, You're really asking about optimisation incidentally. On Friday 10 August 2007 10:54, Jaggo wrote: > Hello! > > I desperately need a simple way to compare whether any item of SmallList is > in BigList. A simple way: True in [x in BigList for x in SmallList] Not efficient necessarily, but it is a simple way. Sounds like you want a faster way. > My current way, > > def IsAPartOfList(SmallList,BigList) > for item in SmallList: > if item in BigList: > return True > return False This is directly equivalent to my approach above BUT I *expect* your approach will run faster. *Since you short circuit the result by returning true. > Takes up waay too much time to process. > Can anyone think of any better way? So what you're really after is a quicker way, yes? The problem you have here is worst case IsAPartOfList will run through all the elements of BigList a number of times (specifically len(SmallList). Sorting the two lists and then working through may be quicker, but I'm struck that the cost of sorting BigList itself may be more costly than you want given you say the above function you wrote (which is pretty efficient) is too slow. Two immediate thoughts - use psyco on the function. It's a simple enough function and psyco may be able to give you a dramatic speedup. Alternatively you could reverse your loop. Rather than do SmallList * BigList number of comparisons, if there are duplicates in BigList (rather than being a set), then you could iterate through BigList more efficiently. If I read your spec correctly, then the following holds true even though its the inverse of what you stated as the probem: def IsAPartOfList_2(SmallList,BigList) for item in BigList: if item in SmallList: return True return False Incidentally this simple reversal may in itself be quicker depending on your data. If the numbers are generated from (say) a list of events and you're correlating events, then you may find this quicker: def IsAPartOfList_3(SmallList,BigList) for item in reversed(BigList): if item in SmallList: return True return False Since that exploits domain knowledge about the two lists. This becomes especially likely if the lists are likely to be already sorted because they've come from some ordered source (eg a server log). Furthermore if BigList is a list of times all in ascending order, and SmallList is a list of times in ascending order, and the latter represents a list of "recent" events and BigList represents a list of all events, then you can make another optimsation to take advantage of that knowledge: def IsAPartOfList_4(SmallList,BigList) for item in reversed(BigList): if item in reversed(SmallList): return True return False Why? Consider the following two lists: BigList: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39] SmallList: [33, 34, 35, 36] Then IsAPartOfList_4 will make 13 comparisons before returning True. Whereas IsAPartOfList_2 will make 133 comparisons, and your original will make 34 comparisons. However, if you have duplicates in BigList, we can skip the "if item in SmallList" every time we have a duplicate: def IsAPartOfList(SmallList,BigList) seen = {} for item in BigList: if not seen.get(item, False): if item in SmallList: return True return False This will only give you a potential speedup IF two things hold: * BigList contains duplicates * seen.get(item, False) is quicker IF these things don't hold then you won't see any improvement. Personally I'd try using psyco on the function since then you leave the function looking clean and simple. Which is things is quickest will depend heavily on the likely structure of the data, likelihood of duplicate, ordering and likely similarities between data. Overall though you have two choices: * Exploit your knowledge of the distribution and ordering of values * Use psyco These aren't mutually exclusive options :-) Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generators
On Tuesday 24 July 2007 13:11, Kent Johnson wrote: > 'while 1' is optimized to just a jump - the compiler recognizes that the > test is not needed and skips it. 'while True' requires looking up the > value of the name 'True' and testing it. This may seem counter intuitive, but the reason for this (for anyone puzzled) is because True is a name for the value representing boolean true, rather than a keyword for the value. If it were a keyword for the value, then like "1" it could not change in value. However since it isn't, it can. For example, True can become false as the following demonstrates, so you do have to do those steps of looking up the value of the name "True" and test it: Python 2.5 (r25:51908, Nov 27 2006, 19:14:46) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> True = 10 >>> while True: ... print True ... True = True -1 ... 10 9 8 7 6 5 4 3 2 1 >>> Rebinding True to anything else is a bad idea, but doable :-) If you change True to "True" you get the same behaviour - python detects an immutable object in the condition and optimises it: >>> dis.dis(compile('while "True": pass', '', 'exec')) 1 0 SETUP_LOOP 3 (to 6) >>3 JUMP_ABSOLUTE3 >>6 LOAD_CONST 0 (None) 9 RETURN_VALUE Regards, Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] My Python project - an update
On Wednesday 28 March 2007 10:50, Rohan Deshpande wrote: > Out of curiousity, why md5? Hasn't it been cracked already? Would sha1 or > 2sum be a better alternative? I'm a newbie to this so it's just a > question. People have indeed shown vulnerabilities in MD5 for this sort of purpose. Specifically this includes modification of existing data on a system in a manner that preserves the MD5 with a crafted modification text (ie actual deliberate change, rather than random text that happens to match). SHA1 is generally considered a better approach at the moment as a result. This isn't to say that MD5 is hideously crippled - for most purposes its still very good, but in this particular context it makes less sense. Especially given that once this sort of vulnerability is shown first to be possible, then demonstrated with a specific attack associated with a repeatable method, after that things generally get worse not better. Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is generator function similar to multi threading?
On Friday 16 March 2007 06:52, ammar azif wrote: > Is generator function similar to multi threading? Yes, however unlike threads they are more general. They can be used in two main ways: * To generate a sequence of values * To achieve something similar to multithreading, but without using operating system threads. For a tutorial on how to do the latter safely, please take a look at this: http://kamaelia.sourceforge.net/MiniAxon/ (It's targeted at someone with very basic python skills, since the first iteration of that tutorial was written for someone who'd learnt python the previous week) We use the latter form extremely heavily on our project to great effect. One of benefits of using a generator over a thread is that you can (as of python 2.5) kill a generator by sending an exception into it.(though this isn't the reason we're using them) As a result combining threading and generators makes sense since you can run a generator inside a thread, and have a mechanism to kill the thread - you send an exception into the generator. That said, the primary intended use of generators *is* to generate values. The fact they're a restricted co-routine however is incredibly handy. (Because they can only be single layer, it forces them to be simpler, which in turn makes them much more reusable) Regards, Michael. -- http://kamaelia.sourceforge.net/Home http://yeoldeclue.com/blog ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (OT) Flame wars
On Monday 06 November 2006 22:52, Alan Gauld wrote: > I wasn't aware we were having a war, but I'm happy to desist :-) FWIW, I wasn't aware of one either. (Mind you I've often noticed what passes for plain speaking in the UK passes for vehement flame war elsewhere, so maybe that's it) Anyway, if that's what people here think a flame war looks like... Well, a) I'll try and avoid such /mild/ comments in future ;) b) good for such people, real flame wars are really nasty ! Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Amazing power of Regular Expressions...
On Monday 06 November 2006 01:08, Alan Gauld wrote: > While using a dictionary is probably overkill, so is a regex. No, in this case it's absolutely the right choice. > A simple string holding all characters and an 'in' test would probably > be both easier to read and faster. I'm stunned you think this. It's precisely this sort of naivete that baffles me with regard to regexes. > Which kind of illustrates the point of the thread I think! :-) Actually, no, it doesn't. A regex compiles to a jump table, and executes as a statemachine. (That or the implementation in the library is crap, and I don't believe for a second python would be that dumb) Given you can compile the regex and use it over and over again (as was the context the example code (isplain) was executed in) using a regex is absolutely the best way. I'd be extremely surprised if you could get your suggested approach faster. I also doubt it would actually be clearer, and in this case, that's MUCH more important. (heck, that's the reason regexes are useful - compact clear representations of a lexical structure that you want to check a string matches rather than obfuscated by the language doing the checking) * ^[0-9A-Za-z_.-]*$ Is a very simple pattern, and as a result an extremely simple specification. If any developer has a problem with that sort of pattern, they really need to go away and learn regexes, since they're missing important tools. (which shouldn't be over used). I'm serious, if you think ^[0-9A-Za-z_.-]*$ is unclear and complex, go away and relearn regexes. Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Amazing power of Regular Expressions...
On Sunday 05 November 2006 15:02, Kent Johnson wrote: ... > Regular expressions are an extremely powerful and useful tool that every > programmer should master and then put away and not use when there is an > alternative :-) There's always an alternative to a regular expression, so are you really suggesting *never* use a regex? (seriously though, I doubt you are, but taken in this context, that's how it looks). The most pathological example of regex avoidance I've seen in a while is this: def isPlain(text): plaindict = {'-': True, '.': True, '1': True, '0': True, '3': True, '2': True, '5': True, '4': True, '7': True, '6': True, '9': True, '8': True, 'A': True, 'C': True, 'B': True, 'E': True, 'D': True, 'G': True, 'F': True, 'I': True, 'H': True, 'K': True, 'J': True, 'M': True, 'L': True, 'O': True, 'N': True, 'Q': True, 'P': True, 'S': True, 'R': True, 'U': True, 'T': True, 'W': True, 'V': True, 'Y': True, 'X': True, 'Z': True, '_': True, 'a': True, 'c': True, 'b': True, 'e': True, 'd': True, 'g': True, 'f': True, 'i': True, 'h': True, 'k': True, 'j': True, 'm': True, 'l': True, 'o': True, 'n': True, 'q': True, 'p': True, 's': True, 'r': True, 'u': True, 't': True, 'w': True, 'v': True, 'y': True, 'x': True, 'z': True} for c in text: if plaindict.get(c, False) == False: return False return True (sadly this is from real code - in defence of the person who wrote it, they weren't even *aware* of regexes) That's equivalent to the regular expression: * ^[0-9A-Za-z_.-]*$ Now, which is clearer? If you learn to read & write regular expressions, then the short regular expression is the clearest form. It's also quicker. I'm not someone who advocates coding-by-regex, as happens rather heavily in perl (I like perl about as much as python), but to say "don't use them if there's an alternative" is a little strong. Aside from the argument that "you now have two problems" (which always applies if you think all problems can be hit with the same hammer), solving *everything* with regex is often slower. (since people then do one after another, after another - the most pathological example I've seen applied over 1000 regexes to a piece of text, one after another, and then the author wondered why their code was slow...) JWZ's quote is more aimed at people who think about solving every problem with regexes (and where you end up with 10 line monstrosities in perl with 5 levels of backtracking). Also, it's worth bearing in mind that there's more than one definition of what regex's are (awk, perl, python, and various C libraries all have slightly differing rules and syntax, even if they often share a common base). Rather than say there's one true way, it's worth bearing in mind that regexes are little more than a shorthand for structured parsing, and bearing this in mind, then it's worth recasting JWZ's point as: If your reaction to seeing a problem is "this looks like it can be solved using a regex", you should think to yourself: has someone else already hit this problem and have they come up with a specialised pattern matcher for it already? If not, why not? In this case that *should* have led the poster to the discovery of the specialised parser: time.strptime(date, '%d/%m/%Y') File globs are another good example of a specialised form of pattern matcher. Using a regex when it's appropriate is good. Finding a more appropriate specialised pattern matcher? Even better. Avoiding using regexes in the way I've shown above, because it's an alternative to using a regex? Bad, it's slow and unclear. :-) Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Turnkey Python on a USB stick
On Monday 27 March 2006 22:21, Steve Slevinski wrote: > Does this sound reasonable? Are their any alternatives to Movable > Python? (http://www.voidspace.org.uk/python/movpy/) Hi Steve, I've got no experience of setting up such a beast or using movable python, but I just wanted to say it sounds like an EXCELLENT idea, and I'd be interested in hearing how you get on! :) Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] map vs. list comprehension
On Tuesday 14 February 2006 20:57, Michael Broe wrote: ... > But I can't see a way to do this in a list comprehension: > > >>> map (pow, [2, 2, 2, 2], [1, 2, 3, 4]) > [2, 4, 8, 16] >>> [ x**y for x,y in zip([2,2,2,2],[1,2,3,4]) ] [2, 4, 8, 16] To me this is clearer. (despite having written some substantial amount of code in SML - a functional language where higher order functions are common) Why ? Because it's easier to mentally break down into its parts for someone less familiar with tools like map. >>> zip([2,2,2,2],[1,2,3,4]) [(2, 1), (2, 2), (2, 3), (2, 4)] >>> [ x**y for x,y in [(2, 1), (2, 2), (2, 3), (2, 4)] ] [2, 4, 8, 16] > Is there a way to do something like the following in a list > comprehension? > > map(pow, [1, 7, 6, 2], [3, 8, 2, 5]) >>> [ x**y for x,y in zip([1,7,6,2],[3,8,2,5]) ] [1, 5764801, 36, 32] Regards, Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] comiling python to microchip?
On Thursday 13 October 2005 01:08, Kent Johnson wrote: > Michael Sparks wrote: > > On Wednesday 12 October 2005 23:19, Kent Johnson wrote: > >>I don't think you can compile python code > > > > Pypy can compile a restricted subset of python... > > There is also Shed Skin - "an experimental Python-to-C++ compiler. It can > convert many Python programs into optimized C++ code" > http://shed-skin.blogspot.com/ Shed skin doesn't support exceptions yet though, which is a fairly major omission unfortunately. Pypy by comparison does, and can compile modules for import into python. Shed skin unfortunately doesn't do the latter. However, personally I think shed skin is pretty stellar - the C++ code it generates is (a lot) more readable than a lot of C++ code I've seen generated by people :-) Indeed. shed skin might be an interesting way for python programmers to learn C++ ;-) (I know, wrong list :) Definitely worth keeping an eye on though :) Regards, Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to extract number of files from directory
On Wednesday 12 October 2005 19:10, Marc Buehler wrote: > i would like to extract the number of JPG files > from the current directory and use that number I've looked through the thread, and the following strikes me as simpler than the suggestions so far. path = "." # Current directory, unix at least. extns = ["jpg", "jpeg"] # add in any others you like :-) piccies = [ f for f in os.listdir(path) if f.split(".")[-1].lower() in extns ] num_files = len(piccies) What does this do? os.listdir(path) -- gives you a list of files in that directory. The condition: f.split(".")[-1].lower() in extns Selects which filenames get put in the resulting list files. This expression says "split the filename on dots '.' ", take the last thing after the last dot, and make it lower. Finally check to see if that extension is in the list of required extensions. I suppose if you prefer a more verbose version of the same thing: path = "." # Current directory, unix at least. extns = ["jpg", "jpeg"] # add in any others you like :-) piccies = [] for filename in os.listdir(path): extension = f.split(".")[-1] if extension.lower() in extns: piccies.append(filename) num_files = len(piccies) Regards, Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] comiling python to microchip?
On Wednesday 12 October 2005 23:19, Kent Johnson wrote: > I don't think you can compile python code Pypy can compile a restricted subset of python... More accurately it translates the restricted subset to C and then *that* can be compiled. Some code can get quite dramatic speed improvements - though interpreted pypy itself (or translated) is still *a lot* slower than regular C-Python). Pypy isn't ready (last time I looked) for general consumption yet, and certainly not for beginners :) Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is it Posible? To Crack And HowTo
On Friday 07 October 2005 10:20, Suranga Sarukkali wrote: > All this could look mostly like any of a question of a idiot! sorry for > that. I've heard that Python is good for hacking and when I ask how to here > on python tutor mailing list answers were all about reading some article > I've already read before, it's not hacking I'm into now but a similar > thing, Cracking and I've got lots of software by these we call proprietary > software developers who are some greedy people having fun licensing > software. Can I get help to this using python and if how to? or elif can't > how to? else where can I get started and going? > > Thanks for all other questions you've answered! > reply to me on [EMAIL PROTECTED] at your earliest convenience. People who license software are well within their rights to do so. It took them time, effort and hence money to produce the software, and they deserve recompense. You wouldn't *demand* that the people emptying the bins in offces the code was developed in work for no wages would you? If you can't afford the software at their prices, I would suggest that it is they who have a problem rather than you. After all you have a wide variety of alternatives available. I don't however respect anyone who doesn't respect the rights of others. Sure, I don't agree with the poltics of party X and partly that's to do with not agreeing with their views on what is/isn't greedy. That doesn't give me the right to damage their livelihood. If you can't afford their software, then can I request you sta,rt using Free Software instead? You will still be complying with greedy people's licenses (they're greedy for freedom), but you will be helping people rather than hurting people. You might ask who am I to ask this question this way - a fair question. I'm a person who was once a student, and when unable to pay for a commercial C compiler (neither Microsoft's or Borland's) chose the route of using DJGPP - a Free alternative. I didn't consider rogue copying then acceptable, despite a need, and lack of finance, and nor do I now. There are alternatives. Also, finally consider this: the required ability to *make* a crack (rather than follow a script) is normally pretty high. You /could/ apply that ability soley to destroying the incomes of people (which is what you do if you /release. a crack) . Alternatively you could take that energy and ability into building better things. Destruction or construction? your choice. I doubt you'll find many, if any, people to aid you in a destructive task. Regards, Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New Python book
On Wednesday 05 October 2005 19:20, Kent Johnson wrote: > This seems to be an update to his previous book, "Practical Python", rather > than a completely new book. The TOC is almost identical. I haven't read the > earlier book, either, so I don't have an opinion. The same sample chapter > is available for each if anyone wants to compare. (see www.apress.com) My wife bought me 'Practical Python' for my birthday last year. I found it to be a very readable style and interesting. I quite like reading books aimed at beginners/novices/etc because it normally results in a fresh view of subjects that I feel are done and dusted. The thing I find particularly interesting about the approach is the 'project oriented' approach in the latter half of the book. I found the GUI chapters to be relatively useless to me. Having downloaded the sources to the examples for this update though it looks like he's using wx extensively throughout, which strikes me as both a good & bad choice. Good in that wx is pretty good, bad in that using Tk would IMO be better since python ships with Tk. That's highly subjective though. Best Regards, Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work?
On Friday 07 October 2005 03:04, R. Alan Monroe wrote: > > I've just double checked what happens when running the contents of that > > page, and it works as expected (here at least), so I suspect the problems > > you're seeing are simply due to "code being in HTML" issues. > > Yeah I was writing as much as I was able on my own rather than > copying/pasting the code, so it was mainly an oversight in my own > work. That's great to hear - not the oversight part but the fact you were talking about your work. Out of interest, how did you find the tutorial/exercises and what level of experience would you say you have? (I know some people find such questions rude and impertinent though so if you want to not say, I don't have a problem, I just hope you found it useful/interesting) Also, if there were bits you found odd, broken, etc, we'd be really interested in hearing things. Specifically I'm more interested in knowing whether a) the approach is compehensible based on the tutorial b) whether the tutorial sucks over some momentary twinge of personal ego. I lived in the North of England for several years (not recently, but...) , so strong language/views won't offend ;-) We're going to be making a 0.3 release of Kamaelia this weekend which has a lot more facilities than the previous releases, but the core approach remains the same - bolting together things. Anyway, thanks for the feedback, it's useful - very useful - and I hope the tutorial helped with understanding generators, how to use them and what they could be used for (if you weren't already comfortable with them :-) Best regards, Michael. -- "Though we are not now that which in days of old moved heaven and earth, that which we are, we are: one equal temper of heroic hearts made weak by time and fate but strong in will to strive, to seek, to find and not to yield" -- "Ulysses", Tennyson ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work?
On Friday 07 October 2005 00:13, R. Alan Monroe wrote: ... > I can see in Pythonwin's debugger that p.boxes['outbox'] fills up with > the hundred or so messages intended for display, but they never get > displayed. I suspect an indentation problem, but I can't spot it, even > stepping through in the debugger. Hi! First of all thanks for trying the tutorial - hope it's been interesting. I'm sorry you hit a problem with it - it looks like the HTML formatting has caused some issues :-( All the code and examples used were tested before the being placed into the "tabbed" version of the tutorial. In this case it looks like the whitespace has gone horribly horribly wrong on that tab :-((( I'll sort it out. In the meantime though, In case of precisely this problem occuring, I also placed that source for all 4 main sections (Standing, Walking, Talking, Conversing) in the following page here: http://kamaelia.sourceforge.net/MiniAxonFull.html I've just double checked what happens when running the contents of that page, and it works as expected (here at least), so I suspect the problems you're seeing are simply due to "code being in HTML" issues. Also, the entire tutorial is available as a single page here, rather than tabbed: * http://kamaelia.sourceforge.net/MiniAxon.html But that has the answers inline, which is why I didn't mention it before. That *does* appear to have formatting preserved correctly in firefox, and I've also just double checked that when copying and pasting that the stated results were the ones stated. Hoping this helps, and thanks! If you're willing to spare a few sentances of how you found the tutorial (on or off list), I'd be really interested in hearing. If it's difficult, what was difficult (naff HTML for example...), if it was clear/unclear, that sort of thing. That said, this query is useful feedback in itself :) Best Regards, (and apologies for the HTML formatting ... :-( Michael. -- Michael Sparks, Senior R&D Engineer, Digital Media Group [EMAIL PROTECTED], http://kamaelia.sourceforge.net/ British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This e-mail may contain personal views which are not the views of the BBC. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] More than one thing at a time?
[ cc'ing the Kamaelia list in case it makes sense to move this conversation there. ] On Sunday 02 October 2005 15:20, Joseph Quigley wrote: > Hi Michael, > You're explanation helped a lot, however, I'm really not good at gui > programming and the irc client was supposed to be a console application, > but: Would it be hard to just have a send texbox and receive read-only > text box? It shouldn't be difficult at all really. If you find an example of a hello world program, and a "hello who are you" program, then it's just a simple matter of using that. If you're happy using pygame as a display, then you could use our Ticker component already. Example 11 shows how to use the Ticker. (Essentially though it takes text strings on it's inbox and displays them. Which gives you a read-only text box) I should've thought of it sooner though, but you //could// do this: pipeline( ConsoleReader(), IRCClient(host="server", port = 6667, nick = "userid", nickinfo = "myclient 1.0", defaultChannel = "#test" ), Ticker(background_colour=(128,48,128), render_left = 1, render_top = 1, render_right = 600, render_bottom = 200, position = (100, 300), ) ).run() We don't actually have a console reader component, but it's simple to knock one up. The only complicating factor here is that reading from the console can be blocking which would lock up the whole system. As a result you'd want that to be a threaded component. (The API for those needs cleaning up admittedly) However the code and simple system test for that looks like this: # Tested on my machine just now and works :-):-) from Axon.ThreadedComponent import threadedcomponent from Kamaelia.Util.ConsoleEcho import consoleEchoer from Kamaelia.Util.PipelineComponent import pipeline class ConsoleReader(threadedcomponent): def run(self): # Threaded components use this method instead of "main" while 1: line = raw_input() line = line + "\n" self.outqueues["outbox"].put(line) pipeline(ConsoleReader(), consoleEchoer() ).run() ### Considering we do have a nascent IRClient component in /Sketches, the Ticker exists and the above ConsoleReader exists, this might speed things up for you. > I'll try this, but I think I should mention that I'm using python-irclib > from sourceforge. I'd suggest that our IRCClient code is nowhere near complete though, and whilst I've not tried python-irclib, I'd suggest looking at our IRCClient component to see how you might want to rewrite it to use python-irclib. > I'll try Kamaelia, thanks a lot. Please do. If you're willing to wait 24 hours we're doing the 0.3 release, which is a much expanded base to work with. If you can't wait, do a cvs checkout of the whole tree - ie: mkdir kamaelia cd kamaelia # So easy to forget to do this, leaving clutter everywhere :-):-) cvs -d:pserver:[EMAIL PROTECTED]:/cvsroot/kamaelia login cvs -z3 -d:pserver:[EMAIL PROTECTED]:/cvsroot/kamaelia co -d . That'll leave you with a full check out. You'll need to then install Axon: cd Code/Python/Axon python setup.py install Similarly to install Kamaelia: cd Code/Python/Kamaelia python setup.py install You'll then find an example program using the ticker in: Code/Python/Kamaelia/Examples/example11 You might also find Code/Python/Kamaelia/Examples/example9 of interest given your query on the pygame list regarding moving pictures about. :):) It's a **simple** game designed to amuse very young children bouncing sprites around the screen. It demonstrates very simple keyboard handling as well - specifically pausing, unpausing and toggling movement. As I say to everyone who looks at Kamaelia - if you find it useful, that's great - if you have any ideas for improvement, please let us know. If you have any criticisms (postive or negative - especially if negative) please let us know. Finally if you want to share any components back to the project we'd be happy to merge them first into sketches and then into the main tree if there's a logical fit. Even a trivial component (such as the one above) has a useful place in the tree - as you can see from this reply :-):-) Best Regards, Michael. -- "Though we are not now that which in days of old moved heaven and earth, that which we are, we are: one equal temper of heroic hearts made weak by time and fate but strong in will to strive, to seek, to find and not to yield" -- "Ulysses", Tennyson ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] More than one thing at a time?
On Saturday 01 October 2005 12:36, Kent Johnson wrote: > Another way to do what you want is to use Twisted; this is touched on in > the second thread above. Another way is to use Kamaelia - its' specifically aimed at making it easy for newbies (and everyone else, me especially :-) do more than one thing at a time. If you understand unix pipelines you already understand the core ideas. (or indeed, how to wire a battery to a bulb :) Though until we've had a number newbies do the mini-axon tutorial and say what they wold like to see improved (in terms of clarity, ease of use), I'd hesitate suggestng it. (People who write things have already by definition gone up the learning curve and hence can't truly evaluate ease no matter how hard they try). However logically using Kamaelia (or any other system) you have 3 concurrent activities/3 things happening at a time here: * Handling sending & receiving of data * Accepting user input to send * Displaying output from the connection In Kamaelia we would /directly/ wrap this as 3 hypothetical components with a top level that might look like this: pipeline( TkTextInputWidget(mode="lineatatime"), IRCClient(host="server", port = 6667, nick = "userid", nickinfo = "myclient 1.0", defaultChannel = "#test" ), TkDisplayWidget(), ).run() Or using a more explicit/low level description of the same system: Graphline( IRC = IRCClient(host="server", port = 6667, nick = "userid", nickinfo = "myclient 1.0", defaultChannel = "#test" ), TOIRC = TkTextInputWidget(mode="lineatatime"), FROMIRC = TkDisplayWidget(), linkages = { ("IRC", "outbox") : ("FROMIRC", "inbox"), ("TOIRC", "outbox") : ("IRC", "inbox"), } ).run() (personally I prefer the latter implementation here since it's more clear the 3 things are relatively independent rather than dependent on the start of the chain. They are both equivalent though.) We've got a nascent IRCClient component in /Sketches of our codebase, and there's display & type in code in the PipeBuilder code in /Sketches that could serve as a starting point. Writing TkDIsplayWidget should be trivial - since it's equivalent if a "hello world" program (more or less) in Tk, and the TkTextInputWidget should also be trivial since it's a matter of writing a Tk based program that allows you to say "What is your name" and have a type in box to answer. In the mainloop, the display widget would check its inbox for data, grab it and display it. The input widget would send data to it's outbox when some types something in. We'd normally recommend writing standalone small scripts for each of these interacting with stdin (instead of an inbox) and stdout (instead of an outbox) - say via "print" when writing them and then turn them into components and then wire everything together. Also aside from a tutorial on how to build the system itself (it's not really that complex) at: * http://kamaelia.sourceforge.net/MiniAxon. We've also got a tutorilal on writing components here: * http://kamaelia.sourceforge.net/cgi-bin/blog/blog.cgi?rm=viewpost&postid=1113495151 If the OP does choose to take this approach, they'd need to use a CVS checkout rather than the main release though since we haven't done a release yet including the TK stuff (Though one is imminent). One key aim of Kamaelia is to make it simple & easy to make it possible to have more than one thing at a time to be dealt with - especially with regard to networking things, so I'd //hope// that using Kamaelia here might be the easiest place to start. Hoping this was useful, Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Request for newbies :-)
[ This /may/ be very "off-netiquette" for the tutor list. If it is, I apologise in advance. ] Hi, One of the aims of the project I'm working on is that it aims to make writing programs which are inherently (and potentially) highly parallel/concurrent easy & safe to work with. We've tested our hypothesis so far with a pre-university trainee who had very little programming experience before joining our team (a little bit of visual basic, some Access). During his time with us he learnt python during his first week, and did learnt our system in his second week. In the remainder of his time with us he wrote a highly parallel program that simulated a digital TV decoder - using a shakespeare script as the data source, and doing things like scene detection, and displayed the script & characters using pygame (which was handled by other parts of the system.) That was a side project (20% style project if you like) whereas his main project he implemented during his short time with us was a system for going through an mpeg video, and sending snapshots every few seconds to a client running on a mobile phone (using python and our system). (An application of this could be browsing PVR content on a mobile). We've since also had a vacation trainee (who's just completed 2 years of his course) join us, and in his 6 weeks with us he learnt python, our system, and despite no prior networking knowledge implemented a system for joining multicast islands together and adding in reliability on top. (A possible application of this is "broadcast" of news over the internet) It's worth noting that the first trainee had very little experience of programming, networks, mobiles and so on, and that the second had no real knowledge of python, networks, concurrency, etc. The approach we took for teaching the system was to get people to implement a simple version of the core of the system itself. (After getting them to work through "How to think like a computer scientist" the week before). This implementation was guied by a simple tutorial that is formulated as a series of guided exercises (Standing, Walking, Talking, Conversing), with a couple of interludes discussing the implications of the results of the exercise. As a result this is where I come to a request. If there is anyone out there who is willing to do the following tutorial/exercises, could they please do so at their own pace and when they've done them please get in touch? * http://kamaelia.sourceforge.net/MiniAxon/ If you want a holding hand, I'm often on #kamaelia on irc on freenode. In order to do the tutorial you need to understand the following concepts: * classes, methods, functions, if/elif/else, while, try..except, for..in.., generators (yield), lists, dictionaries, tuples. If you're not clear on generators, this might be a good way of understanding what you can do with them :-) Thanks in advance to anyone willing to give this a go, and to others for their patience regarding this message! Best Regards, Michael. -- Michael Sparks, Senior R&D Engineer, Digital Media Group [EMAIL PROTECTED], http://kamaelia.sourceforge.net/ British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This e-mail may contain personal views which are not the views of the BBC. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] call a def/class by reference
On Thursday 29 September 2005 22:26, Alan G wrote: > string -> function mapping directly. > > Its not usually a very useful thing to do This is precisely how shared libraries under linux and IIRC DLLs in windows work. cf dlopen, dysym in C. > how would the typical user know what the function names were? Under linux one can examine the names of functions in a library using "nm". eg: # nm libpython2.4.so|head -20 U abort@@GLIBC_2.0 000dfea0 d abs_doc 0001fcf0 t abstract_get_bases 0001fe20 t abstract_issubclass U access@@GLIBC_2.0 000e9ba0 d acquire_doc 0008f970 t addcleanup 0001be40 t addclosure 000d2040 d add_doc 0009d7c0 t add_flag 0001b8f0 t addnfaarc 0001b870 t addnfastate 00059680 t add_subclass 00049de0 t adjust_tp_compare 000ea680 d alarm_doc U alarm@@GLIBC_2.0 000e9760 d allocate_doc 000e6280 d api_version_warning 0003a6f0 t app1 000cfc40 d append_doc Obviously, ctypes does much the same thing. Compare and contrast: try: from ctypes import * libc = cdll.LoadLibrary("/lib/libc.so.6") sched_yield = libc.sched_yield except ImportError: def sched_yield(): pass except AttributeError: def sched_yield(): pass with ... try: import functions as libc sched_yield = getattr(libc, "sched_yield") # this is of course effectively equivalent to: # sched_yield = libc.sched_yield except ImportError: def sched_yield(): pass except AttributeError: def sched_yield(): pass It's pretty much the same thing. I could see that this may have uses in systems that allow plugins. Devils-advocate-ly , ;-) Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] stopping threads?
On Thursday 29 September 2005 07:27, Pierre Barbier de Reuille wrote: > IMO, it is better to explicitely call the base class ... I think it is > more readable. But I don't know if there is any drawback for any > solution... A drawback of NOT using super is that you're potetially setting yourself you for a fall. Consider the following code (Option 1) from hypothetical import SomeBaseClass class myClass(SomeBaseClass): def __init__(self, ...): super(myClass, self).__init__(...) (Option 2) from hypothetical import SomeBaseClass class myClass(SomeBaseClass): def __init__(self, ...): SomeBaseClass.__init__(self) In the case of option 1, this will work, and have reliable, predictable behaviour even if the implementation of SomeBaseClass in the "hypothetical" library changes from something like: class SomeBaseClass(ActualBase): ... To something like: class SomeBaseClass(ActualBase,mixin1, mixin2): ... In Option 2, you run the risk of methods higher up the tree being run more than once. Obviously in your *own* code you can avoid this if you like, but as soon as you start using and inheriting from classes in other people's libraries you can't guarantee that you're not running that risk. I posted an example about this via gmane's email to news gateway last week, but it doesn't appear to have hit the archive (or the list :) for some reason, so I've included the reply I gave illustrating what can go wrong if you don't use super at the end. Regards, Michael. --- Original post regarding super: Subject: Re: Using superclass __init__ method paul brian wrote: > class Base: >def __init__(self): >print "hello" > > class Child(Base): >def __init__(self): >Base.__init__(self) > >def foo(self): > print "foo" I note this is using "old" style classes. However it's normal to recommend that people use "new" style classes these days. (I only started using python after they invented new style classes, hence the quotes around new/old) A more canonical example here is this: class Base(object): def __init__(self): print "hello" class Child(Base): def __init__(self): super(Child,self).__init__() def foo(self): print "foo" Whilst this might an esoteric change, it's really to handle the fact that python has multiple inheritance. Consider: >>> class ChildOne(Base): ... def __init__(self): ... Base.__init__(self) ... print "Hello from ChildOne" ... >>> class ChildTwo(Base): ... def __init__(self): ... Base.__init__(self) ... print "Hello from ChildTwo" ... >>> class GrandChild(ChildOne,ChildTwo): ... def __init__(self): ... ChildOne.__init__(self) ... ChildTwo.__init__(self) ... print "Hello from GrandChild" ... >>> GrandChild() Hello from Base Hello from ChildOne Hello from Base Hello from ChildTwo Hello from GrandChild <__main__.GrandChild instance at 0x40397f8c> What you can see here is that the __init__ in Base was executed twice. This may or may not be a problem with some things, but where people use classes to "mixin" functionality it can be a real problem. Consider the alternative using "super" instead: >>> class Base(object): ... def __init__(self): ... print "Hello from Base" ... >>> class ChildOne(Base): ... def __init__(self): ... super(ChildOne,self).__init__() ... print "Hello from ChildOne" ... >>> class ChildTwo(Base): ... def __init__(self): ... super(ChildTwo,self).__init__() ... print "Hello from ChildTwo" ... >>> class GrandChild(ChildOne,ChildTwo): ... def __init__(self): ... super(GrandChild,self).__init__() ... print "Hello from GrandChild" ... >>> GrandChild() Hello from Base Hello from ChildTwo Hello from ChildOne Hello from GrandChild <__main__.GrandChild object at 0x4039ccac> Regards, Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Embedding
On Tuesday 27 September 2005 23:16, Kent Johnson wrote: > Joseph Quigley wrote:... > > Well we are three programmers. I know python, another knows Java and the > > other C++. We are trying to figure out how to combine all three > > langauges to make a game. > > Sounds like a bit of a hash to me. Show them pygame and convince them to > learn Python :-) If you tell them to drop the type declarations, braces {}, semicolons, and make their code a touch simpler, then they already (more or less) know python (At least that's the way I normally introduce people who know C/C++/Java to python). Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Linking with C programs
On Tuesday 27 September 2005 14:49, Matt Williams wrote: > Could someone explain how, in very general terms, one would use python > to wrap some C libraries/ API. > > I ask because there are a few bits of C software that look quite > interesting, and I know that Python can be used to wrap the C - but how > does it work? Use Pyrex. If you don't care about produce bindings for languages other than python and you just want access to C based libraries, then pyrex is by far the most pleasant way I've found of wrapping C. Essentially pyrex is a bridge language - half C and half python. It compiles down to pure C, but handles all the awkward parts of bridging the two for you. (like handling ref counts and similar.) We've used this to wrap a few libraries so far and it's been a pleasant experience everytime. It has a couple of tutorials, that work, and even shows you how to use distutils (aka setup.py) to make it easy for others to build your bindings too. * http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ * http://ldots.org/pyrex-guide/ - Michael Smith's guide to Pyrex - it's IMO brilliant and the examples work, and if you're used to C and used to python just feels _natural_ . If you're after a couple of examples to work forward, you can download them from: * http://sourceforge.net/projects/kamaelia Specifically the vorbissimple and python-dirac downloads will hopefully get you started. (The vorbissimple example includes a small simple library written in C and show hand off of data from python to C and from C to python, as well as how to have a "context" variable in C that python doesn't need to understand the internal structure of. (Much like with a FILE structure you don't need to understand the FILE structure's internals, just how you pass it about) Regards, Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Diamond Equivalent
On Thursday 22 September 2005 23:46, [EMAIL PROTECTED] wrote: > I am coming to Python from Perl. Does Python have anything like the diamond > operator found in Perl? The correct answer is not really no, but you can manually perform the same tasks. For those who don't know perl, <> is an incredibly useful little operator that does some really wierd and wonderful things :-) (That said, I don't think I'd like a magic operator like this in python :-) If you want to do this: @a = <>; The equivalent is probably best expressed thus: def diamond_array(): # Note, untested... import sys if len(sys.argv ==1): return sys.stdin.readlines() else: result = [] for file in sys.argv[1:]: try: file = open(file) result.extend(file.readlines()) except IOError: pass return result a = diamond_array() If however you want to do the equivalent of: while ($line = <>) { ... } That mode of <> probably best equates to this: for line in diamond_lines(): def diamond_lines(): # Note, untested... import sys if len(sys.argv ==1): for line in sys.stdin.xreadlines(): yield line else: for file in sys.argv[1:]: try: file = open(file) for line in file.xreadlines(): yield line except IOError: pass As for this idiom: while(1) { $line = <>; ... } That probably matches best to this: diamond_iterator = diamond_lines() # same function as above while 1: line = diamond_iterator.next() Whereas this kind of trick: $firstline = <>; @remaining_lines = <>; Would map to this: (using the functions above) diamond_iterator = diamond_lines() firstline = diamond_iterator.next() remaining_lines = list(diamond_iterator.next()) Or to show a relatively common perl idiom: $firstline, @remaining_lines= <>,<>; Maps to: diamond_iterator = diamond_lines() firstline,remaining_lines = diamond_iterator.next(), list(diamond_iterator.next()) Best Regards, Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor