Re: Why do Perl programmers make more money than Python programmers
On 6 May 2013 13:03, Steven D'Aprano wrote: > On Mon, 06 May 2013 17:30:33 +1000, Chris Angelico wrote: > > > On Mon, May 6, 2013 at 4:28 PM, Fábio Santos > > wrote: > >>> And of course, the Python Programmer's moral code is only 80 > >>> characters wide. > >> > >> No! Was it not seventy characters wide? Was I fooled my entire life? > > > > Well you see, it was 70 bytes back in the Python 2 days (I'll defer to > > Steven for data points earlier than that), > > > You had bytes? You were lucky. When I were a lad, we used to have to > program by punching holes in stone tablets with our head. > > > You-tell-young-people-this-today-and-they-don't-believe-you-ly y'rs, I do have my doubts, yes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with loading file into an array
On 5 May 2013 07:06, peter berrett wrote: > I am trying to build a program that can find comets in a series of > astronomical images. I have already written functions to find the comet in > a series of images, the data of which is stored in embedded lists. > > The area I am having difficulty with is take a standard gif file (1024 x > 1024) and reading it into an array or embedded lists. > This is not what you should really be doing. There are specialised things for this. Take a look at PIL (http://www.pythonware.com/products/pil/). It will install as "Image" and from there you can do: import Image image = Image.open("FILE") pixels = image.load() and access the pixels like: pixels[x, y] # You get (r, g, b) tuple of integers from 0 to 255 > In a nutshell here is an example of what I want to do > > Let's say I have a gif file called 20130428__c2_1024.gif in a folder > called c:\comets > > I want to read the data from that gif file taking the red data (excluding > the green and blue data) and store that in an array called Image[][] which > is a nested array length 1024 with a list in each item of 1024 length (ie > 1024 x 1024) > *Ahem*: 1) Python standard is to only uppercase class (and sometimes module) names, so it should just be "image". 2) Technically, you mean list. 3) Chose the above method instead, so instead of indexing it with "image[x][y]" you use "image[x, y]". Now, you only want the red channel. What this means is that you want to "split" the image into channels before using image.load(): import Image image = Image.open("FILE") image.load() # .open is lazy, so you have to load now red, green, blue = image.split() red_pixels = red.load() And you access as before: red_pixels[x, y] # You get integer from 0 to 255 Could someone please provide a piece of code to do the above so I can then > go on to modify it to pick up different files from different folders? In > particular I am keen to seen how you read in the data and also how you > change the directory from which you are reading the image. > Changing directories is done with "os.chdir" ( http://docs.python.org/3/library/os.html#os.chdir). > For the record this is not for homework but is a pet project of mine. I > have already written a version of the program in Justbasic but python is > faster. I am also interested in readers views as to which is the simplest > and best way to achieve what I am trying to do. > Thanks for the clarification, btw. Good luck, as well. -- http://mail.python.org/mailman/listinfo/python-list
Re: Collision of Two Rect
On 4 May 2013 00:42, Ian Kelly wrote: > The other thing that is suspicious about the code you posted is that > it has two different notions of the ball's position that are not > necessarily in agreement. There is the ball_rect, and there are also > the x and y variables. > You should be careful to make sure these > variables agree at all times -- or better yet, get rid of x and y > entirely, so that you only have one notion of the ball's position to > worry about. Pygame uses integers for its Rects and thus I advise much the opposite: *never* store position in Rects. Sorry, but it's true. You'll need to keep x and y around and try to use Rects only when representing pixels on the screen. Pygame has a lot of deficiencies with its default set of objects and functions, so it's something to get used to. -- http://mail.python.org/mailman/listinfo/python-list
Fatal Python error
Hello all, again. Instead of revising like I'm meant to be, I've been delving into a bit of Python and I've come up with this code: class ClassWithProperty: @property def property(self): pass thingwithproperty = ClassWithProperty() def loop(): try: thingwithproperty.property except: pass loop() try: loop() except RuntimeError: pass As you will expect, this does nothing... on Python2.7 and PyPy. Python3.3 prefers to spit out a "Fatal Python error: Cannot recover from stack overflow.", which seems a bit unexpected. Wuzzup with that? -- http://mail.python.org/mailman/listinfo/python-list
Re: Fatal Python error
On 29 May 2013 13:25, Dave Angel wrote: > On 05/29/2013 07:48 AM, Joshua Landau wrote: > >> Hello all, again. Instead of revising like I'm meant to be, I've been >> delving into a bit of Python and I've come up with this code: >> >> > To start with, please post in text mode. By using html, you've completely > messed up any indentation you presumably had. Appologies, I use GMail and I don't know how to force text-only > class ClassWithProperty: >> @property >> def property(self): >> pass >> > > Did you really mean to hide the built-in property? I don't know if this > does that, but it's certainly confusing. And perhaps that's a difference > between 2.x and 3.x I'm not. That goes to self.property, whilst the normal function isn't. I guess it does locally hide it, but who really cares? :P You can rename it if you want. Anything will do. Obviously this is a minimal example code, and not the real thing. As you will expect, this does nothing... on Python2.7 and PyPy. Python3.3 >> prefers to spit out a "Fatal Python error: Cannot recover from stack >> overflow.", which seems a bit unexpected. >> >> > A stack overflow means you have infinite recursion. I realise, but I was hoping to catch that with the "except RuntimeError". > Try fixing the property name above, and see if that makes a difference. It does not make a difference. -- http://mail.python.org/mailman/listinfo/python-list
Re: Fatal Python error
On 29 May 2013 13:30, Marcel Rodrigues wrote: > > I just tried your code with similar results: it does nothing on PyPy 2.0.0-beta2 and Python 2.7.4. But on Python 3.3.1 it caused core dump. > It's a little weird but so is the code. You have defined a function that calls itself unconditionally. This will cause a stack overflow, which is a RuntimeError. The weirdness of the code is simply as I've taken all the logic and conditionality away, since it was irrelevant. Why, though, does removing any one element make it fail properly? That's what's confusing, largely. > > Since you are handling this very exception with a pass statement, we would expect that no error occurs. But the fatal error message seems pretty informative at this point: "Cannot recover from stack overflow.". > > One thing to note is that while it's reasonable to handle exceptions that happens at the level of your Python code, like a ValueError, it's not so reasonable to try to handle something that may disturb the interpreter itself in a lower level, like a stack overflow (I think that the stack used by your code is the same stack used by the interpreter code, but I'm not sure). What is the expected response here then? Should I ever feel justified in catching a Stack Overflow error? This code was extracted from a file manager after much difficulty, but it should have been "caught" by a global try...except and not crashed the whole program immediately. I'd imagine that's a good enough reason to bring this up. Also; This works for the code: def loop(): thingwithproperty.prop loop() This does not: def loop(): try: thingwithproperty.prop except: pass loop() thingwithproperty.prop NEVER creates an error. (.prop is the new .property) -- http://mail.python.org/mailman/listinfo/python-list
Re: Fatal Python error
On 29 May 2013 14:02, Dave Angel wrote: > On 05/29/2013 08:45 AM, Oscar Benjamin wrote: > Joshua: Avoid doing anything complex inside an exception handler. Unfortunately, Ranger (the file manager in question) wraps a lot of stuff in one big exception handler. Hence there isn't much choice. The original wasn't actually in an infinite recursion, too, but just a recursion over a large directory. Is there a reason that Python 3 can't be made to work like Python 2 and PyPy, and -if not- should it? The catchable fail would be much nicer than just bombing the program. In the meantime the algorithm should just be reworked, but it seems like a larger step than should be needed. If nothing else, the exception frame is huge. I probably would have > spotted it except for the indentation problem triggered by html. The top > level code following your function didn't have any loops, so it wasn't a > problem. > > Can anyone help Joshua put his gmail into text mode? I've found a new option. As a test, here's a simplified version without the property: def loop(): try: (lambda: None)() except: pass loop() try: loop() except RuntimeError: pass which is pretty much Oscar Benjamin's, but less stupid. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can anyone please help me in understanding the following python code
On 30 May 2013 10:48, wrote: > Question: > - > Function mergeSort is called only once, but it is getting recursively > executed after the printing the last statement "print("Merging ",alist)". But > don't recursion taking place except at these places "mergeSort(lefthalf), > mergeSort(righthalf)" > > Sometimes the function execution directly starts from i=0,j=0,k=0 . Not sure > how. Here's some different code; it does the same thing but in a less weird way: ## def mergeSort(alist, depth=1): # If the piece we have to sort is [i] or [], then we have no sorting to do if len(alist) <= 1: # Returning what we were given # Make a new list from it, though, because we are nice print("{padding}return {list}\n".format(padding=" "*depth*8, list=alist)) return alist[:] # Split along the middle mid = len(alist)//2 # We have two halves lefthalf = alist[:mid] righthalf = alist[mid:] # Which we sort, so we have two sorted halves print("{padding}lefthalf = mergesort({list})\n".format(padding=" "*depth*8, list=lefthalf)) lefthalf = mergeSort(lefthalf, depth+1) print("{padding}righthalf = mergesort({list})\n".format(padding=" "*depth*8, list=righthalf)) righthalf = mergeSort(righthalf, depth+1) # We want to return a sorted "alist" from our two lists # We'll add the items to here new_list = [] # We'll go through adding the smallest to new_list while lefthalf and righthalf: # Lefthalf has the smaller item, so we "pop" it off into new_list if lefthalf[0] < righthalf[0]: new_list.append(lefthalf.pop(0)) # Righthalf has the smaller item, so we "pop" it off into new_list else: new_list.append(righthalf.pop(0)) # One of our lists isn't empty, so just add them on new_list += lefthalf + righthalf print("{padding}return {list}\n".format(padding=" "*depth*8, list=new_list)) return new_list print("Start mergesort({list}):\n".format(list=[2, 4, 0, 1])) sorted_list = mergeSort([2, 4, 0, 1]) print("Our final result: {list}".format(list=sorted_list)) ## And it gives ## Start mergesort([2, 4, 0, 1]): lefthalf = mergesort([2, 4]) lefthalf = mergesort([2]) return [2] righthalf = mergesort([4]) return [4] return [2, 4] righthalf = mergesort([0, 1]) lefthalf = mergesort([0]) return [0] righthalf = mergesort([1]) return [1] return [0, 1] return [0, 1, 2, 4] Our final result: [0, 1, 2, 4] ## Hopefully this code is a little easier to understand - the original changes the list while it is running the algorithm and mine makes new lists. The algorithm is very similar, and what you learn applies to both. You can see in the output (thanks Chris Angelico) that the main function is always running. It runs *two* other instances: lefthalf and righthalf. So the "mergesort([2, 4, 0, 1])" runs "lefthalf = mergesort([2, 4])" "mergesort([2, 4])" runs "lefthalf = mergesort([2])" "mergesort([2])" gives back [2] to "mergesort([2, 4])" "mergesort([2, 4])" goes "OH! I can continue now" and runs "righthalf = mergesort([4])" "mergesort([4])" gives back [4] to "mergesort([2, 4])" "mergesort([2, 4])" goes "OH! I can continue now" and gives back [2, 4] to "mergesort([2, 4, 0, 1])" "mergesort([2, 4, 0, 1])" goes "OH! I can continue now" and runs "righthalf = mergesort([0, 1])" "mergesort([0, 1])" runs "lefthalf = mergesort([0])" "mergesort([0])" gives back [0] to "mergesort([0, 1])" "mergesort([0, 1])" goes "OH! I can continue now" and runs "righthalf = mergesort([1])" "mergesort([1])" gives back [1] to "mergesort([0, 1])" "mergesort([0, 1])" goes "OH! I can continue now" and gives back [0, 1] to "mergesort([2, 4, 0, 1])" "mergesort([2, 4, 0, 1])" goes "OH! I can continue now" and gives back [0, 1, 2, 4] DONE. Does that help you see the flow? Exactly the same flow happens for your code. The difference is that instead of returning a list, mergesort *sorts* a list, and then that is used to replace items in the original list. Personally, their way is a little silly (and mine is inefficient, so use neither). Question: Why did you rewrite the code? Answer: Revising is boring. Question: Sometimes the function execution directly starts from i=0,j=0,k=0 . Not sure how. Answer: That's not a question. Anyhow: i, j and k are LOCAL to a function. "mergesort([2, 4, 0, 1])" has a different i, j and k than "mergesort([0, 1])", They never use each other's i, j and k. Hence for each recursion they run "i=0, j=0, k=0" and they are set to 0 within the function. Does this help? -- http://mail.python.org/mailman/listinfo/python-list
Re: Can anyone please help me in understanding the following python code
On 30 May 2013 11:19, wrote: > Also, Can you please let me know how did you found out that I am using Python > 2 Interpreter. Do you have access to a Python3 interpreter? If so, try running it and your output will look like: Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20] Splitting [54, 26, 93, 17] Splitting [54, 26] Splitting [54] Merging [54] Splitting [26] Merging [26] ... BLAH BLAH BLAH Which is obviously much nicer. This is how Chris knew the code was written for Python3. Therefore I would suggest you use Python3 - not all code runs on both! The "proper" way to write the prints for Python2 is without the brackets: print "Merging ",alist But the methods Chris and I have used work the same on both so are probably better in this case. They're more complicated, though. -- http://mail.python.org/mailman/listinfo/python-list
Re: User Input
On 30 May 2013 15:47, Eternaltheft wrote: >> And perhaps you meant for your function to CALL drawBoard(), rather than >> returning the function object drawBoard. >> >> DaveA > > do you think it would be better if i call drawBoard? Please read http://www.catb.org/esr/faqs/smart-questions.html, or anything similar you can find. Start from the beginning. 1) What are you doing? Not "what are you doing now" but, from the top, what is the goal you are trying to achieve? 2) How have you tried to do it? Code would be nice here too, but don't just send really large blocks of irrelevant code. For example, your "drawBoard" function would be better surmised as: def drawBoard(b): Turtle.speed(0) Turtle.up() Turtle.goto(-4 * b, 4 * b) Turtle.down() for i in range (8): Turtle.forward(b) Turtle.right(90) ... # etc, drawing a board 3) What are you stuck on? In this case, you are stuck on what to do after you call input("stuff"), if I understand. What do you want to do - not "how do you want to do it" but what is it that you are doing? 4) Finally, we should understand what calling drawBoard is for. Ask us again and we'll be much more likely to give good answers. -- http://mail.python.org/mailman/listinfo/python-list
Re: Cutting a deck of cards
On 31 May 2013 12:56, Lee Crocker wrote: > Why on Earth would you want to? "Cutting" a deck makes no sense in software. > Randomize the deck properly (Google "Fisher-Yates") and start dealing. > Cutting the deck will not make it any more random, True > and in fact will probably make it worse depending on how you choose the > cutpoint. I'm pretty sure it won't. Otherwise you'd be lowering entropy by doing a random thing to a random thing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Too many python installations. Should i remove them all and install the latest?
On 3 June 2013 04:18, Chris Angelico wrote: > On Mon, Jun 3, 2013 at 12:30 PM, alex23 wrote: >> On Jun 1, 10:24 am, Chris Angelico wrote: >>> Hmm. What other MUD commands have obvious Unix equivalents? >>> >>> say --> echo >>> emote --> python -c >>> attack --> sudo rm -f >> >> who --> who >> tell --> write >> alias --> ln >> look --> cat >> go --> cd >> teleport --> pushd/popd ? > > I don't use an explicit 'go' though, I usually just type 'n' to go > north, or 'booth1' to go booth1. Unfortunately that doesn't translate > well into a simple alias :) What shell do you use? Zsh supports this (implicit cd). I don't have it active because it's not that useful - you get better completion with explicit cd - but it exists. -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner question
On 4 June 2013 04:39, wrote: > Is there a more efficient way of doing this? Any help is gratly appreciated. > > > import random > def partdeux(): > print('''A man lunges at you with a knife! > Do you DUCK or PARRY?''') > option1=('duck') > option2=('parry') > optionsindex=[option1, option2] > randomizer=random.choice(optionsindex) > while randomizer==option1: > if input() in option1: > print('he tumbles over you') > break > else: > print('he stabs you') > break > while randomizer==option2: > if input() in option2: > print('you trip him up') > break > else: > print('he stabs you') > break > partdeux() I'm going to look directly at the code for my comment, here, and explain what's up. I imagine you were given this code to "fix up", I'll lead you through the steps. > import random You only use "random.choice", never anything else, so in this case I'd be tempted to do: > from random import choice This is *entirely optional*: I tend to do quite a lot of "from import " but others prefer to be more explicit about where things come from; your choice. > def partdeux(): Other than the atrocious name this is as simple as it gets to define a function - you should like that it's a function, though. > print('''A man lunges at you with a knife! > Do you DUCK or PARRY?''') This is iffy! Triple-quotes? Personally this is a really bad time to use them - they break indentation and whatnot. I'd write: >print('A man lunges at you with a knife!') >print('Do you DUCK or PARRY?') This, in my opinion, is much nicer. But we haven't "simplified" much yet. > option1=('duck') > option2=('parry') > optionsindex=[option1, option2] There are two things off about this. Firstly, no-one should be so addicted to brackets to use them here, and you should space variables. > option1 = 'duck' > option2 = 'parry' BUT this is not needed anyway. The next line puts both of these in a variable. You can add them straight in: > optionsindex = ['duck', 'parry'] There are some things wrong though: 1) *Never* lie. This is not an "index" of any sort, unless you're referring to one of these: [http://shop.pageprotectors.com/images/Index-Ring-Binder-2-Rings-Recipe-3x5-Card.jpg] This should be named "options" or, better, "valid_responses". 2) You write "Do you DUCK or PARRY?". None of this suggests uppercase. We shall deal with this later. Thus: > valid_responses = ['duck', 'parry'] > randomizer=random.choice(optionsindex) > while randomizer==option1: ... > while randomizer==option2: This is odd! What do you think this does? This says that you choose an option, "duck" or "parry". If it is "duck", then do A. If it is "parry", then do B. But why would a computer choose options like that? Surely it's better to do: (I'm properly spacing it as I go along, by the way) >randomizer = random.choice([True, False]) >while randomizer: ... >while not randomizer: Oh, that's odd! As randomizer never changes after you set it, you can be sure that the "while randomizer" is equivalent to "while True" or "while False". This means it will loop forever without a break. Looking at the breaks it is clear that *all paths lead to a break*. A while *LOOP* should only ever be used to *LOOP*. This makes the looping redundant. Thus remove the breaks and use: >randomizer = random.choice([True, False]) >if randomizer: ... >if not randomizer: which can be better written: >if random.choice([True, False]): ... >else: (BUT you may have to write "if choice([True, False]):" if you've followed all of my advice) > if input() in option1: "option1" no longer exists, so this is now written: > if input() in valid_responses[0]: BUT why "in"? You want to check whether that *equals* the response, not whether that is *in* the response: > if input() == valid_responses[0]: > else: > print('he stabs you') Why "else"? This means that if you wrote "Seppuku" *he'd* stab you. You want to check that you actually wrote the right thing! > elif input() == valid_responses[1]: > print('he stabs you') This does not work, but we'll fix it later. > if input() in option2: For the same reason, change this to: >if input() == valid_responses[1]: > else: > print('he stabs you') and this to: > elif input() == valid_responses[0]: > print('he stabs you') The rest is better. That leaves you with a much nicer looking function: ### START CODE ### from random import choice def partdeux(): print("A man lunges at you with a knife!") print("Do you DUCK or PARRY?") valid_responses = ["duck", "parry"] if choice([True, False]): if input() == valid_responses[0]: print('he tumbles over you') elif i
Re: How to get an integer from a sequence of bytes
On 4 June 2013 14:39, Grant Edwards wrote: > On 2013-06-03, Dan Stromberg wrote: >> Today though, it would be difficult to sell a conventional (Von Neumann) >> computer that didn't have 8 bit bytes. > > There are tons (as in millions of units per month) of CPUs still being > sold in the DSP market with 16, 20, 24, and 32 bit "bytes". (When > writing C on a TMS320Cxx CPU sizeof (char) == sizeof (int) == sizeof > (long) == sizeof (float) == sizeof (double) == 1. They all contain 32 > bits. ) *) for the bracket not in the reply Sorry. -- http://mail.python.org/mailman/listinfo/python-list
Re: [RELEASED] Python 2.7.5
On 4 June 2013 00:12, Mark Lawrence wrote: > On 03/06/2013 23:37, Carlos Nepomuceno wrote: >> What still doesn't work in Python 3? > > http://python3wos.appspot.com/ Don't take this list too seriously - some of those do have fully working and stable Python 3 packages that just aren't in pip, like python-daemon. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to increment date by week?
On 4 June 2013 22:31, PieGuy wrote: >Starting on any day/date, I would like to create a one year list, by week > (start date could be any day of week). Having a numerical week index in > front of date, ie 1-52, would be a bonus. >ie, 1. 6/4/2013 >2. 6/11/2013 >3. 6/18/2013etc to # 52. > >And to save that result to a file. >Moving from 2.7 to 3.3 > TIA What have you tried? What are you stuck on? We're not here to do your work for you. See http://docs.python.org/3/library/datetime.html for where to get started. -- http://mail.python.org/mailman/listinfo/python-list
Re: Re-using copyrighted code
On 10 June 2013 17:29, llanitedave wrote: > However, I have yet to see an example of source code that qualifies as either > parody or satire under any standard. You should try reading Perl. -- http://mail.python.org/mailman/listinfo/python-list
Re: Split a list into two parts based on a filter?
On 11 June 2013 01:11, Peter Otten <__pete...@web.de> wrote: > def partition(items, predicate=bool): > a, b = itertools.tee((predicate(item), item) for item in items) > return ((item for pred, item in a if not pred), > (item for pred, item in b if pred)) I have to tell you this is the coolest thing I've read today. I'd never have thought of that. -- http://mail.python.org/mailman/listinfo/python-list
Re: "Don't rebind built-in names*" - it confuses readers
On 11 June 2013 01:14, Terry Jan Reedy wrote: > Many long-time posters have advised "Don't rebind built-in names*. > > For instance, open Lib/idlelib/GrepDialog.py in an editor that colorizes > Python syntax, such as Idle's editor, jump down to the bottom and read up, > and (until it is patched) find > list.append(fn) > with 'list' colored as a builtin. Stop. That looks wrong. List.append needs > two arguments: a list instance and an object to append to the list. The > 'solution' is in a previous line > list = [] > Reading further, one sees that the function works with two lists, a list of > file names, unfortunately called 'list', and a list of subdirectories, more > sensibly call 'subdirs'. I was initially confused and reading the code still > takes a small bit of extra mental energy. Idle stays confused and will > wrongly color the list instance name until it is changed. Calling the file > list 'fnames' or 'filenames' would have been clearer to both me and Idle. The problem here is the problem with all of this - names should be descriptive. There is rarely a case where "str" or "string", even, is sufficiently detailed, and "file" often really refers to a "path" for example. You should really not worry about shadowing builtins because if you're using sufficiently long names you almost ne'er accidentally will. In one of my recent posts I was chastised by someone (I remember not who) for overwriting the "property" builtin - obviously this would *never* happen in real life. If you call your property "property" you are a fool. It means nothing! Secondly, shadowing will _almost never_ be a problem, as you invariably, given that you don't use "list" or "str" as variable names, will have shadowed a completely contextually useless variable. And thus, in the one-in-a hundred-in-a-thousand chance that you accidentally shadow a builtin that happens to be important, you can assume that your editor has a half-decent variable replacement mechanism - it's only shadowed in a single scope! But enough of that, you asked about syntax highlighting. Personally, the current method is good - it reminds you when you are shadowing, but does it gently. If you're adamant that the most sensible name for your variable is "format", use it. The highlighting shouldn't be taken to mean "this is from __builtins__", but a little reminder that __builtins__ uses the name. Chances are, you won't be using "format", so do. The little colour change, though, reminds you to check that it really is the best name. Or, well, do what I do and use a proper editor, and set syntax not to highlight keywords if you care enough. My editor makes a good choice only to highlight those keywords that you really don't want to shadow - list, str, etc. - where they're just too vague to be good variable names. "Format"'s unusual and as such do what you want with it. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyWart: The problem with "print"
On 4 June 2013 14:35, Mark Lawrence wrote: > On 04/06/2013 14:29, rusi wrote: >> The Clash of the Titans >> >> Lé jmf chârgeth with mightƴ might >> And le Mond underneath trembleth >> Now RR mounts his sturdy steed >> And the windmill yonder turneth >> > > +1 funniest poem of the week :) Week? Do we do this every Tuesday? I vote all-time best post for python-list@python.org. -- http://mail.python.org/mailman/listinfo/python-list
Re: My son wants me to teach him Python
On 13 June 2013 17:50, Tomasz Rola wrote: > Of course kids are more interesting in things painted on > screen, especially if they are colorful, move and make > sounds at that. The next step would be a simple, > interactive game. > > Which is why I would synthesize something neat yet > simple from http://processing.org/tutorials/ > > Python is overkill for a kid. Ugh. Some people have just > no common sense at all. As someone who can only recently claim to be "not a kid", I will again do my duty and counter this point. GUI is boring. I don't give a damn about that. If I had it my way, I'd never write any interfaces again (although designing them is fine). Console interaction is faster to do and it lets me do the stuff I *want* to do quicker. Also - Python is pretty much the only language that *isn't* overkill; once you take more than the first few steps a language that's *consistent* will help more with learning, á mon avis, than these "quicker" languages ever will. Python is consistent and simple. Then, when you're better and you do want to do cool stuff, Cython/occasionally PyPy/Numpy/Numba etc. let you get C-like speeds learning no other languages at all (although you do need to get C types down). That's the easy way out, not Python-then-C-because-Python-is-slow or some nonsense like that. Basically, "kid" is a *very* generic term and there are people who like GUIs and there are people who like internals and there are hundreds of other classifiers from all over the globe. Please don't conflate groups if you can help it, as it's often just wrong. -- http://mail.python.org/mailman/listinfo/python-list
Re: My son wants me to teach him Python
On 13 June 2013 14:01, rusi wrote: > Some views of mine (controversial!). > > Python is at least two things, a language and a culture. > As a language its exceptionally dogma-neutral. > You can do OO or FP, throwaway one-off scripts or long-term system > building etc > > However as a culture it seems to prefer the OO style to the FP style. > This is unfortunate given that OO is on the down and FP is on a rise. > Some thoughts re OOP: > http://blog.languager.org/2012/07/we-dont-need-no-o-orientation-4.html > > So my suggestion is use some rigorous FPL like Haskell to learn/teach > programming. > After that you can switch to python or some other realistic language. Hey - Haskell is realistic [1]. > Note: I have some serious reservations regarding Haskell > http://blog.languager.org/2012/08/functional-programming-philosophical.html > Nevertheless it seems to be the best there is at the moment. > > tl;dr: Haskell is in 2013 what Pascal was in 1970 -- good for > programming pedagogy. > -- > http://mail.python.org/mailman/listinfo/python-list [1] http://xmonad.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: My son wants me to teach him Python
I don't normally respond to trolls, but I'll make an exception here. On 14 June 2013 04:33, Rick Johnson wrote: > On Thursday, June 13, 2013 3:18:57 PM UTC-5, Joshua Landau wrote: > >> [...] >> GUI is boring. I don't give a damn about that. If I had it >> my way, I'd never write any interfaces again (although >> designing them is fine). Console interaction is faster to >> do and it lets me do the stuff I *want* to do quicker. > > And are you willing to provide *proof* that the console is > faster? Or is this merely just your "opinion"? I would be > ready and willing to compete in a "Pepsi challenge" to > disprove your claim if needed. For instance, if i want to > open a text file on my machine, i merely navigate to the > file via my file browser interface, using clicks along the > way, and then the final double click will open the text file > using it's default program. Are you telling me you can type > the address faster (much less remember the full path) than i > can point and click? And if you think you're going to cheat > by creating an "environment variable", well i can still win > by doing the same thing with a "shortcut". 1) I said it's faster to implement, not faster to use. 2) Yes, I would win that test. Say I want to go to "Projects/Programming Tidbits/FeedLess", I'd write "j Fee". Done. I'm there. What was hard about that? 3) Gee, you think a graphical file manager is good? You should try Ranger. Seriously, it's way better. (Seriously) >> Also - Python is pretty much the only language that >> *isn't* overkill; once you take more than the first few >> steps a language that's *consistent* will help more with >> learning, a mon avis, than these "quicker" languages ever >> will. Python is consistent and simple. > > Your statement is an oft cited misconception of the Python > neophyte. I'm sorry to burst your bubble whilst also raining > on your parade, but Python is NOT consistent. And the more i > learn about Python the more i realize just how inconsistent > the language is. Guido has the correct "base idea", however > he allowed the evolution to become a train wreck. If you ignore stdlib, for a moment, lol. If you include stdlib you're just wrong, but not humorously so. >> [...] >> Basically, "kid" is a *very* generic term and there are >> people who like GUIs and there are people who like >> internals > > Your statement is true however it ignores the elephant in > the room. You can "prefer" console over GUI all day long but > that does not negate the fact that GUI's outperform the > console for many tasks. With the exception of text based > games, the console is as useful for game programming as a > cheese grater is for masturbation -- slightly amusing, but > mostly just painful! I'd like to see you write or do the equivalent of: when-changed $FILE.coffee "coffee -c $FILE.coffee; xclip -selection clipboard < $FILE.js; echo Update" in a GUI. Really, I would. Oh, and then make your result searchable with to all of your other little one-liners, in a process that takes ½ a second to complete. Nevermind that I was talking about console programs being quicker to make this whole time, rather than quicker to use. -- http://mail.python.org/mailman/listinfo/python-list
Re: Eval of expr with 'or' and 'and' within
On 14 June 2013 19:37, rusi wrote: > 2. The recent responses from Robert Kern are in my view the ideal. In > summary it runs thus: > Stupid question no. 6457 from Nikos: ... > Robert : Look this up > Nikos: I dont understand > Robert: explains > Nikos: I DONTU NDERSTND > Robert: explains (repeated as often as needed) > > When (if) finally Nikos actually reads the link and asks a more > specific/intelligent question, can be replaced by more specific > +1 Please, everyone else, just do this. This will calm the beast, I assure you, at least somewhat. If you're worried about not being "helpful", don't - this is as much help as ever. It's just it takes less time, and a *lot* less space. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why 'files.py' does not print the filenames into a table format?
On 15 June 2013 20:51, Nick the Gr33k wrote: > On 15/6/2013 10:46 μμ, Jarrod Henry wrote: >> >> Nick, at this point, you need to hire someone to do your work for you. > > > The code is completely ready. > Some detail is missing and its not printing the files as expected. Look, Nick, A lot of people are frustrated by you. You should understand that. If you cannot, you need to step back and consider, or you really are a troll. Now, obviously it's not going to get you any help to have half of the forum angry at you. People have stopped helping, at least in large. This is fine; people here are volunteers. But you want help. So, Nick, listen. You need to learn how to ask *smart* questions. If you do, I *guarantee* that people will respect you a lot more. I'll be willing to give a bit of time to explain what I mean. 1) What is your problem. Not "I want to know why it doesn't print anything." Here's an example, for some random idea: > I've written some code to find the first file in a directory which > is not UTF-8. Lines 40-42 are meant to print out the file found > to a log ("/home/joshua/.logs/log"). Unfortunately, although > there is no error, no file is printed to the log. 2) What have you tried? What debugging have you done? For someone of your skill level, it's also important to tell us what you think your code is doing. Example: > I've tried checking for a failure - when there is no non-UTF-8 file > in the directory the appropriate error is raised. I think this should > mean that the "else" after the "for" loop would be run, and this > should run the lines 40-42 above when there *is* a non-UTF-8 > file. 3) If possible, give us an example we can run. > To make helping easier, I've removed the code that searches the > directory as I know that works, and instead there's a list of BytesIO > and StringIO objects that pretend to be them. The bug is still > there. Do you see the difference? > Irrelevant to my question i just noticed weird behavior about my > pelatologio.py script which can be seen here: > > http://superhost.gr/?show=stats > > The first 3 files are of my doing. > All the rest are of someone else's that managed to append entries into my > counters database utilizing this code: > > > > try: > #find the needed counter for the page URL > cur.execute('''SELECT ID FROM counters WHERE url = %s''', > page ) > data = cur.fetchone()#URL is unique, so should only > be one > > if not data: > #first time for page; primary key is automatic, hit > is defaulted > cur.execute('''INSERT INTO counters (url) VALUES > (%s)''', page ) > cID = cur.lastrowid#get the primary key > value of the new record > == > > Does someone want to state something? Sure. Here I go: What's the question? -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern Search Regular Expression
On 15 June 2013 11:18, Mark Lawrence wrote: > I tend to reach for string methods rather than an RE so will something like > this suit you? > > c:\Users\Mark\MyPython>type a.py > for s in ("In the ocean", > "On the ocean", > "By the ocean", > "In this group", > "In this group", > "By the new group"): > print(' '.join(s.split()[1:-1])) > > > c:\Users\Mark\MyPython>a > the > the > the > this > this > the new Careful - " ".join(s.split()) != s Eg: >>> " ".join("s\ns".split()) 's s' It's pedantry, but true. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Beginner's Doubt
Please be aware, Augusto, that Rick is known to be a bit... OTT. Don't take him too seriously (but he's not an idiot either). On 19 June 2013 14:58, wrote: > Hello! > This is my first post in this group and the reason why I came across here is > that, despite my complete lack of knowledge in the programming area, I > received an order from my teacher to develop a visually interactive program, > until 20th July, so we can participate in a kind of contest. > > My goal is to learn and program it by myself, as good as the time allows me. > That said, what I seek here is advice from people who definitively have more > experience than me on topics like: is it possible to develop this kind of > program in such a short amount of time? Possible? Yes. It'll be well'ard to get much done with too limited a knowledge base, but it should be possible even then. > What kinds of aspects of Python should I focus on learning? What tutorials > and websites are out there that can help me? What kind of already done > packages are out there that I can freely use, so I do not need to create all > the aspects of the program froms scratch? Neil Cerutti suggested Tkinter. Choosing a good simple GUI toolkit is a good idea over Pygame for something like this. I've used Pygame and I guarantee you it's not the hammer you want. (I don't know much about GUI's to be honest, though.) > It would be wise to give an abstract of the program. I made an information > flux kind of graphic, but I do not know how to post it in here, so I'll use > only words: > Thats basically the whole program. I've been studying Python for a week and > half now, through: How to think like a Computer Scientist and Invent with > Python and Pygame. I'm still at the very beggining, though, and I can't make > much more than make some images appear on a Pygame screen in a menu-like > style, with a patterned gap between them. No mouse interactions up to now. In regards to this, I really would recommend just taking Rick's suggestion: Tkinter; canvas; menu; etc. Now, as I'm probably the most new programmer here I'll point out that I don't agree with Chris when he says that: > One way or > another, you will probably spend the next week writing code you throw > away; if you try to tackle the primary project immediately, you'll > have to rewrite parts of it as you learn. It's easier to throw away a > toy "Hello world" program than hunks of what you thought would be your > final code. As a new programmer, you will throw away code whether or not you practice beforehand. Beware of that. If anything, it's the best thing you can do*. Other than that, he's spot on. Personally, I'd start on the big project sooner rather than later, but not be afraid to dump all the code every now and again. *Anecdote time; a friend of mine who learned VB as his first language wrote as one of his earlier scripts a 2075 line program with no indentation - I still have a copy of that gem tucked away in a very dark corner. Last point; DRY. Look it up and breathe it. People might wonder why I'm making that big a deal about it (it's not the be-all and end-all of anything) but as a new programmer most of your random bits of not-nice-looking code will probably just be a breach of DRY. If you've written the same thing 5 times you've *probably* done it in a not-too efficient manner and the real solution will be the next ladder up in the hierarchy of programming. As someone new, paying a fair bit of attention to this will probably make what you learn some important higher-level concepts faster. Best of luck, I hope I added something helpful. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Beginner's Doubt
On 19 June 2013 17:39, Joel Goldstick wrote: > What is the subject that this teacher of yours teaches? > Do you know anyone who has every done any programming? > Why python? One of those questions is too easy :P. But, no, I'd actually point out that Python might *not* be the best language for the job! *GASP!* *HERETIC* *I'M TELLING!* If you just want a GUI interface program, I'd recommend JavaScript. Heck, if you don't mind the compiler troubles I'd use CoffeeScript. "Why?!" You scream! Well, it's definitely not the language. The GUI toolkit, HTML, however, is ace for really small compatibility-don't-really-matter scripts. A couple old examples from before I "went Python" are attached, not to show off the somewhat lame code but just to point out that even as a new programmer these things were *concise*. That made them so many billions of times easier. Be careful not to mistake the libraries I used for the code I wrote, too. The amount of code *I* wrote for each numbers very few lines (just the main two html files). About half in total was HTML/CSS, so doesn't even count as code. I wrote these for me, so pretend they're licensed strictly. Anything I can give away I do, but it's best to check the licences anyway. Please note that if you don't run these in a modern Chrome/Chromium browser you'll have a bad time - I never bothered with compatibility. Also, apologies for snatching the coffeescript.org coffeescript - but I didn't want to mail a 60KB attachment. Instructions: Guessing the rules is part of the game. They're both thinking games, by the way. For Z-Rox clone, the inspiration is from http://www.kongregate.com/games/evildog/z-rox. How is this relevant to you? Well, JQuery will make what you've written probably just couple of hundred lines. Forget about 2000! This isn't relevant if any of: 1) You have to use python 2) You don't want a silly web interface 3) Any other good reason See http://jqueryui.com/draggable/ for little examples. Examples.tar.gz Description: GNU Zip compressed data -- http://mail.python.org/mailman/listinfo/python-list
Re: python game
This is prob'ly the freakiest thing I've ever run... Anyhoo, I recommend that when you post slabs of code to a mailing list you at least make it runnable for us. We don't have the images. I "fixed" it by doing: | playerImage = pygame.Surface((40, 40)) | bearImage = pygame.Surface((64, 64)) | | playerImage.fill(pygame.Color("red")) | bearImage.fill(pygame.Color("blue")) I'll not just give you answers, here, but try and make you understand what you need to do to make your code shiny. I'll answer your questions on the way, though. On 19 June 2013 21:18, wrote: > I made this game where you move a player over bears, but the bears keep > loading over the plaeyer making it hard to see it, also when i move down the > player goes down to the right > > here is my code: > > import pygame, sys, random > from pygame.locals import * > from threading import Timer You probably want to split up these lines; all the cool kids do: | import sys | import random | import pygame | | from pygame.locals import * | from threading import Timer This is just style; you might wonder why people do this but it's something I've found makes sense in the long run for some reason, and it's recommended as such. > #set up pygame > pygame.init() > mainClock = pygame.time.Clock() > > #set up the window > WINDOW_WIDTH = 400 > WINDOW_HEIGHT = 400 > windowSurface = pygame.display.set_mode((WINDOW_WIDTH, > WINDOW_HEIGHT),0) > pygame.display.set_caption('Get the Bears') > > #set up color constants > BLACK = (0,0,0) > BLUE = (0, 0, 255) Ah! Pygame has a color module. For example, instead of: | windowsurface.fill(BLACK) it's better to do: | windowsurface.fill(pygame.Color("black")) > #set winning text > textFont = pygame.font.SysFont("impact", 60) > text = textFont.render("YOU WIN!", True, (193, 0, 0)) Just a niggle here; it'd be better to call this "win_text" or some other more descriptive name. It's also better to use under_score_names; they're more readable. It took me about a year to realise this, but it's true. It's also recommended. > #set up the player and bear data structures > bearCounter = 0 > NEW_BEAR = 40 > BEAR_SIZE = 64 I'll come back to this later. > playerImage = pygame.image.load('hunter.png') > bearImage = pygame.image.load('bear.png') I replaced this with: | player_image = pygame.Surface((40, 40)) | bear_image = pygame.Surface((64, 64)) | | player_image.fill(pygame.Color("red")) | bear_image.fill(pygame.Color("blue")) Note that I'm changing things like the naming scheme as I go. > player = pygame.Rect(300, 100, 40, 40) Although it's OK to use pygame.Rect as a "player" now, it's not a "player" and you really shouldn't let this be a habit. It'd be better to call this player_rect, or some more useful name. > bears = [] > for i in range(20): > bears.append(pygame.Rect(random.randint(0, WINDOW_WIDTH - BEAR_SIZE), > random.randint(0, WINDOW_HEIGHT - BEAR_SIZE), > BEAR_SIZE, BEAR_SIZE)) Split this up, damnit! | for i in range(10): | x = random.randint(0, WINDOW_WIDTH - BEAR_SIZE) | y = random.randint(0, WINDOW_HEIGHT - BEAR_SIZE) | | bears.append((x, y), (BEAR_SIZE, BEAR_SIZE)) See how this way it's more obvious what it all means, there's no silly line-wrapping *and* it's easier to read. > #movement variables > moveLeft = False > moveRight = False > moveDown = False > moveUp = False > > MOVE_SPEED = 15 ER MER GERD Think about what you're doing here. If I ask you what direction an object on the screen is going in, do you say: 1) Left, about 15 pixels a frame 2) West at 5 klicks per hour 3) Left=True, Right=False, Up=False, Down=False, Speed=15 ? Well, it's not (3). So let us think about this. A good "classical" newbie method, which works for non-newbie stuff too, is just | directions = {"left", "right", "up", "down"} | movement_direction = "left" However, it's not the best. In "programming terms" you'd want variable speed in *both* directions. My preferred method is: | velocity = [the_value_of_x, the_value_of_y] so you'd write above: | velocity = [0, 0] See how nice that is? We'll come back to this later. > #run the game loop > startGame = True > while startGame == True: N! Not you too! You have here a (really weird - I'll come to that later) "infinite" loop. This is best described like so: | while True: | stuff() | if finished(): | break That's what "break" is for, after all. Even better (I think) you can do: | while "game is running": | stuff() | if finished(): | break which explains what you're doing concisely without changing the meaning of the code. A second advantage of this method Plus, if you *insist* on "while FLAG", choose a good name. "startGame" is wrong, because it's not only running during the start of the game. You mean: | while game_running: > #check for quit This is a misplaced comment. > for event in pygame.event.get(): > if event.type == QUIT: >
Re: Problem with the "for" loop syntax
On 19 June 2013 23:53, Arturo B wrote: > Mmmm > > Ok guys, thank you > > I'm really sure that isn't a weird character, it is a space. > > My Python version is 3.3.2, I've runed this code in Python 2.7.5, but it > stills the same. > > I've done what you said but it doesn't work. > > Please Check it again here is better explained: > > http://snipplr.com/view/71581/hangman/ Listen; 1) Post the code in the EMail, not an external link. 2) Don't Top Post. 3) That link doesn't exist. There are so many good hosting sites; why use one that doesn't work? 4) Give us a minimal example. This should be easy; just remove the code above and the code below. This is also a valid debugging technique. 5) Images? Really? -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with the "for" loop syntax
On 20 June 2013 04:11, Cameron Simpson wrote: > Also, opening-and-not-closing a set of brackets is almost the only > way in Python to make this kind of error (syntax at one line, actual > mistake far before). > > See if your editor has a show-the-matching-bracket mode. > If you suspect you failed to close a bracket, one approach is to > go _below_ the syntax error (or right on it) and type a closing > bracket. Then see where the editor thinks the opening one is. Thanks for that, that's quite an ingenious technique. -- http://mail.python.org/mailman/listinfo/python-list
Re: About GIL Questions!
On 20 June 2013 05:13, Thanatos xiao wrote: > Hey everyone! > Recently I see the python source code, but i still not understand about gil. > first, why single core quicker multi-core ? Chris Angelico touched on your other points, but not this as clearly; Python threads run on one thread because they have to. It is not because they're faster. Python theoretically would be faster if its threads could run multicore, but it's really hard to make that work. See http://pypy.org/tmdonate.html for an example of the acrobatics it would take to get a propper GIL-free Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: n00b question on spacing
On 21 June 2013 23:26, Gary Herron wrote: > On 06/21/2013 02:17 PM, Yves S. Garret wrote: >> I have the following line of code: >> log.msg("Item wrote to MongoDB database %s/%s" %(settings['MONGODB_DB'], >> settings['MONGODB_COLLECTION']), level=log.DEBUG, spider=spider) <...> >> I was thinking of splitting it up like so: >> log.msg("Item wrote to MongoDB database %s/%s" >> %(settings['MONGODB_DB'], settings['MONGODB_COLLECTION']), >> level=log.DEBUG, spider=spider) > > This is how I'd do it: (And it's *FAR* clearer -- You win no points for > clarity by having it all in one statement.) > > fmt = "Item wrote to MongoDB database %s/%s" > msg = fmt % (settings['MONGODB_DB'], > settings['MONGODB_COLLECTION']) > log.msg(msg, level=log.DEBUG, spider=spider) Hear, Hear. But really, you should be using .format by now :P My favourite way would be along the lines of: message = "Item wrote to MongoDB database " message += "{0[MONGODB_DB]}/{0[MONGODB_COLLECTION]}".format(settings) log.msg(message, level=log.DEBUG, spider=spider) -- http://mail.python.org/mailman/listinfo/python-list
Re: n00b question on spacing
On 22 June 2013 14:36, Joshua Landau wrote: > message = "Item wrote to MongoDB database " Pedant's note: "Item *written* to MongoDB database" -- http://mail.python.org/mailman/listinfo/python-list
Re: n00b question on spacing
On 22 June 2013 16:24, Rick Johnson wrote: > On Saturday, June 22, 2013 8:36:43 AM UTC-5, Joshua Landau wrote: >> message = "Item wrote to MongoDB database " >> message += "{0[MONGODB_DB]}/{0[MONGODB_COLLECTION]}".format(settings) >> log.msg(message, level=log.DEBUG, spider=spider) > > If you're going to whore out parts of the string to > variables i would suggest going for the gold and actually > make it readable. Erm, as you wish. > Plus, your use of the format syntax is > incorrect. Wut? > _arg1 = settings['MONGODB_DB'] > _arg2 = settings['MONGODB_COLLECTION'] > _fmtstr = "Item wrote to MongoDB database {0}, {1}" > msg = _fmtstr.format(_arg1, _arg2) > log.msg(msg, level=log.DEBUG, spider=spider) > > If you want readability, now you got it. If you say so. -- http://mail.python.org/mailman/listinfo/python-list
Re: n00b question on spacing
On 22 June 2013 14:36, Joshua Landau wrote: > My favourite way would be along the lines of: > > message = "Item wrote to MongoDB database " > message += "{0[MONGODB_DB]}/{0[MONGODB_COLLECTION]}".format(settings) > log.msg(message, level=log.DEBUG, spider=spider) To make a habit of replying to myself, I thought I'd point out I wrote it this way mostly because I have no idea how big "settings" is. If it's not large and only contains keys that are valid identifiers, it'd be more readable to write: message = "Item wrote to MongoDB database " message += "{MONGODB_DB}/{MONGODB_COLLECTION}".format(**settings) log.msg(message, level=log.DEBUG, spider=spider) -- http://mail.python.org/mailman/listinfo/python-list
Re: n00b question on spacing
On 22 June 2013 16:55, Rick Johnson wrote: > On Saturday, June 22, 2013 10:40:24 AM UTC-5, Joshua Landau wrote: >> > Plus, your use of the format syntax is incorrect. >> Wut? > > Well what i mean exactly is not that it's illegal, i just > find the use of the "getattr sugar", from WITHIN the format > string, to be excessively noisy. Sure... So in other words you realised you were wrong but you're too scared to admit it. Eh? That's it, isn't it! You just don't want to loosen your proud persona :P. > In short, i don't care to know WHAT is being injected into > the format string, i simply need to know WHERE it is being > injected. No, I agree. It's never about what you're doing; it's where you are when you do it. > It's about abstractions. It's about not violating the > fundamentals of "templates". Mmhmm, I too treasure these 'fundamentals'. -- http://mail.python.org/mailman/listinfo/python-list
Re: n00b question on spacing
On 22 June 2013 18:28, Alister wrote: > On Sat, 22 Jun 2013 17:11:00 +0100, Joshua Landau wrote: > >> On 22 June 2013 16:55, Rick Johnson >> wrote: >>> On Saturday, June 22, 2013 10:40:24 AM UTC-5, Joshua Landau wrote: >>>> > Plus, your use of the format syntax is incorrect. >>>> Wut? >>> >>> Well what i mean exactly is not that it's illegal, i just find the use >>> of the "getattr sugar", from WITHIN the format string, to be >>> excessively noisy. >> >> Sure... >> So in other words you realised you were wrong but you're too scared to >> admit it. Eh? That's it, isn't it! You just don't want to loosen your >> proud persona :P. > > In this argument I tend to find myself siding with Rick. > Considering his general reputation in this forum am I missing something > or do I need help? ;-) I wasn't mocking the preference against it, but rather that that was completely not what he said originally. One cannot let slip when the mighty Rick misses his mark. That said, yes, it is quite a noisy construct. I still prefer it to: message = "Item wrote to MongoDB database {}/{}" message = message.format( settings['MONGODB_DB'], settings['MONGODB_COLLECTION'] ) log.msg(message, level=log.DEBUG, spider=spider) Because this feels undescriptive - the first and "second" lines feel detached. Instead of Rick's hilarious unpacking, you could always do: message = "Item wrote to MongoDB database {database}/{collection}" message = message.format( database=settings['MONGODB_DB'], collection=settings['MONGODB_COLLECTION'] ) log.msg(message, level=log.DEBUG, spider=spider) Which is probably as good, if longer. You'll see the real problem is that "MONDODB_DB" and "MONGODB_COLLECTION" are awful names; would you really have so detested message = "Item wrote to MongoDB database " message += "{settings[database]}/{settings[collection]}".format(settings=settings) log.msg(message, level=log.DEBUG, spider=spider) or even, now, message = "Item wrote to MongoDB database {settings[database]}/{settings[collection]}" message = message.format(settings=settings) log.msg(message, level=log.DEBUG, spider=spider) ? I think those options are quite nice, á mon avis. I could even write a wrapper (oh noes!): # Shortened for EMail class SettingsWrapper: def uglify_key(self, key): return key if key.startswith("MONGODB") else "MONGODB_" + key.upper() def __init__(self, settingsdict): self.wrapped = settingsdict def __len__(self): return self.wrapped.__len__() def __iter__(self): return self.wrapped.__iter__() def __getitem__(self, key): return self.wrapped[self.uglify_key(key)] def __contains__(self, key): return self.uglify_key(key) in self.wrapped def __setitem__(self, key, value): self.wrapped[self.uglify_key(key)] = value def __delitem__(self, key, value): del self.wrapped[self.uglify_key(key)] settings = SettingsWrapper(settings) message = "Item wrote to MongoDB database {settings[db]}/{settings[collection]}" message = message.format(settings=settings) log.msg(message, level=log.DEBUG, spider=spider) -- http://mail.python.org/mailman/listinfo/python-list
Re: What's wrong with this code? (UnboundLocalError: local variable referenced before assignment)
Here's a little test to make sure you understand (this is one of the most confusing parts of Python's closures in my opinion): foo = "I'm foo!" def working(): print(foo) def broken(): print(foo) if False: # There's no way this could cause a problem! foo = "This will *never* happen" -- http://mail.python.org/mailman/listinfo/python-list
Re: What's wrong with this code? (UnboundLocalError: local variable referenced before assignment)
On 24 June 2013 21:12, John Gordon wrote: > Since you're new to programming, this might be a bit tricky to explain, > but I'll do my best. :-) > > The problem is that change() isn't being executed here; instead it's being > executed from within root.mainloop(), whenever the user presses button-1. > > And within root.mainloop(), there is no variable called isWhite. Sorry, but I don't think you're right. Functions "carry" their contexts around with them, so that shouldn't matter (See Peter and Antoon's comments for explanation of what I think it is) -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this PEP-able? fwhile
On 24 June 2013 20:52, wrote: > Syntax: > > fwhile X in ListY and conditionZ: > > The following would actually exactly as: for X in ListY: > > fwhile X in ListY and True: > > fwhile would act much like 'for', but would stop if the condition after the > 'and' is no longer True. > > The motivation is to be able to make use of all the great aspects of the > python 'for' (no indexing or explict > end condition check, etc.) and at the same time avoiding a 'break' from the > 'for'. There is one good reason not to use breaks: itertools. I often prefer a for-over-a-properly-constrained-iterable to a for-with-a-break, but there's no real reason to ever prefer a while. That said, why add this to the syntax when there's already functionality that gives you what you want? Just use itertools.takewhile as Ian Kelly says. > (NOTE: Many people are being taught to avoid 'break' and 'continue' at all > costs, so they instead convert > the clean 'for' into a less-clean 'while'. Or they just let the 'for' run > out. You can argue against this teaching > (at least for Python) but that doesn't mean it's not prevalent and > prevailing.) We shouldn't make a language around "people are taught the language badly - let us accommodate for their bad practices!" > [People who avoid the 'break' by functionalizing an inner portion of the > loop are just kidding themselves and making > their own code worse, IMO.] > > I'm not super familiar with CPython, but I'm pretty sure I could get this up > and working without too much effort. > The mandatory 'and' makes sense because 'or' would hold the end value valid > (weird) and not accomplish much. > The condition itself could of course have multiple parts to it, including > 'or's. > > It's possible the name 'fwhile' is not optimal, but that shouldn't affect > the overall merit/non-merit of the concept. "Possible"? It's more than just possible, *wink*. > Comments and Questions welcome. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's wrong with this code? (UnboundLocalError: local variable referenced before assignment)
On 24 June 2013 21:19, wrote: > Thank's to you all! > > Setting isWhite as global worked fine. > I'll probably be back soon with another silly question, see you then :) By the way, it's normally bad to use globals like this. When you're learning it's something you just do, though; it's fine for now. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this PEP-able? fwhile
On 25 June 2013 00:13, Tim Chase wrote: > On 2013-06-24 23:39, Fábio Santos wrote: >> On 24 Jun 2013 23:35, "Tim Chase" wrote: >> > On 2013-06-25 07:38, Chris Angelico wrote: >> > > Python has no issues with breaking out of loops, and even has >> > > syntax specifically to complement it (the 'else:' clause). Use >> > > break/continue when appropriate. >> > >> > from minor_gripes import breaking_out_of_nested_loops_to_top_level >> >> for x, y in itertools.product(range(width), range(height)): > > This works nicely for certain use cases, but if there's additional > processing that needs to be done in the outer loops, it starts to get > hairy. As Ian Kelly mentions, I could really dig a labeled > break/continue in Python (it's one of the few ideas I like that Java > made pretty popular; though I can't say I particularly care for > Java's implementation). I'd love to see something like a decorator > where you could do things like the following pseudocode: > > @toplevel > for i in range(height): > for j in range(width): > for component in data[i,j]: > if condition: > continue toplevel > elif other_condition: > break toplevel > else: > other processing > > I'm not sure such a feature would ever arrive, but it would make it > easier than the current recommendation which is usually to either (1) > make inner loops into functions from which you can return; or (2) > raise a custom exception and then catch it in the outer loop. Guido says no; supposedly you can always just use a function. I don't agree, but I'm not Guido. Anyhoo, I prefer: for i in range(height) as toplevel: for j in range(width): break from toplevel Which reads like pure Python gold. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this PEP-able? fwhile
On 24 June 2013 23:50, Chris Angelico wrote: > > In more free-form languages, I implement this by simply omitting a line-break: ... > Python could afford to lose a little rigidity here rather than gain > actual new syntax: > > for i in range(10): if i%3: > print(i) > > And there you are, the for-if "filtered iteration" model, just by > relaxing one rule. Maybe rather: for i in range(10); if i%3: print(i) One of the awesomer things about Coffeescript is: decorator = (f) -> (args...) -> f(args[0]) Which lets you do stuff like: recursive = do -> r = (n) -> if n > 0 then n*r(n-1) else 1 instead of: def recursive_gen(): def recursive(n): return n*recursive(n-1) if n > 0 else 1 return recursive recursive = recursive_gen() Of course, Coffeescript has its own quirks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Limit Lines of Output
On 25 June 2013 21:22, Bryan Britten wrote: > Ah, I always forget to mention my OS on these forums. I'm running Windows. Supposedly, Windows has "more" [http://superuser.com/questions/426226/less-or-more-in-windows], For Linux+less; this works: from subprocess import Popen, PIPE less = Popen("less", stdin=PIPE) less.stdin.write(b"\n".join("This is line number {}".format(i).encode("UTF-8") for i in range(1000))) less.wait() -- http://mail.python.org/mailman/listinfo/python-list
Re: class factory question
On 26 June 2013 15:46, Peter Otten <__pete...@web.de> wrote: > The clean way to > cope with the situation is to use a dict: > > classnames = ["Vspace", ...] > classes = {name: type(name, ...) for name in classnames} > > Then you can access the Vspace class with > > classes["Vspace"] > > If that is inconvenient for your usecase you can alternatively update the > global (module) namespace: > > globals().update((name, type(name, ...) for name in classnames) > > For example: > class A(object): pass > ... globals().update((n, type(n, (A,), {})) for n in ["Beta", "Gamma"]) Beta > issubclass(Beta, A) > True I would say if a dict isn't good, there are still some cases where you might not want to use globals. I _might_ do: import sys from types import ModuleType # As before newclasses = ['Vspace', 'Boldpath', "and so on", "and yes, these all become variables"] little_classes = {name: type(name, (int,), {}) for name in newclasses} # Make a module module_for_little_classes = ModuleType("module_for_little_classes", "All the things") module_for_little_classes.__dict__.update(little_classes) # Hack it in there! sys.modules["module_for_little_classes"] = module_for_little_classes # Now we can undo all import module_for_little_classes as mlc mlc.Vspace mlc.Boldpath ... # And undo all our hard work avoiding globals(): from module_for_little_classes import * Vspace Boldpath So, why avoid globals()? 1) Linters don't like globals() 2) Urm... it's ugly? 3) Ur... -- http://mail.python.org/mailman/listinfo/python-list
Re: Limit Lines of Output
On 25 June 2013 22:48, Gene Heskett wrote: > On Tuesday 25 June 2013 17:47:22 Joshua Landau did opine: I did not. -- http://mail.python.org/mailman/listinfo/python-list
Re: Limit Lines of Output
On 26 June 2013 17:46, Steven D'Aprano wrote: > On Wed, 26 Jun 2013 16:24:56 +0100, Joshua Landau wrote: > >> On 25 June 2013 22:48, Gene Heskett wrote: >>> On Tuesday 25 June 2013 17:47:22 Joshua Landau did opine: >> >> I did not. > > Unless there are two people called "Joshua Landau" with email address > , I'm afraid that you did. Ah, but as rusi has understood, I did not. (Although "I did not" may itself be opining, that was not the quoted text.) Hey, sometimes I just like being cryptic. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help removing trailing zeros
On 26 June 2013 23:02, wrote: > Hello, i'm making a calculator and I want to be able to use decimals but I > don't like it when it comes out as ex.12.0 when it should be 12. I tried > using .rstrip("0".rstrip(".") but that never seemed to work. If anyone has a > solution please let me know, all help is greatly appreciated. > > Code: Was that really necessary? All you needed to give use was "print(1.0)"; why post so much? Either: "{:g}".format(1.0) or, if you hate scientific notation: "{:f}".format(1.0).rstrip(".0") -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help removing trailing zeros
On 26 June 2013 23:21, PyNoob wrote: > Sorry about that... And thanks for your help, but I don't quite understand. That's fine, but... > Would that make it off your example print("{:g}".format(1.0))? I don't understand this sentence. But, hey, I forgot to check what level you were working at -- there's little point running ahead of what you know. Did you try: print("{:g}".format(1.0)) ? It works for me. So, yes, that's what you want. So instead of: print("The quotient of", A, "and", B, "is: ", Answer) you want print("The quotient of", A, "and", B, "is: ", "{:g}".format(Answer)) See how I just used "{:g}".format as some kind of magic-fixing-power? Well, why does it work? [See http://docs.python.org/3/library/stdtypes.html#str.format and the sub-links for a more full explanation] Run each of these in an interpreter: "{} {} {} {} {}".format("This", "is", "a", "formatted", "string!") "It is really useful: I have {} cows and {} sheep".format(number_of_cows, number_of_sheep) "It gives me back a formatted {}, which I can print".format(type("".format()).__name__) "I can also give things indexes: {3} {2} {1} {0}".format("Print", "in", "reverse", "order") "I can also give things names: {egg} {ham} {flies}".format(egg="Are", ham="you", flies="there?") "It's not just {:!<10}".format("that") "It lets me choose how I want things to be printed: {0:@^6}, {0:~>10}, {0:£<8}".format("Hi") "And for numbers: {0:e}, {0:.10%}, {0:#.1f}".format(123.456) So you just want the best formatter; see [http://docs.python.org/3/library/string.html#format-specification-mini-language] Your best choice is "{:g}" which just means "general format". Note that you can also write your prints as so: print("The quotient of {} and {} is: {:g}".format(A, B, Answer)) Whether you prefer it is your choice. -- In regards to .rstrip: It will only work on strings; so you need to convert like so: str(1.0).rstrip("0").rstrip(".") And note that: 1) My .rstrip("0.") was wrong and foolish (try str(10).rstrip("0.")) 2) This needs the string to be reliably formatted in this style: "{:#f}" *and* requires it to be a float. So really, you'd need: "{:#f}".format(float(number)).rstrip("0").rstrip(".") Which is ugly, but I guess it works. -- http://mail.python.org/mailman/listinfo/python-list
Re: class factory question
On 26 June 2013 16:40, Peter Otten <__pete...@web.de> wrote: > Joshua Landau wrote: > >> I would say if a dict isn't good, there are still some cases where you >> might not want to use globals. >> >> I _might_ do: > >> # Make a module >> module_for_little_classes = ModuleType("module_for_little_classes", >> "All the things") >> module_for_little_classes.__dict__.update(little_classes) > > Hm, from within module_for_little_classes that is globals(). To illustrate: > >>>> import __main__ as main >>>> globals() is main.__dict__ > True Yes, that's true - but the point wasn't not to use "globals the function", but not to use *this* global scope. > Also, I'd spell module.__dict__ vars(module). Again, good catch. Definitely that. > That said I agree that it's a good idea to use a dedicated module (not > necessarily created on the fly) for those dynamically generated classes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Limit Lines of Output
On 27 June 2013 00:57, Steven D'Aprano wrote: > On Wed, 26 Jun 2013 10:09:13 -0700, rusi wrote: > >> On Wednesday, June 26, 2013 8:54:56 PM UTC+5:30, Joshua Landau wrote: >>> On 25 June 2013 22:48, Gene Heskett wrote: >>> > On Tuesday 25 June 2013 17:47:22 Joshua Landau did opine: >>> >>> I did not. >> >> I guess Joshua is saying that saying ≠ opining > > But it is. From WordNet: > > opine > v 1: express one's opinion openly and without fear or > hesitation; "John spoke up at the meeting" [syn: opine, > speak up, speak out, animadvert, sound off] To give context; On 25 June 2013 22:48, Gene Heskett (incorrectly) wrote: > On Tuesday 25 June 2013 17:47:22 Joshua Landau did opine: > > > On 25 June 2013 21:22, Bryan Britten wrote: > > > Ah, I always forget to mention my OS on these forums. I'm running > > > Windows. > > > > Supposedly, Windows has "more" > > [http://superuser.com/questions/426226/less-or-more-in-windows], > > Yes, but less is more than more. > > > For Linux+less; this works: > > > > from subprocess import Popen, PIPE > > less = Popen("less", stdin=PIPE) > > less.stdin.write(b"\n".join("This is line number > > {}".format(i).encode("UTF-8") for i in range(1000))) > > less.wait() As you can see, my quoted text contained no *opinions*, at least of the nuance that "opine" refers to. > Admittedly we cannot tell what Joshua's mental state was at the time he > responded to Bryan, he may have been absolutely terrified for all we > know, but there's no sign of this fear, and no reason to think that he > hesitated, given that his response came through a mere nine minutes after > Bryan's comment. That's taking a very analytic turn... To clarify; I did have little hesitation but that was not the grounds to my objection. > Or if you prefer the Collaborative International Dictionary of English: > > Opine \O*pine"\, v. t. & i. [imp. & p. p. Opined; p. pr. & vb. >n. Opining.] [L. opinari, p. p. opinatus; akin to opinus >(in comp.) thinking, and perh. to E. apt: cf. F. opiner.] >To have an opinion; to judge; to think; to suppose. --South. >[1913 Webster] As this accurately sums up, to "opine" requires one to "judge" in some form, or to be "opinionated"; these are not things I did; I rather just referenced someone's work without openly judging it and stated (objectively so, you shall find) that some code worked. >> [Or is he opining?] > > That's just his opinion, man. > > *wink* -- (I wasn't expecting this to spawn so much discourse.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is the argparse module so inflexible?
On 27 June 2013 13:54, Andrew Berg wrote: > I've begun writing a program with an interactive prompt, and it needs to > parse input from the user. I thought the argparse module would be > great for this, but unfortunately it insists on calling sys.exit() at any > sign of trouble instead of letting its ArgumentError exception > propagate so that I can handle it. Overriding ArgumentParser.error doesn't > really help since methods like parse_known_args just send a > message to be relayed to the user as an argument after swallowing > ArgumentError (which does have useful information in its attributes). If I > wanted to figure out what actually caused the exception to be raised, I'd > have to parse the message, which is ugly at best. I understand > that most people do want argparse to just display a message and terminate if > the arguments supplied aren't useful, but there's a lot of > potential in the module that is crippled outside the main use case. I have to > wonder why a module that is meant to be imported would ever > call sys.exit(), even if that is what the caller would normally do if > presented with an exception. >>> import sys >>> try: sys.exit() ... except SystemExit: pass ... >>> That said, you might want to try docopt [http://docopt.org/] if you have qualms with ArgParse. -- http://mail.python.org/mailman/listinfo/python-list
Re: class factory question
On 26 June 2013 14:09, Tim wrote: > I am extending a parser and need to create many classes that are all > subclassed from the same object (defined in an external library). When my > module is loaded I need all the classes to be created with a particular name > but the behavior is all the same. Currently I have a bunch of lines like this: > > class Vspace(Base.Command): pass > class Boldpath(Base.Command): pass > > There are a bunch of lines like that. > Is there a better way? Something like > > newclasses = ['Vspace', 'Boldpath', ... ] > for name in newclasses: > tmp = type(name, (Base.Command,) {}) > tmp.__name__ = name > > Is there a more pythonic way? I've just realised -- why on earth are you doing this? Surely there's a better way than having 50 identical classes. :/ -- http://mail.python.org/mailman/listinfo/python-list
Re: ? get negative from prod(x) when x is positive integers
On 28 June 2013 15:38, Vincent Davis wrote: > I have a list of a list of integers. The lists are long so i cant really > show an actual example of on of the lists, but I know that they contain only > the integers 1,2,3,4. so for example. > s2 = [[1,2,2,3,2,1,4,4],[2,4,3,2,3,1]] > > I am calculating the product, sum, max, min of each list in s2 but I get > negative or 0 for the product for a lot of the lists. (I am doing this in > ipython) > > for x in s2: > print('len = ', len(x), 'sum = ', sum(x), 'prod = ', prod(x), 'max = ', > max(x), 'min = ', min(x)) > > ... > > ('len = ', 100, 'sum = ', 247, 'prod = ', 0, 'max = ', 4, 'min = ', 1) > ('len = ', 100, 'sum = ', 230, 'prod = ', -4611686018427387904, 'max = ', 4, > 'min = ', 1) > ('len = ', 100, 'sum = ', 261, 'prod = ', 0, 'max = ', 4, 'min = ', 1) > > . > > ('prod =', 0, 'max =', 4, 'min =', 1) > ('prod =', 1729382256910270464, 'max =', 4, 'min =', 1) > ('prod =', 0, 'max =', 4, 'min =', 1) > > > > > Whats going on? Let me guess. These are your lists (sorted): [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] You are using numpy.prod() Numpy.prod overflows: >>> numpy.prod([-9223372036854775808, 2]) ... 0 You want to use something that doesn't such as: def prod(iter): p = 1 for elem in iter: p *= elem return p and then you get your correct products: 8002414661101704746694488837062656 3907429033741066770846918377472 682872717747345471717929714096013312 -- http://mail.python.org/mailman/listinfo/python-list
Re: FACTS: WHY THE PYTHON LANGUAGE FAILS.
On 28 June 2013 19:52, Wayne Werner wrote: > On Fri, 28 Jun 2013, 8 Dihedral wrote: > >> KIND OF BORING TO SHOW HOW THE LISP PROGRAMMING >> WAS ASSIMULATED BY THE PYTHON COMMUNITY. >> >> OF COURSE PYTHON IS A GOOD LANGUAGE FOR DEVELOPING >> ARTIFICIAL INTELEGENT ROBOT PROGRAMS NOT SO BRAIN DAMAGES, >> OR SO SLAVERY AS C/C++ OR ASEMBLY PARTS. > > > Best. Post. EVER. Dihedral is the one spammer to this list who I appreciate -- he comes up with spookily accurate gems one day and then hilarious nonsense the next. One could with all the spammers were bots - they seem to post less too. Alas, Dihedral is in a class of his own. -- http://mail.python.org/mailman/listinfo/python-list
Re: FACTS: WHY THE PYTHON LANGUAGE FAILS.
On 28 June 2013 20:35, Joel Goldstick wrote: > > On Fri, Jun 28, 2013 at 3:22 PM, Joshua Landau > wrote: >> >> On 28 June 2013 19:52, Wayne Werner wrote: >> > On Fri, 28 Jun 2013, 8 Dihedral wrote: >> > >> >> KIND OF BORING TO SHOW HOW THE LISP PROGRAMMING >> >> WAS ASSIMULATED BY THE PYTHON COMMUNITY. >> >> >> >> OF COURSE PYTHON IS A GOOD LANGUAGE FOR DEVELOPING >> >> ARTIFICIAL INTELEGENT ROBOT PROGRAMS NOT SO BRAIN DAMAGES, >> >> OR SO SLAVERY AS C/C++ OR ASEMBLY PARTS. >> > >> > >> > Best. Post. EVER. >> >> Dihedral is the one spammer to this list who I appreciate -- he comes >> up with spookily accurate gems one day and then hilarious nonsense the >> next. One could with all the spammers were bots - they seem to post >> less too. >> >> Alas, Dihedral is in a class of his own. >> -- >> http://mail.python.org/mailman/listinfo/python-list > > > I was under the impression that Dihedral is a bot, not a person. Amusing, > none the less Well, yes; I wrote my post knowing that. I was saying with "One could wi[s]h all the spammers were bots - they seem to post less too" that I would rather that other spammers on this list were more like Dihedral -- bots :P. We'd have fewer, much more enlightening posts from them that-a way. -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 29 June 2013 03:07, charles benoit wrote: 1) You haven't asked a question. 2) You posted your code twice. That makes it look a lot harder and longer than it really is. 3) Give us a *minimal* reproducible test case. I currently just get: %~> python2 /tmp/nd.py Traceback (most recent call last): File "/tmp/nd.py", line 12, in finale_line2=finale_line NameError: name 'finale_line' is not defined This isn't the only problem. In other words, you've given us an unsolvable problem. Try again. -- http://mail.python.org/mailman/listinfo/python-list
Re: Closures in leu of pointers?
On 29 June 2013 20:42, Tim Chase wrote: > On 2013-06-29 19:19, Steven D'Aprano wrote: >> Nobody ever asks why Python doesn't let you sort an int, or take >> the square of a list... > > just to be ornery, you can sort an int: > i = 314159265 ''.join(sorted(str(i))) > '112345569' To be yet more ornery, you are merely sorting the string representation of an int. You can sort an int, though: [1].sort() You may say "No! You are sorting a *list*!" However, is it not fair to say that with: [1, 2, 3, 4, 5].sort() you are sorting integers? That is just a common english idiom. Hence, "[1].sort()" sorts an int. > And I suppose, depending on how you define it, you can square a list: >From Wikipedia, "a square is the result of multiplying a number, or other expression, by itself. In other words, squaring is exponentiation to the power 2." This means that the only logical definitions would be "list*list" and "list**2". However, it can be done! class PowList(list): def __pow__(self, other): pass PowList([1, 2, 3])**2 // Because being a pedant is more fun when you're doing it competitively // -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 29 June 2013 18:00, Mark Lawrence wrote: > On 29/06/2013 17:05, Joshua Landau wrote: >> > > Why this when the approach to Nick the Incompetant Greek has been to roll > out the red carpet? I am my own person, and should not be judged by the actions of others. -- http://mail.python.org/mailman/listinfo/python-list
Rough sketch of a PEP for issue2292
In order to get the ball rolling, and because after hours of futzing I still can't get the diff to work (yeah, fine, I'm incompetent), I've started sketching out how a PEP for http://bugs.python.org/issue2292, "Missing *-unpacking generalizations" might look. It's attached if anyone cares to look. You can insult me over it if you want, but I'd prefer if you liked it :P. I also don't mind additions to it if you feel you want to waste some time. If anyone knows how to get the patch (from the bug report) working, or where to find http://code.python.org/python/users/twouters/starunpack after code.python.org was deleted in favour of hg.python.org (which seems not to have it), that'd be nice too. Again, this is a sketch. It's incomplete and I'm likely to replace large parts of it tomorrow. There's also very little justification and, I think, there are too many code blocks. So it's all liable to change. PEP: XXX Title: Additional Unpacking Generalizations Version: $Revision$ Last-Modified: $Date$ Author: Joshua Landau Discussions-To: python-id...@python.org Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 29-Jun-2013 Python-Version: 3.4 Post-History: #TODO Abstract This PEP proposes extended usages of the ``*`` iterable unpacking operator. Specifically: Multiple unpackings:: >>> print(*[1], *[2]) 1 2 >>> dict(**{'x': 1}, **{'y': 2}) {'x': 1, 'y': 2} Unpacking does not prevent further arguments being passed:: >>> print(*[1], 2) 1 2 >>> dict(**{'x': 1}, y=2) {'x': 1, 'y': 2} >>> def f(*args, last): pass Keywords arguments must still follow positional arguments but now must also follow ``*``-unpackings. The function of a lone ``*`` in function definitions is unchanged. Unpacking inside tuples, lists, sets and dictionaries, and comprehensions for iterators, lists, sets and dictionaries:: >>> *range(4), 4 (0, 1, 2, 3, 4) >>> [*range(4), 4] [0, 1, 2, 3, 4] >>> {*range(4), 4} {0, 1, 2, 3, 4} >>> {'x': 1, **{'y': 2}} {'x': 1, 'y': 2} >>> ranges = [range(i) for i in range(5)] >>> [*item for item in ranges] [0, 0, 1, 0, 1, 2, 0, 1, 2, 3] Rationale = Current usage of the ``*`` iterable unpacking operator features somewhat arbitrary restrictions. A limitation of one unpacking per function call makes some function calls more verbose than necessary; instead of:: function(**arguments, **more_arguments) one is forced to write:: kwargs = arguments.copy() kwargs.update(more_arguments) function(**kwargs) or, if they know to do so:: from collections import ChainMap function(**ChainMap(more_arguments, arguments)) This also applies to any circumstance where you would like to unpack positional arguments followed by another positional argument:: function(*args, arg) Function definitions are also now more symmetrical with assignment; whereas previously just:: first, *others, last = iterable was valid, now so too is:: def f(first, *others, last): ... f(*iterable) There are two primary rationale for unpacking inside of containers. Firstly, it would make sense for:: lst = (1, 2, 3, 4, 5) first, *others, last = lst to be the inverse of:: first, others, last = 1, [2, 3, 4], 5 lst = first, *others, last Secondly, it vastly simplifies dictionary "addition" such as:: combination = first_dictionary.copy() combination.update({"x": 1, "y": 2}) and equivalents, as now you can just write:: combination = {**first_dictionary, "x": 1, "y": 2} which is especially important in contexts where expressions are preferred. This can also help replace ``lst + [item]``. Specification = This isn't my forté, so it will take a bit longer. Function calls may accept an unbound number of ``*`` and ``**`` unpackings, which are allowed anywhere that positional and keyword arguments are allowed respectively. In approximate pseudo-notation: :: function_call( [(*args|arg), ]... [(**kwargs|kwarg=), ]... ) The function ``lambda *args, last: ...`` now does not require ``last`` to be a keyword only argument, and thus:: def func(*args, *, keyword_only): ... is valid. Otherwise, function definitions remain unchanged. Tuples, lists, sets and dictionaries now allow unpacking. Dictionaries require ``**`` unpacking, all the others require ``*`` unpacking. A dictionary's key remain in a right-to-left priority order, so ``{**{'a': 1}, 'a': 2, **{'a': 3}}`` evaluates to ``{'a': 3}``. **I am unclear on what t
Re: Stupid ways to spell simple code
On 30 June 2013 07:06, Chris Angelico wrote: > There's a bit of a discussion on python-ideas that includes a function > that raises StopIteration. It inspired me to do something stupid, just > to see how easily I could do it... > > On Sun, Jun 30, 2013 at 3:45 PM, Nick Coghlan wrote: > Re: [Python-ideas] "Iteration stopping" syntax > def stop(): >> ... raise StopIteration > > Here's a much more insane way to spell that: > > stop = (lambda: 0 and (yield 1))().__next__ > > So, here's a challenge: Come up with something really simple, and > write an insanely complicated - yet perfectly valid - way to achieve > the same thing. Bonus points for horribly abusing Python's clean > syntax in the process. > > Go on, do your worst! You'll have to excuse me -- I'm writing a library to do just that. I'll be done in a few weeks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Stupid ways to spell simple code
On 30 June 2013 15:58, Rick Johnson wrote: > Chris, i'm sorry, but your challenge is decades too late. If you seek > amusement you need look no further than the Python stdlib. If you REALLY want > to be amused, peruse the "idlelib" -- not only is the code obfuscated, it > also breaks PEP8 and the PYTHON ZEN many times over. To translate: Not only is the code impossible to read, inefficient and unmaintainable whilst being only shallowly correct, but, *GASP* it sometimes *breaks* semi-arbitrary code *style* *suggestions*! How dare it!‽ -- http://mail.python.org/mailman/listinfo/python-list
Re: Stupid ways to spell simple code
On 30 June 2013 18:36, Steven D'Aprano wrote: > Pfft! Where's the challenge in that? Let's use an O(n!) algorithm for > sorting -- yes, n factorial -- AND abuse a generator expression for its > side effect. As a bonus, we use itertools, and just for the lulz, I > obfuscate as many of the names as I can: > > > from random import shuffle as OOO00O > from itertools import takewhile as OO0O0O, count as O0OO0O > > OO0O00 = range(5) > > list(OO0O0O(lambda O: any(O[O0] < O[O0-1] for O0 in > range(1, sum(('O' for O in O), type('O', (), > {'__add__': lambda O0O, OO0: OO0})()).count('O'))), > (OOO00O(OO0O00) or OO0O00 for O in O0OO0O([0] I've got to say -- that last line got me for quite a while, especially as the list of lists was returning a list of sorted lists! For obfuscation, though, you want unicode. It's much harder to reason about code that you can't read. from itertools import count as æ, permutations as Æ, starmap as ð [globals().setdefault("%c"%sum(ø.encode()),ß)for ø,ß in vars(__builtins__).items()if ø!="vars"] sorted = lambda ħ:ƿ(ƞ for ı in φ(ƴ(lambda:ħ,æ),ń(0,ń(ħ)**(len(ħ)*2-1)*len(ħ)))for ƞ in Æ(ħ)if ǂ(()).__eq__((ŕ(ð(ǂ(Ƽ(ƞ).pop()).__rpow__,φ(ŕ(œ(ƞ,ƴ(lambda:0,ħ)),()),1))),ħ),ı))[::-1] print(sorted([4, -3, 4, 2, -1])) This only works for integers (including negatives) and some things that seem to do nothing but slow it down are needed to cover special cases. This one takes about 3½ minutes on my computer -- it's got a runtime efficiency of something along the lines of O( (L!) * ((L)**i) ) for i being related to the elements in the list and L being the length of the list. That said, it's rather OK at sorting [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]. I know this is more oriented towards obfuscation of code than obfuscation of technique, but --as I said-- I'm writing a library for that. I'll be back when it's ready. -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 30 June 2013 20:58, Robert Kern wrote: > On 2013-06-30 18:24, Νίκος wrote: >> >> Στις 29/6/2013 8:00 μμ, ο/η Mark Lawrence έγραψε: >> >>> Why this when the approach to Nick the Incompetant Greek has been to >>> roll out the red carpet? >> >> >> Your mother is incompetent who raised a brat like you. > > > That is not acceptable behavior on this list. Please keep the gratuitous > insults offlist. As much as you are right, this argument was started by Mark. If you reprimand anyone (other threads being ignored) it should be him. Reacting only to Nick, even though what Nick said was undue, implies that you agree with Mark's actions. Remember that Nick is as much a human as all of us, he is bound to have his feelings hurt when so many people pick on him -- whether they are justified or not. -- http://mail.python.org/mailman/listinfo/python-list
Re: indexerror: list index out of range??
On 29 June 2013 15:30, Mark Lawrence wrote: > > On 29/06/2013 14:44, Dave Angel wrote: >> >> Since you're using the arrogant and buggy GoogleGroups, this >> http://wiki.python.org/moin/GoogleGroupsPython. >> > Please don't make comments like this, you'll upset the Python Mailing List > Police. *doesn't understand* -- http://mail.python.org/mailman/listinfo/python-list
Re: Stupid ways to spell simple code
On 1 July 2013 14:14, Chris Angelico wrote: > On Mon, Jul 1, 2013 at 10:59 PM, Neil Cerutti wrote: >> On 2013-06-30, Chris Angelico wrote: >>> So, here's a challenge: Come up with something really simple, >>> and write an insanely complicated - yet perfectly valid - way >>> to achieve the same thing. Bonus points for horribly abusing >>> Python's clean syntax in the process. >>> >>> Go on, do your worst! >> >> I've often thought it was redundant for Python to support 'if' >> when it has dictionaries, cf the rationale for having no >> 'switch'. >> >> valid_name = None >> while not valid_name: >> name = input("Enter your name: ") >> valid_name = { >> True: lambda: print("No name longer than 20 letters."), >> False: lambda: True, >> }[len(name) > 20]() >> >> Much better. > > Good! Good! But, wh. Wh. > > def get_name(): > while True: > name = input("Enter your name: ") > yield { > True: lambda: print("No name longer than 20 letters."), > False: lambda: name, > }[len(name) > 20]() > name = next(filter(None,get_name())) Oh, cruel. But you can do worse. Who needs "while" when you have filter(iter(FUNCTION, object()))? def get_name(): name = input("Enter your name: ") return [ lambda: name, lambda: print("No name longer than 20 letters."), ][len(name) > 20]() name = next(filter(None, iter(get_name, object( But who needs *any* of this! Defining functions is so old-hat. It's all already in the standard library (using only assignments and function-calls): from functools import partial from operator import getitem, ge, methodcaller from itertools import compress, tee apply = methodcaller("__call__") ret_true = partial(getitem, [True], 0) print_invalid = partial(print, "No name longer than 20 letters.") inputs = iter(partial(input, "Enter your name: "), ...) inputs, valid = tee(inputs) valid = map(len, valid) valid = map(partial(ge, 20), valid) side_effect_valid = map(partial(getitem, [print_invalid, ret_true]), valid) side_effect_valid = map(apply, side_effect_valid) valid_inputs = compress(inputs, side_effect_valid) name = next(valid_inputs) Which can be "neatly" expressed as two statements (I'm struggling to got it to one without those evil lambdas): from functools import partial from operator import getitem, ge, methodcaller from itertools import compress, tee inputs, valid = tee(iter(partial(input, "Enter your name: "), ...)) name = next( compress( inputs, map( methodcaller("__call__"), map( partial( getitem, [ partial(print, "No name longer than 20 letters."), partial(getitem, [True], 0) ] ), map( partial(ge, 20), map(len, valid) ) ) ) ) ) Beautiful, see? Of course, the most powerful function deals with this much more quickly: exec(""" while True: name = input("Enter your name: ") if len(name) <= 20: break else: print("No name longer than 20 letters.") """) -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 1 July 2013 16:49, rusi wrote: > On Monday, July 1, 2013 9:04:11 PM UTC+5:30, Steven D'Aprano wrote: >> > And no, i do not want to piss off people like you, who have spend time >> > helping me. >> Too late. I asked you to stop flaming on-list, and you didn't. I am now >> kill-filing you for a month. Feel grateful that it is not permanent, and >> take this time to reflect that you are running out of people willing to >> help you. > > A suggestion (request??) to all list members in this respect: > > We strengthen Steven's decision as follows: > > For the next month (till 1st August) > - No discussions about Nikos specifically or trolling/flaming in general > - No answers to anything he asks (This does not target you, but is a response to your suggested response) No, it's: 1) Insults and off-topic derogatory are not allowed. That's it. If you're insulted, tough. Take it off-list. If you think it's totally and unabashedly Nikos's fault, tough. Take it off-list. If you think Nikos is completely innocent, tough. Take it off-list. Insults and derogatory are not cool. I thought we were adults. If you choose to ignore Nikos's posts, fine. If you choose like me to wait until he asks questions well, fine. Whatever. That's beside the point. As before. no insults, no derogatory. If you don't get why this is not allowed, you need to step back. To put things in perspective, these are the people who have been insulting on this post: Mark Lawrence (once, probably without meaning to be insulting) Nikos Antoon Pardon And here are the people who have reminded them to stop: Steve Simmons Steven D'Aprano Andrew Berg Walter Hurry rusi Joshua Landau (me) So yes, Antoon Pardon and Nikos, please stop. You are not representing the list. I haven't followed any of the other arguments, true, but you two in particular are causing a lot of trouble for the rest of us. It is not hard to avoid making your disagreements public. -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 1 July 2013 18:15, Νίκος wrote: > Στις 1/7/2013 7:56 μμ, ο/η Joshua Landau έγραψε: > >> So yes, Antoon Pardon and Nikos, please stop. You are not representing >> the list. I haven't followed any of the other arguments, true, but you >> two in particular are causing a lot of trouble for the rest of us. It >> is not hard to avoid making your disagreements public. > > > I promise i will not reply to him any more even if still provoked. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 1 July 2013 19:29, rusi wrote: > On Monday, July 1, 2013 10:26:21 PM UTC+5:30, Joshua Landau wrote: >> So yes, Antoon Pardon and Nikos, please stop. You are not representing >> the list. > > This 'and' is type-wrong. I don't follow. >> I haven't followed any of the other arguments, true, but you >> two in particular are causing a lot of trouble for the rest of us. > > This thread only makes sense in the context of the last year of threads > culminating in the last month of bullshit that this list is drowning under. Yes, but I followed that. What I haven't followed are the probably-100-post-long "wars" that are happening in other threads between specific individuals who I can't be bothered to look up. So I don't know who else has been slandering off of this thread. >> It is not hard to avoid making your disagreements public. > > The reverse is also true in general and more appropriate in this case. > Sometimes the consequences of not speaking up are more tragic than speaking > too much, see > http://en.wikipedia.org/wiki/First_they_came...#The_text That's hardly relevant. Nikos isn't "targeting" any minority. > Yeah sure, abusive posts, derogatory remarks, snide baiting etc is a problem. > > However when you take Alex sarcastic comment > "rename comp.lang.python to comp.support.superhost" > and see the seriousness behind the sarcasm, you would find a considerably > bigger problem -- the python list is stopping to be a python list. No it hasn't. Nikos is a fraction of this list, and over the past while has shrunk far below his peak. The people spewing insults (including Nikos, but he's said he'll stop and I respect him for that) are a much more voluminous sect of this list and a much bigger problem. > In short if you agree and expand on only the first part of my request > >> - No discussions about Nikos specifically or trolling/flaming in general I don't care whether people "discuss" Nikos. I care whether they insult people, flame people and whether they act derogatorily. That is uncalled for. Python-List is known for going off-topic, *but we should not be known for insults*. This is especially true as only two people have been insulting on this thread -- none of the others have endorsed it. If [http://en.wikipedia.org/wiki/First_they_came...#The_text] applies to any situation here, it's your lack of appreciation of the fact that these insults are harming people. > without the second > >> - No answers to anything he asks > > then we are not in agreement. And that is why I disagreed with you. I feel that your post implied either everyone "STFU" or I'm OK with insults. It's not that. It's "STFU", or don't, but insults are not OK. Ever. > Let me end with 2 points: > 1. If this discussion is to go beyond name-calling and over-specific, > under-effective bandaids to getting a real grasp of the problem and hopefully > a real solution, it would be good if people could familiarize themselves with > the paradigm called "tragedy of the commons" > http://www.systems-thinking.org/arch/arch.htm#archtc That doesn't apply here. > 2. Steven's "I am kill-filing you for a month" will have a salutary effect on > all only if we all do it. Good for him. I prefer not to kill-fire - I don't even know how yet - because it's easy enough to ignore posts. But that's fine - it's his choice and it's not a bad one. -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 1 July 2013 20:12, Antoon Pardon wrote: > Op 01-07-13 18:56, Joshua Landau schreef: > >> >> To put things in perspective, these are the people who have been >> insulting on this post: >> >> Mark Lawrence (once, probably without meaning to be insulting) >> Nikos >> Antoon Pardon > > > I don't consider something insulting if it can be supported > by argument and evidence. > > I stand by my statement that Nikos behaved like incompetent > inconsidered jerk can be supported as such. So if this > is insulting it only is in the same matter that the > truth can be insulting. Well then you are wrong. But fine, I'll use your definition incorrect as it may be (when talking to you, please don't misrepresent my other posts). Nevertheless, these statements that we are talking about, that I shall now term "pseudo-insults", are unwanted and not called for. Please keep them off-list. >> And here are the people who have reminded them to stop: >> >> Steve Simmons >> Steven D'Aprano >> Andrew Berg >> Walter Hurry >> rusi >> Joshua Landau (me) >> >> So yes, Antoon Pardon and Nikos, please stop. You are not representing >> the list. I haven't followed any of the other arguments, true, but you >> two in particular are causing a lot of trouble for the rest of us. It >> is not hard to avoid making your disagreements public. > > > Well nobody is representing the list. So where does that leave us? I am afraid you are wrong. The body of people of this list, as a whole, represent this list. As a whole, as I have shown, they resent your pseudo-insults. rusi is an exception, who only seems to resent Nikos's, but rusi has not fallen to pseudo-insults himself (herself?). > And perhaps I am causing a lot of trouble, that doesn't mean I am > wrong. Maybe it is time to question the way this list in general > tries to avoid trouble. Irrelevant. Your pseudo-insults are unwanted. Please stop. Argue all you want - I'm not going to judge who's right. But I'd rather you appreciate that no-one wants your pseudo-insults on this list. -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 1 July 2013 20:18, Antoon Pardon wrote: > Op 01-07-13 17:33, Steven D'Aprano schreef: > >> On Mon, 01 Jul 2013 15:08:18 +0200, Antoon Pardon wrote: >> >>> Op 01-07-13 14:43, Steven D'Aprano schreef: >>> Νίκος, I am not going to wade through this long, long thread to see what problem you are trying to solve today. >>> >>> >>> Nikos is not trying to solve a problem in this thread. What happened is >>> that the original poster here got a rather short answer to his question. >>> Mark Laurence reacted questioning why this person didn't get the same >>> kind of treatment as "Nick the Incompetant Greek". Then Nikos came in >>> with an insulting remark. The rest developed from their. >> >> >> Okay, thank you for explaining the situation. >> >> Now, please stop baiting Nikos. > > > I am not baiting Nikos. I know he mentions this two week period but all > I have done in the last two weeks that involves Nikos as a subject is > the "Don't feed the troll thread" and today this thread. > > So if he feels baited for the last two weeks, it is either by that > "Don't feed the troll" thread or I have very little to do with it. Obviously Steven, as I do, considers your actions in this thread as "baiting". Whether or not you agree with his definition of baiting, he wants you to stop. -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading froma string or list -- back to the question
On 1 July 2013 20:32, Joel Goldstick wrote: > I copied the original question so that the rant on the other thread can > continue. Let's keep this thread ontopic Thank you. I shall do the same below. Unfortunately I don't have high hopes that any progress will be made on this thread -- Charles Benoit hasn't made a single reply since his original post. On 29 June 2013 03:07, charles benoit wrote: 1) You haven't asked a question. 2) You posted your code twice. That makes it look a lot harder and longer than it really is. 3) Give us a *minimal* reproducible test case. I currently just get: %~> python2 /tmp/nd.py Traceback (most recent call last): File "/tmp/nd.py", line 12, in finale_line2=finale_line NameError: name 'finale_line' is not defined This isn't the only problem. In other words, you've given us an unsolvable problem. Try again. -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 2 July 2013 05:34, rusi wrote: > On Monday, July 1, 2013 8:36:53 PM UTC+5:30, Neil Cerutti wrote: >> On 2013-07-01, rusi wrote: >> > 1. Kill-filing/spam-filtering are tools for spam. >> > Nikos is certainly not spamming in the sense of automated >> > sending out of cooked mail to zillions of recipients/lists. >> > His posts are definite and intentional >> >> I disagree. Kill-files are not only for spam. I filter out >> anything I believe I won't want to see. > > I happen to be a champ in using a wrench to hammer screws into bricks. > Others do a better job I am told -- and without being champs :-) That's not really valid, your proposed technique is "use nothing", in which case using a wrench is a golden opportunity. And you've also implied that filtering out what you don't want is akin to hammering screws into bricks, in which case I've been programming wrong my whole programming life. > Tools can be used right... and wrong. Sufficiently extreme wrong use adds to > the original problem/mess. > > Kill-filing is a solution for one problem. In the current context it is much > more the problem than the solution. Two cases: True, kill-filing *is* a solution for one problem. Don't get ahead of yourself, though, by assuming that implies it's not a solution for anything else. > 1. My estimate is that about 30-40 *different* answers-ers in hundreds of > different posts have expressed frustration with dealing with Nikos. The fact > that they are now silent can mean one of two cases: I'm struggling to make those numbers add up. > a. Nikos has turned a new leaf and become a golden boy > b. The protesters have opted out of the discussion/system > (like so-called democracies where 20% of the populace vote and criminals come > to power) First of all, the basis on which you claim there are only two cases is false. Hence this point is void. Secondly: wut? How is any of this a relevant point in the least? > You can take your pick on which case (Hint: Read this thread) > > 2. "I am killfiling you" is bullying behavior. It is worse than useless > because No it is not. You can check the definition of "bully" if you want. Please try not to overuse emotionally rigged terms. > a. The problem cases couldn't care a hoot Nikos has shown that he does, in fact, "care a hoot". > b. Those who could contribute usefully are shut up You wouldn't killfire someone whose posts you want to read. > c. The messengers are being shot as substitute for the culprits If what the messengers are talking unacceptably for your tastes, then by all means you should have right not to listen. Is that not just basic reasoning? People aren't kill-firing because the "messengers" are telling truths we don't want to hear. People are kill-firing because they're doing it in ways that we don't find acceptable. > On the whole we techies have a penchant (may I say allure?) for solving > problems technically rather than socially. > It works well up to a point: > "Thou shall indent thy programs" is a social requirement in C and technical > in python. And so we consider -- rightly -- that python advances C. > > However this line cannot solve all problems. Our belief that technology can > solve all problems is directly linked to the impending fact that the planet > may go up in smoke. Wut? > In short technology in its place is good but conscience is not substitutable: > the use of (tools like) kill-filing analogizes to this piece of medical logic: > > Brain tumor causes headache > Aspirin cures headache > Therefore aspirin cures brain tumors I see no connection. No connection to what this is supposedly an "in short" of (despite being longer) and no connection to the actual point you are trying to make. Basically, I don't understand what you're trying to portray. > tl;dr > > Nikos is not spamming/trolling/baiting/flaming. The Nikos-threads are a more > serious disease than all these. The fact that this thread is not started by > him suggests the disease is spreading. By not speaking up one is colluding. You might want to look up colluding. Basically, rusi, I don't understand you. You seem to speak coherently, but I never know what point you are making, what side you are arguing. You seem to be strongly anti-Nikos, but further than that is opaque to me. What I'm not too fond of, though, is your seeming insistence that your methodology should be rigorously followed by every other party on this list -- we are not a dictatorship, least of all one of your control. As long as we all act civil, and occasionally on-topic, what you do is at your discretion. Plus it's hard to follow someone's command if you haven't the least idea what they're telling you to do. Actually, the one other thing I get from you is that you have the militant view of "we have to all act now in unison to do ". It might explain your odd choice of links. -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 2 July 2013 08:22, Antoon Pardon wrote: > Op 01-07-13 21:28, Joshua Landau schreef: > >> Well then you are wrong. But fine, I'll use your definition incorrect >> as it may be (when talking to you, please don't misrepresent my other >> posts). >> >> Nevertheless, these statements that we are talking about, that I shall >> now term "pseudo-insults", are unwanted and not called for. Please >> keep them off-list. > This doesn't make sense. This means that someone can behave like a jerk > on this list, later tries to spin his behaviour as some innocent exchange > of ideas and make it near impossible for others to make it clear what > bullshit he is peddling because stating clearly how much like a jerk he > > behaved would be insulting. This is giving those who are behaving badly > > a huge advantage. No it does not. I'd give you more of a counter but I actually have no idea how you came up with that. >>> Well nobody is representing the list. So where does that leave us? >> I am afraid you are wrong. The body of people of this list, as a >> whole, represent this list. As a whole, as I have shown, they resent >> your pseudo-insults. rusi is an exception, who only seems to resent >> Nikos's, but rusi has not fallen to pseudo-insults himself (herself?). > You have shown no such thing. You have shown some people who resent > my speaking clearly. I'd prefer you use my less ambiguous term "pseudo-insults". If you'd prefer, you can rename it. Using weasel-words helps nobody. I have no problem with you "speaking clearly" in a literal sense. I have a problem with your pseudo-insults. If you want to use "speaking clearly" to mean "pseudo-insult", you're going to have to point out that you're using words how they're not literally intended. > That doesn't mean much, those that resent > something are always making more noise than those who don't care or > would even prefer it that way. Only the people, no - person, making most noise is you. So you've sort-a countered your point. Sort of. But it's hard to counter a point that is basically just "well, despite the fact no-one supports my view there might be other silent people who do". > But for your ease of mind I'll make it clear I have no intention > of haunting Nikos or of keeping him the subject of discussion. > But should I stumble on a conversation in which his past behaviour > is framed as him being innocentltly asking questions, I will point > of what bullshit that is. Fair enough. If that's all you did in this thread, then I wouldn't care. But once again you seem to have missed the point that I and others keep reiterating: pseudo-insults have no place on this list. (If you need a reminder, pseudo-insults are just what other people term "insults". You can change the name if you see fit.) -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 2 July 2013 13:01, Antoon Pardon wrote: > Op 02-07-13 11:34, Joshua Landau schreef: > >> No it does not. I'd give you more of a counter but I actually have no >> idea how you came up with that. > Please answer the following question. If someone behaved incompetently, > how can I clearly state that fact when "incompetently" is seen as an > insult and insults don't belong on the list? There is not ever a place on this list where you will need to call someone incompetent. You can explain to someone that they do not understand what they are doing, but when you attack the character of the person it is no longer acceptable. >>>>> Well nobody is representing the list. So where does that leave us? >>>> I am afraid you are wrong. The body of people of this list, as a >>>> whole, represent this list. As a whole, as I have shown, they resent >>>> your pseudo-insults. rusi is an exception, who only seems to resent >>>> Nikos's, but rusi has not fallen to pseudo-insults himself (herself?). >>> You have shown no such thing. You have shown some people who resent >>> my speaking clearly. >> I'd prefer you use my less ambiguous term "pseudo-insults". If you'd >> prefer, you can rename it. Using weasel-words helps nobody. >> >> I have no problem with you "speaking clearly" in a literal sense. I >> have a problem with your pseudo-insults. If you want to use "speaking >> clearly" to mean "pseudo-insult", you're going to have to point out >> that you're using words how they're not literally intended. > What if using pseudo-insults was the most clear way to describe the > situation. Should I start looking for eufenisms? No. In that case if you wish to describe the situation you would have to do with less clear means. I'm sure the people on this list would understand what you mean even if you left out the judgementalism. In this case in particular, many other people have "described the situation" perfectly adequately without resorting to blatant insults on Nikos. But how is a statement as blatantly inhumane as "Should we particularly care about Nikos's feelings?" a needed action -- it certainly isn't a good way of describing the situation. >>> But for your ease of mind I'll make it clear I have no intention >>> of haunting Nikos or of keeping him the subject of discussion. >>> But should I stumble on a conversation in which his past behaviour >>> is framed as him being innocentltly asking questions, I will point >>> of what bullshit that is. >> Fair enough. If that's all you did in this thread, then I wouldn't care. >> >> But once again you seem to have missed the point that I and others >> keep reiterating: pseudo-insults have no place on this list. >> >> >> (If you need a reminder, pseudo-insults are just what other people >> term "insults". You can change the name if you see fit.) > So what are the non-insulting terms for > > incompentent, (starting a webservice in a language you're a newby in, > making changes on the life server so that any typo you make, can take > your site out the air), You just did it. > inconsiderate (behave annoyingly in multiple ways and despite poeple pointing > it out multiple times, mostly continue in the same manner, without taking > their remarks into account) and I do not tend to consider "inconsiderate" inappropriate if said in earnest, as it is defensive. I'd still rather you talked about actions as inconsiderate rather than people, but baby steps. > jerk (trying to spin your inconsiderate behaviour as you being the victim, > misrepresenting your behaviour when it is being discussed, always "explaining" > your behaviour, as if an explanation would make a difference to the annoyance > you caused to others...) You came close. But, since Nikos has thankfully ceased, I'm saying here that unless you have good reasons otherwise I'd rather only continue this off-list. If you reply on-list without justification I will likely not reply. Apologies to everyone else for the clutter this has caused. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python list code of conduct
On 2 July 2013 16:51, Steve Simmons wrote: > Erm, > > It probably isn't the best time to start this post but I was wondering... > > Does this list have a code of conduct or a netiqeutte (sp?) > statement/requirement? > > If not, should it? > > Is the membership of this list presently in the right frame of mind to > create one or update any existing one? > > The reason I ask is that it seems to me that if we (the current membership > of the list) could agree to a set of preferred/required behaviours we would > at least have a framework by which to measure unwelcome posts. And, more > importantly, to guide newcomers in understanding that we are enthusiasts who > choose to discuss Python and *voluntarily* help solve problems with Python > for the less experienced members. I don't know if we do and I'll support such measures (pending that they're done intelligently) but unfortunately there seem to be at least two problems with your plan. - There seems to be no authority for upholding such rules - Newbies never read around That said, the idea itself is well grounded. I'd suggest stealing the rules Python already has somewhere. -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing Text file
On 2 July 2013 20:50, Tobiah wrote: > How do we know whether we have Sometext? > If it's really just a literal 'Sometext', then > just print that when you hit maskit. > > Otherwise: > > > for line in open('file.txt').readlines(): > > if is_sometext(line): > memory = line > > if line == 'maskit': > print memory My understanding of the question follows more like: # Python 3, UNTESTED memory = [] for line in open('file.txt').readlines(): if line == 'maskit': print(*memory, sep="") elif line: memory.append(line) else: memory = [] -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing Text file
On 2 July 2013 21:28, wrote: > Here I am looking for the line that contains: "WORK_MODE_MASK", I want to > print that line as well as the file name above it: > config/meal/governor_mode_config.h > or config/meal/components/source/ceal_PackD_kso_aic_core_config.h. > > SO the output should be something like this: > config/meal/governor_mode_config.h > > #define GOVERNOR_MODE_WORK_MODE_MASK(CEAL_MODE_WORK_MASK_GEAR| \ >CEAL_MODE_WORK_MASK_PARK_BRAKE | \ >CEAL_MODE_WORK_MASK_VEHICLE_SPEED) > > config/meal/components/source/kso_aic_core_config.h > #define CEAL_KSO_AIC_WORK_MODE_MASK (CEAL_MODE_WORK_MASK_GEAR | \ >CEAL_MODE_WORK_MASK_PARK_BRAKE | \ >CEAL_MODE_WORK_MASK_VEHICLE_SPEED) (Please don't top-post.) filename = None with open("tmp.txt") as file: nonblanklines = (line for line in file if line) for line in nonblanklines: if line.lstrip().startswith("#define"): defn, name, *other = line.split() if name.endswith("WORK_MODE_MASK"): print(filename, line, sep="") else: filename = line Basically, you loop through remembering what lines you need, match a little bit and ignore blank lines. If this isn't a solid specification, you'll 'ave to tell me more about the edge-cases. You said that > #define CEAL_KSO_AIC_WORK_MODE_MASK (CEAL_MODE_WORK_MASK_GEAR | \ >CEAL_MODE_WORK_MASK_PARK_BRAKE | \ >CEAL_MODE_WORK_MASK_VEHICLE_SPEED) was one line. If it is not, I suggest doing a pre-process to "wrap" lines with trailing "\"s before running the algorithm: def wrapped(lines): wrap = "" for line in lines: if line.rstrip().endswith("\\"): wrap += line else: yield wrap + line wrap = "" ... nonblanklines = (line for line in wrapped(file) if line) ... This doesn't handle all wrapped lines properly, as it leaves the "\" in so may interfere with matching. That's easily fixable, and there are many other ways to do this. What did you try? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to calculate reputation
On 2 July 2013 22:43, Surya Kasturi wrote: > Hi all, this seems to be quite stupid question but I am "confused".. > We set the initial value to 0, +1 for up-vote and -1 for down-vote! nice. > > I have a list of bool values True, False (True for up vote, False for > down-vote).. submitted by users. > > [True, False, False, True] > > Now to calculate the total reputation > > should I take True = +1, False=0 [or] True = +1, False=-1 ?? for adding > all. > > I am missing something here.. and that's clear.. anyone please help me on > it? It depends what you want to do. I suggest http://www.evanmiller.org/how-not-to-sort-by-average-rating.html. This aint so simple, but it's the correct way to sort by "approval". In fact, it's bloody confusing. To assume that only the "sum" approval counts, I'd not suggest {True: 1, False: 0}. The problem is that a "downvote" then becomes pointless. So probably go with False as -1. So you'd want: sum((1 if vote else -1) for vote in votes) -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 2 July 2013 23:34, Ben Finney wrote: > > Joshua Landau writes: >> There is not ever a place on this list where you will need to call >> someone incompetent. > > So even if that term describes their behaviour and manner, you think > no-one should ever point it out? Yes. I see no instance where it would be needed or helpful. >> > So what are the non-insulting terms for >> > >> > incompentent, (starting a webservice in a language you're a newby in, >> > making changes on the life server so that any typo you make, can take >> > your site out the air), >> >> You just did it. > > So you agree the correct term to use *is* “incompetent”, as Anton said. > Yet you don't want Anton to use the correct term. What? No, I think you misread what I intended in that post. I said that rather than attacking Niko's integrity by calling him incompetent, it is better to, for example, explain to him that he is "starting a webservice in a language you're a newby in, making changes on the life server so that any typo you make, can take your site out the air". Given, of course, that that is what prompted you to want to call him incompetent in the first place. Saying "you don't understand what you are doing" and "you are incompetent" are in this case interchangeable, except one involves making the other feel hurt. You don't need to do that, nor does it help anyone. > Needless to say, I disagree with your position. There is no place for > baseless insults in this community; but when the behaviour of someone in > this community is harmful, then it is entirely appropriate to use clear > terms (e.g. “incompetent”, “inconsiderate”) to describe their behaviour. Firstly, describing someone's behaviour and describing someone's character are two completely different things. The second is far more judgemental and unhelpful than the first. Antoon is describing people's character. You are talking about describing their actions. Secondly, as I said, I have few objections to the term "inconsiderate". Fewer still when describing a behaviour. As for calling someone incompetent, it would be wrong to associate incompetence with harm to this community. People were not upset -- at least I was not upset -- from Nikos being incompetent. Many people on this list lack skills. This is fine, everyone's unlearnt at some point. Some stay unlearnt forever. People were upset because of his manner, his demanding, his overbearing, him acting selfishly, etc. I will never complain to you calling someone rude, especially not calling someone's actions rude. I will never complain to you calling someone overbearing, especially not calling someone's actions overbearing. I will never complain to you calling someone's actions selfish. etc. I may disagree, and I may voice disagreements, but you have right to speak up if you feel mistreated. Please don't believe I think otherwise. Calling someone incompetent is an attack, and is not the same. If you cannot see the difference, I'm not sure what more I can say. I feel it is reasonable to continue my correspondence with you on-list, but if it spawns more than a few more posts I would rather take it off-list. I have no objections if you would like to Cc Antoon Pardon in the process, seeing as it's his post involved. -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Parser
On 2 July 2013 18:43, wrote: > I could not use BeautifulSoup as I did not find an .exe file. Were you perhaps looking for a .exe file to install BeautifulSoup? It's quite plausible that a windows user like you might be dazzled at the idea of a .tar.gz. I suggest just using "pip install beautifulsoup4" at a command prompt. See http://stackoverflow.com/questions/12228102/how-to-install-beautiful-soup-4-with-python-2-7-on-windows for explanations -- there are links for things you need to know. But basically, use BeautifulSoup. It does what you need. -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 3 July 2013 01:36, Ben Finney wrote: > I think we've found the root of > the disagreement. I've made my position clear and will let it rest there. Seconded. > Thanks for caring enough about this community to act in the > interest of keeping it open, considerate, and respectful. Thank you in turn. -- http://mail.python.org/mailman/listinfo/python-list
Re: Bug reports [was Re: Python list code of conduct]
On 3 July 2013 01:52, Steven D'Aprano wrote: > If you are a beginner to a programming language, assume that anything > that doesn't work the way you expect is a bug in YOUR code, or YOUR > understanding, not in the language. Not just beginners. Out of the hundreds of times where I've gone "this *can't* make sense", I think only one -maybe two- was an actual bug in Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to calculate reputation
On 2 July 2013 23:19, Surya Kasturi wrote: > > I think I didnt explain it clearly.. let me make it clear.. Yeah... I don't get it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator help
On 3 July 2013 23:09, Joseph L. Casale wrote: > I have a set of methods which take args that I decorate twice, > > def wrapped(func): > def wrap(*args, **kwargs): > try: > val = func(*args, **kwargs) > # some work > except BaseException as error: > log.exception(error) > return [] > return wrap > > def wrapped_again(length): > def something(func): > def wrapped_func(*args, **kwargs): > values = func(*args, **kwargs) > # do some work > return values > return wrapped_func > return something > > So the methods wrapped are as follows: > > @wrapped_again(12) > @wrapped > def class_method(self, **kwargs): > # > > Is it possible to get the name of the original method (class_method) from > within wrapped_func inside wrapped_again? > Thanks! Normally you'd want to use functools.wraps; def wrapped(func): @functools.wraps def wrap(*args, **kwargs): ... return wrap def wrapped_again(length): @functools.wraps def something(func): ... return something @wrapped_again(12) @wrapped def class_method(self, **kwargs): And then the name is "carried", as with docstrings. If you don't want to do that, you'd need to use introspection of a remarkably hacky sort. If you want that, well, it'll take a mo. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator help
On 3 July 2013 23:19, Joshua Landau wrote: > If you don't want to do that, you'd need to use introspection of a > remarkably hacky sort. If you want that, well, it'll take a mo. After some effort I'm pretty confident that the hacky way is impossible. -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 3 July 2013 02:21, wrote: > On 07/02/2013 05:18 PM, Joshua Landau wrote: >> On 2 July 2013 23:34, Ben Finney wrote: >>[...] >>> Needless to say, I disagree with your position. There is no place for >>> baseless insults in this community; but when the behaviour of someone in >>> this community is harmful, then it is entirely appropriate to use clear >>> terms (e.g. “incompetent”, “inconsiderate”) to describe their behaviour. >> >> Firstly, describing someone's behaviour and describing someone's >> character are two completely different things. The second is far more >> judgemental and unhelpful than the first. Antoon is describing >> people's character. You are talking about describing their actions. > > In practice there is often little difference. "You are acting > like an asshole" could be defended as describing a behavior > and "you are rude" as describing a character (rude by nature). "You are acting like an asshole" *is* describing someone's behaviour. "You are an asshole" is the equivalent describing their character. In turn, "You are rude" *is* describing their character. However, I said the "second is far more judgemental and unhelpful than the first". I stand by that, but don't take that to mean that comments on people's behaviour cannot be insulting of derogatory, nor that comments on character have to be insulting. Calling someone rude may be worse than saying that they are acting rude, but it is not unjust if they have been rude, for example. > The reality is that few of the people at whom such statements > are aimed will make such fine distinction. If you use negatively > judgemental statements against other posters, a significant > number of them will respond to you in kind. I think most people will take "you are stupid" and "what you've done is stupid" to have very different levels of hostility, even though the same thing to be said has been expressed. That does not mean people will not take offense at the second, but they will take less. I believe that this does generalise. Note that I am not advocating calling people's actions stupid, as it is still just a harsher way of saying "you've made a mistake". -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 3 July 2013 11:01, Antoon Pardon wrote: > Op 02-07-13 15:40, Joshua Landau schreef: >> On 2 July 2013 13:01, Antoon Pardon wrote: >>> >> >> There is not ever a place on this list where you will need to call >> someone incompetent. You can explain to someone that they do not >> understand what they are doing, but when you attack the character of >> the person it is no longer acceptable. > > This is not an attack of character. Level of skill/competence is > not in general seen as a character trait. I disagree. I'm not sure how to argue this, rather than point out that by "character trait" I'm not talking about "intrinsic trait" but rather "revolving around who you are". The alternative I posed is talking about things revolving around specific actions that you have taken. > It is something one can > generally increase if one is willing to work on it, and once > you acquired it, you don't have to keep your guard for situations > in which you might loose it. That's not relevant to whether it's a character trait, á mon avis. >>> So what are the non-insulting terms for >>> >>> incompentent, (starting a webservice in a language you're a newby in, >>> making changes on the life server so that any typo you make, can take >>> your site out the air), >> You just did it. > > But how do I describe this in one word? What conclusion am I allowed > to make from all this? That it's worth taking a little more time doing things if it makes sure you aren't harming the person on the other end. > Can I say: > He displayed a pattern of incompetence? WIth trepidation. Saying what someone did is "incompetent" is quite judgemental. > He has been blundering about? With trepidation. This is just another way of saying the same thing. > His skill level was unimpressive? With trepidation. This refers to his character, but is still quite light and far lower than the level of aggression that spawned my speaking-up. > The skill level he displayed, left much to be desired? Probably. Except only if you remove the comma. Bear in mind that if the way you were acting was all in my "with trepidation" category, I would likely have not spoken up. I believe you crossed a lot further beyond that line. >>> inconsiderate (behave annoyingly in multiple ways and despite poeple >>> pointing >>> it out multiple times, mostly continue in the same manner, without taking >>> their remarks into account) and >> I do not tend to consider "inconsiderate" inappropriate if said in >> earnest, as it is defensive. I'd still rather you talked about actions >> as inconsiderate rather than people, but baby steps. > > I don't understand this, since (in)consideration is in general seen as > a character trait. On that basis I think you have it exactly backwards > when you consider "incompetent" an attack of character yet seem to > have little problem with "inconsiderate". "You are inconsiderate" is describing someone's character. Hence I believe it would be better to say "what you did was inconsiderate". What I was saying, though, is that because "inconsiderate" is defensive and reactionary it is not an insult*. It refers to the fact that you believe the person you say it to should respect other people and what he is doing negatively impacts them. Another example would be: "you are awesome". Despite being a description of character, I'm not too idiotic to realise that it is not a mean thing to say. (Even here, "what you did is awesome" is a *milder* way of saying the same idea.) It's easy to misread what I've said, but I was never trying to imply that my problem was solely in this distinction -- it was just that it's important to realise that the divide exists and very explanatory to some aspects of how people take commentary. Both rurpy and you seem to have mistaken me to believe that describing character vs. describing actions is the be-all and end-all. Rather, I just believe it is a large factor in the harshness of what you say. *You seem to have moved back to the term "insult"; this seems especially appropriate since we are discussing its meaning. > Yet people who have a more > inconsiderate character can't work on acquiring consideration, as one > can on acquiring skill/competence. Sure one can work on it, but it is > something you have to keep watchful for. Otherwise you can easily slip > again into a pattern of being/behaving inconsiderate. Firstly, I disagree. Consideration is a learnt trait as most human interaction is. Secondly, I don't understand why you are bringing this up. >>
Re: Why this code works in python3, but not python 2:
On 4 July 2013 04:52, Maciej Dziardziel wrote: > Out of curiosity: Does anyone know why the code below is valid in python3, > but not python2: > > def foo(*args, bar=1, **kwargs): > pass Python 3 gained syntax for keyword-only arguments. Try "foo(1)" and it will fail -- "bar" needs to be given as a keyword. This is because it comes after a *-expression. You can also do "def foo(*, bar=1)" if you want bar to be keyword-only without accepting any number of positional arguments. Python 2 does not have these, and doesn't understand the syntax for them. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default scope of variables
On 4 July 2013 05:07, Chris Angelico wrote: > On Thu, Jul 4, 2013 at 1:27 PM, Steven D'Aprano > wrote: >> With respect to the Huffman coding of declarations, Javascript gets it >> backwards. Locals ought to be more common, but they require more typing. >> Locals are safer, better, more desirable than globals, and so it should >> be easier to use locals than globals, not the other way around. Having to >> declare "give me the safe kind of variable", while getting the harmful[1] >> kind of variable for free, strikes me as arse-backwards. Lazy, naive or >> careless coders get globals[2] by default or accident. That's bad. > > I agree that Javascript has it wrong, but not quite for the reason you > say. The advantage of declaring locals is a flexibility: you can have > multiple unique variables with the same name in the same function. > Python lets you do that across but not within functions. > > But Javascript/ECMAScript/whatever doesn't give you that. A var > declaration makes it function-local, no matter where the declaration > is. Coffeescript, which compiles to Javascript, "fixes" the problem Steven brought up by automatically declaring variables so that you don't have to. But what do you think this does?: a = 1 func = -> a = 2 b = 2 The "a" in "func" is global, the "b" is local. And Coffeescript *doesn't let* you shadow even if you explicitly want to. There just isn't syntax for it. That said, I'm not too convinced. Personally, the proper way to do what you are talking about is creating a new closure. Like: for i in range(100): with new_scope(): for i in range(100): func(i) func(i) # Using i from original loop But it's not like Python'll ever support that. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default scope of variables
On 4 July 2013 05:36, Chris Angelico wrote: > On Thu, Jul 4, 2013 at 2:30 PM, Joshua Landau > wrote: >> That said, I'm not too convinced. Personally, the proper way to do >> what you are talking about is creating a new closure. Like: >> >> for i in range(100): >> with new_scope(): >> for i in range(100): >> func(i) >> func(i) # Using i from original loop >> >> But it's not like Python'll ever support that. >> > > def foo(): > for i in range(3): > print("outer",i) > def inner(): > for i in range(4): > print("inner",i) > inner() > print("outer",i) > > That works, but you then have to declare all your nonlocals, and it > hardly reads well. Unfortunately that's what people, I included, end up doing. Stuff like: def paranoia(...): def safe_recursive(...): safe_recursive(...) return safe_recursive safe_recursive = paranoia() is blimmin ugly. Then you're only really left with class safe_recursive: def __call__(self, ...): self(...) which only solves it for recursive functions. I guess this means I actually agree with your sentiment, just not the specifics. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why this code works in python3, but not python 2:
On 4 July 2013 05:47, alex23 wrote: > On 4/07/2013 2:12 PM, Joshua Landau wrote: >> >> On 4 July 2013 04:52, Maciej Dziardziel wrote: >>> >>> def foo(*args, bar=1, **kwargs): >>> pass > > >> Try "foo(1)" and it will fail -- "bar" needs to be given as a keyword. > > > No it won't, because it is supplied with a default. Pah! I'm not even thinking. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default scope of variables
On 4 July 2013 17:54, Rotwang wrote: > 53*(63**100 - 1)//62 Or about 10**10**6.255 (so about 1.80M digits long). For the unicode side (Python 3, in other words) and reusing your math (ya better hope it's right!), you are talking: 97812*((97812+2020)**100 - 1)/(97812+2020-1) Or about 10**10**6.699 Which has about 5.00M digits. Good luck running out. -- http://mail.python.org/mailman/listinfo/python-list
Re: Important features for editors
On 4 July 2013 08:32, cutems93 wrote: > I am researching on editors for my own reference. I found that each of them > has some features that other don't, but I am not sure which features are > significant/necessary for a GOOD editor. What features do you a good editor > should have? Keyboard shortcuts? Extensions? Let me give you some reasons I really, really like Sublime Text. * Fast. Like, really fast. I've used Vim -- Sublime Text is faster. Considering I'm on a middle-end 5-year-old computer (not for long...) this matters. * The rendering is gorgeous. There are subtle shadows, there's perfectly crisp text (the main reason I no longer use terminal editors, actually), and once you choose the right theme (Nexus and Phoenix, Tomorrow Night for me) it's just lovely. There's this feature where it shows you tabs -- but only for the part of the file you're on. There's, instead of a scrollbar, a little "bird's-eye-view" of the whole code on the RHS. This goes on. Visually it is stunning, in a helpful way. If it had proper terminal-emulation support, I'd replace my terminal with it. It's just that usable an interface. * Multiple cursors. This is something that no-one else really advertises, but it's one of the most used features for me. It's something you just have to try for a while -- I think it's a bit like Vim's power-of-Regex but easy for a, you know, human. (I just found https://github.com/terryma/vim-multiple-cursors). * Good navigation between and inside of files. A lot of things have this, so I won't say much more. * The "Command Palette" is a dropdown that you do commands from, and because of the way you search it, it's like a hybrid between vim's command-based power and something that's actually discoverable and easy. * Usable on *really big* files, and has one of the best binary-file support I know of. I open binary file a little more than I should, not that I can do much with them. * Useful extensions, installable at a button-press -- in[search for package]. Like SublimeREPL. I know Emacs/Vim will do better at REPLs, but few others will. * Etc. This goes on. Looking at Dave Angel's list, Sublime Text pretty-much aces it. What I don't understand is where he says: > The main negatives I can see are: ... > It's available for OS/X, Linux and Windows, with a single purchase > The eval/demo is not time-limited (currently) How on earth are those negatives? He basically only dislikes it because you have to use PayPal, which is his choice. I can't say I agree with it though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator help
On 4 July 2013 06:39, Peter Otten <__pete...@web.de> wrote: > Joshua Landau wrote: > >> On 3 July 2013 23:19, Joshua Landau wrote: >>> If you don't want to do that, you'd need to use introspection of a >>> remarkably hacky sort. If you want that, well, it'll take a mo. >> >> After some effort I'm pretty confident that the hacky way is impossible. > > Well, technically it's > > func.func_closure[0].cell_contents.__name__ > > but of course you cannot know that for the general case. I didn't want to do something like that as it implies a lot of knowledge about the function -- which implies that there's no reason to do it hacky in the first place. I was using "inspect.getclosurevars(func).nonlocals" and that "coerces" to a dictionary first. It's the "correct" way of doing things. But you never know what name the function inside the wrapper is bound to, so I didn't accept that. Also, your method has undefined behaviour AFAIK -- the order of func_closure is compiler-dependant. If you want to do something like this, I recommend my method (but it doesn't work for the general case in the slightest): inspect.getclosurevars(func).nonlocals["func"].__name__ If you can't assume the name it's stored in, but you can know the order of closure variables *then* use Peter's. But again, don't use either; it's impossible just as I said. -- http://mail.python.org/mailman/listinfo/python-list
Re: First attempt at a Python prog (Chess)
Just a minor suggestion: def display_board(board): print ' a b c d e f g h' print '+---+---+---+---+---+---+---+---+' for row in range(8): for col in range(8): piece = board[row * 8 + col] if piece_type[piece] == WHITE: print '| \x1b[31;01m%c\x1b[39;49;00m' % board[row * 8 + col], else: print '| \x1b[34;01m%c\x1b[39;49;00m' % board[row * 8 + col], print '|', 8 - row print '+---+---+---+---+---+---+---+---+' -- http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 4 July 2013 12:19, Antoon Pardon wrote: > Op 04-07-13 01:40, Joshua Landau schreef: > >> Bear in mind that if the way you were acting was all in my "with >> trepidation" category, I would likely have not spoken up. I believe >> you crossed a lot further beyond that line. > > I had to look up "trepidation" and the translation I got from my > dictionary was not 100% helpful. Would "hesitation" or "wariness" > be a good substitute. Yes; it's along the lines of "hesitation /due/ to wariness". > Can we go back to my first entry in this thread? I would like to > know whether you think that already crossed the line or if that > would fall under your "with trepidation" category and I crossed > the line later. > > I think the relevant part is this: > > ] Maybe that way he'll learn that if he doesn't want to be considered > ] an incompetent inconsiderate jerk, he shouldn't behave like one. If my records are accurate*, by the time I responded (excluding that to Mark Lawrence), you had also said: > Should we particularly care about Nikos's feelings? > May that way he'll learn that if he doesn't > want to be considered an incompetent inconsiderate jerk, he shouldn't > behave like one. > You'll notice I don't judge all newbies as > incompetent jerks. Just you > I am judging you for > behaving liken an asshole and trying to deny it. > you were behaving like an asshole > You poor thing. (Obvious hostile sarcasm in context) And quite a few repeats of the same things. * I thought I stepped in earlier, but I'm not going to argue with GMail's history. This quote: > Maybe that way he'll learn that if he doesn't want to be considered > an incompetent inconsiderate jerk, he shouldn't behave like one. in solidarity -- although calling someone "incompetent" and, especially, a "jerk" is unwanted -- would probably not have made me respond. However, it is definitely past the "with trepidation" category. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default scope of variables
On 5 July 2013 03:03, Dave Angel wrote: > On 07/04/2013 09:24 PM, Steven D'Aprano wrote: >> On Thu, 04 Jul 2013 17:54:20 +0100, Rotwang wrote: >>> It's perhaps worth mentioning that some non-ascii characters are allowed >>> in identifiers in Python 3, though I don't know which ones. >> >> PEP 3131 describes the rules: >> >> http://www.python.org/dev/peps/pep-3131/ > > The isidentifier() method will let you weed out the characters that cannot > start an identifier. But there are other groups of characters that can > appear after the starting "letter". So a more reasonable sample might be > something like: ... > In particular, > http://docs.python.org/3.3/reference/lexical_analysis.html#identifiers > > has a definition for id_continue that includes several interesting > categories. I expected the non-ASCII digits, but there's other stuff there, > like "nonspacing marks" that are surprising. > > I'm pretty much speculating here, so please correct me if I'm way off. For my calculation above, I used this code I quickly mocked up: > import unicodedata as unidata > from sys import maxunicode > from collections import defaultdict > from itertools import chain > > def get(): > xid_starts = set() > xid_continues = set() > > id_start_categories = "Lu, Ll, Lt, Lm, Lo, Nl".split(", ") > id_continue_categories = "Mn, Mc, Nd, Pc".split(", ") > > characters = (chr(n) for n in range(maxunicode + 1)) > > print("Making normalized characters") > > normalized = (unidata.normalize("NFKC", character) for character in > characters) > normalized = set(chain.from_iterable(normalized)) > > print("Assigning to categories") > > for character in normalized: > category = unidata.category(character) > > if category in id_start_categories: > xid_starts.add(character) > elif category in id_continue_categories: > xid_continues.add(character) > > return xid_starts, xid_continues Please note that "xid_continues" actually represents "xid_continue - xid_start". -- http://mail.python.org/mailman/listinfo/python-list
Re: Default scope of variables
On 5 July 2013 03:03, Dave Angel wrote: > In particular, > http://docs.python.org/3.3/reference/lexical_analysis.html#identifiers > > has a definition for id_continue that includes several interesting > categories. I expected the non-ASCII digits, but there's other stuff there, > like "nonspacing marks" that are surprising. "nonspacing marks" are just accents, so it makes sense *á* mon avis. -- http://mail.python.org/mailman/listinfo/python-list