Re: Inserting record with Microsoft Access
"jeffhg582003" <[EMAIL PROTECTED]> wrote in news:[EMAIL PROTECTED]: > fields. I am trying to capture the number generated from the insert but > I am not exactly sure how to do that after an insert. Other folks have pointed you to "select @@identity" but I thought I should mention that if you use ADO with the AddNew method then autonumbers are magically retrieved. Something like this should work: rs.AddNew() rs.Fields("somefield").Value= "Blah" rs.Update() print "Autonumber is", rs.Fields("TheAutonumberField").Value This didn't always work so ADO and the MDB can't be ancient versions. SQL Server will also do this but the recordset must be opened with: rs.CursorLocation= constants.adUseServer rs.Open("Tablename", conn, constants.adOpenKeyset, constants.adLockOptimistic) -- http://mail.python.org/mailman/listinfo/python-list
Re: Puzzled by code pages
Buy high quality TAG Heuer Tiger Woods Golf Watches at low price, you can not believe, but it is true. There are two models on http://www.luxuryowner.net/Replica-TAG-Heuer-Tiger-Woods-Golf-Watches.html White: Tag Heuer Tiger Woods Golf White Mens Watch WAE1112.FT6008: http://www.luxuryowner.net/Replica-Tag-Heuer-Tiger-Woods-Golf-White-Mens-Watch-WAE1112.FT6008.html Black: Tag Heuer Tiger Woods Golf Black Mens Watch WAE.FT6004 http://www.luxuryowner.net/Replica-Tag-Heuer-Tiger-Woods-Golf-Black-Mens-Watch-WAE.FT6004.html More replica watches you can refer: http://www.luxuryowner.net/ "Adam Tauno Williams" дÈëÏûÏ¢ÐÂÎÅ:mailman.193.1273883243.32709.python-l...@python.org... > I'm trying to process OpenStep plist files in Python. I have a parser > which works, but only for strict ASCII. However plist files may contain > accented characters - equivalent to ISO-8859-2 (I believe). For example > I read in the line: > handle = open('file.txt', 'rb') data = handle.read() handle.close() data > '"skyp4_filelist_10201/localit\xc3\xa0 termali_sortfield" = > NSFileName;\n' > > What is the correct way to re-encode this data into UTF-8 so I can use > unicode strings, and then write the output back to ISO8859-? > > I can read the file using codecs as ISO8859-2, but it still doesn't seem > correct. > handle = codecs.open('file.txt', 'rb', encoding='iso8859-2') data = handle.read() handle.close() data > u'"skyp4_filelist_10201/localit\u0102\xa0 termali_sortfield" = > NSFileName;\n' > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Collision of Two Rect
On May 6, 2013 10:39 AM, "Joshua Landau" wrote: > > 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. You don't need subpixel positioning for many games -- arguably including Pong, although I suppose the argument would be stronger if the OP were not using a ludicrously high frame rate of 200 fps, which is going to limit the number of reasonable integer velocities available. For games where logical coordinates and screen coordinates need to be separated though, I agree. -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question -- plural of class name?
On Wed, May 8, 2013 at 2:37 PM, John Downs wrote: > On Wed, May 8, 2013 at 4:20 PM, Roy Smith wrote: >> >> FooEntry is a class. How would you describe a list of these in a >> docstring? >> >> "A list of FooEntries" >> >> "A list of FooEntrys" >> >> "A list of FooEntry's" >> >> "A list of FooEntry instances" >> >> The first one certainly sounds the best, but it seems wierd to change >> the spelling of the class name to make it plural. >> -- >> http://mail.python.org/mailman/listinfo/python-list > > > How about: "A list with elements of type FooEntry"? I also like the last > one: "A list of FooEntry instances". list *ducks* -- http://mail.python.org/mailman/listinfo/python-list
Re: Message passing syntax for objects | OOPv2
On Wed, May 8, 2013 at 8:35 PM, Mark Janssen wrote: > Okay, to anyone who might be listening, I found the core of the problem. What "problem" are you referring to? You've been posting on this topic for going on two months now, and I still have no idea of what the point of it all is. I recall something about not being happy with the OOP paradigm because apparently none of the dozens of existing languages handle message passing in the particular way that you think it should work; but if that's all it is, then why don't you just build a new language that does it the way that you think is right? If it's good, spread it around and it will gain traction. If not, then it will die the quiet death it deserves. All this irrelevant nonsense about Turing machines and lambda calculus that you've injected into the conversation though just reminds me of the "Einstein was wrong" cranks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Message passing syntax for objects | OOPv2
On Thu, May 9, 2013 at 3:51 PM, Mark Janssen wrote: > On Thu, May 9, 2013 at 10:33 AM, Ian Kelly wrote: >> On Wed, May 8, 2013 at 8:35 PM, Mark Janssen >> wrote: >>> Okay, to anyone who might be listening, I found the core of the problem. >> >> What "problem" are you referring to? You've been posting on this >> topic for going on two months now, and I still have no idea of what >> the point of it all is. > > You see Ian, while you and the other millions of coding practitioners > have (mal)adapted to a suboptimal coding environment where "hey > there's a language for everyone" and terms are thrown around, > misused, this is not how it needs or should be. Instead of the > thriving Open Source culture on the web we could have, Non sequitur. Open source software has nothing to do with coding environment or choice of language or OOP paradigm. Or Turing machines or lambda calculus, for that matter. > the community stays fractured. The open source community seems pretty healthy to me. What is the basis of your claim that it is "fractured"? > Languages can reach for an optimal design (within a constant margin of > leeway). There is no "optimal design". The *reason* that "there's a language for everyone" is because different people think about software in different ways and find different approaches better suited to them. Furthermore, some programming styles are naturally more conducive to accomplishing certain tasks, and worse at others. Take video game programming for an example. If I'm working on the graphics engine for a game, I would probably want to use a low-level imperative language for efficiency reasons. If I'm working on the AI, I will more likely prefer a functional or declarative language for clarity, flexibility and static analysis. In either case, OOP is probably a bad choice. > Language "expressivity" can be measured. And the measurements can be endlessly debated. Expressivity is not the sole measure of a programming language, though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Differences of "!=" operator behavior in python3 and python2 [ bug? ]
On Sun, May 12, 2013 at 5:23 PM, Mr. Joe wrote: > I seem to stumble upon a situation where "!=" operator misbehaves in > python2.x. Not sure if it's my misunderstanding or a bug in python > implementation. Here's a demo code to reproduce the behavior - The != operator is implemented by the __ne__ special method. In Python 3, the default implementation of __ne__ is to call __eq__ and return the opposite of whatever it returns. In Python 2, __ne__ calls the older __cmp__ method instead, which is no longer meaningful in Python 3. -- http://mail.python.org/mailman/listinfo/python-list
Re: Differences of "!=" operator behavior in python3 and python2 [ bug? ]
On Mon, May 13, 2013 at 5:27 PM, Andrew Berg wrote: > On 2013.05.13 17:53, Mark Lawrence wrote: >> I much prefer the alternative <> for != but some silly people insisted >> that this be removed from Python3. > It's not removed from Python 3, though: > > Python 3.3.1 (v3.3.1:d9893d13c628, Apr 6 2013, 20:30:21) [MSC v.1600 64 bit > (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. from __future__ import barry_as_FLUFL 3 <> 2 > True I'd like to see ≠ added as a synonym for !=, even if nobody uses it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Message passing syntax for objects | OOPv2
On Sun, May 12, 2013 at 10:48 PM, Mark Janssen wrote: > You're very right. But that is what has made it sort of a test-bed > for internet collaboration. The project I'm working on is aimed to > solve that problem and take the Wiki philosophy to its next or even > ultimate level. By adding a "natural" per-revision voting and > user-ranking it can clear up all the noise and scale to the whole > internet itself. But no one around here seem to think its > possible. I may have missed it in the noise, but I don't recall that you ever proposed such a project "around here". That said, your brief description does sound rather like Cloud Cuckoo Land to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Fractal
On Mon, May 13, 2013 at 9:41 AM, Sharon COUKA wrote: > Hello, I'm new to python and i have to make a Mandelbrot fractal image for > school but I don't know how to zoom in my image. > Thank you for helping me. Is this a GUI application or does it just write the image to a file? What GUI / image library are you using? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7.x - problem with obejct.__init__() not accepting *args and **kwargs
On Wed, May 15, 2013 at 6:16 AM, Oscar Benjamin wrote: > I don't generally use super() but I did see some advice about it in > this article: > https://fuhm.net/super-harmful/ > > From the conclusion: > "Never use positional arguments in __init__ or __new__. Always use > keyword args, and always call them as keywords, and always pass all > keywords on to super." While that article is a good read, this one is a bit better on giving advice about how to practically use super: http://rhettinger.wordpress.com/2011/05/26/super-considered-super/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Question re: objects and square grids
On Wed, May 15, 2013 at 10:56 AM, Andrew Bradley wrote: > Hello everyone. > > I am having a good time programming with Python 3.3 and Pygame. Pygame seems > like the perfect platform for the kind of simple games that I want to make. > > What I have currently programmed is basically a drawn rectangle filled with > 200 squares, each side of the squares being 43 pixels. The rectangle is 20 > squares by 10 squares. It's more work, but I would recommend making the squares scalable in some manner, instead of arbitrarily hard-coding them at 43 pixels. What are you going to do when somebody has a 4K monitor and wants to run the game full screen? > This grid is what I want to have the entire game on. There will be pieces > that move certain numbers of squares, perform actions that effect pieces on > certain squares, etc. The possibilities are endless. > > So what I am now trying to do is organize these squares into objects that I > can easily reference when programming things related to the squares. > > So far, I have done this: > > A1 = pygame.Rect(10, 12, 43, 43) > A2 > A3 > A4 > B1 > B2 > etc. This is a tedious, repetitive, and error-prone way to build all the squares. Instead of having a separate variable for each square, consider putting them in a collection and building them up using nested loops. For example, the above could look something like: squares = [] for row in range(10): row_squares = [] for column in range(20): rect = Rect(column * width + x_offset, row * height + y_offset, width, height) row_squares.append(rect) squares.append(row_squares) Then the A1 rect is accessible as squares[0][0], A2 as squares[0][1], B1 as squares[1][0], etc. Alternatively, you could store the rects in a dict and use "A1", "B1", etc. as the keys, but I think you will find that the game logic will be simpler if you use integers internally for your rows and columns, rather than the square labels. > where said integers are the precise location of the top left-most square for > A1, and onward down the line. I would guess that I could continue on in such > a fashion, with appropriate box names for each square. But I'm running into > the problem of confirming that the code above actually does something > useful. For example, I would love to be able to turn A1 a different color, > but how does this work? How do I actually utilize these object variable > names? Are there methods that I am not aware of, because most things I try > tend to do nothing or crash the game. For example, A1.fill(BLUE) does not > work. A Rect only stores position and size information and provides methods for processing the same. It doesn't know anything about drawing. Use the pygame.draw or pygame.gfxdraw functions for that. For example, to fill a part of the screen as indicated by the position of a rect: BLUE = (0, 0, 255) pygame.draw.rect(screen, BLUE, squares[0][0]) That said, you probably don't just want to color a square blue. You probably also want to remember that the square is blue for when you are redrawing it later. You need to track not just the position of each square, but also their state. This means that each object in your "squares" container should not just be a rect, but some broader object that contains square data, *including* a rect. Something like this: class Square: def __init__(self, rect): self.rect = rect self.color = (0, 0, 0) self.contents = None # ... and whatever else you need to track Then when you fill the squares container, you would fill it with instances of your Square class instead of plain Rects, which gives you a place to keep track of the square's color, among other things. The drawing code above then might look something like this: pygame.draw.rect(screen, some_square.color, some_square.rect) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7.x - problem with obejct.__init__() not accepting *args and **kwargs
On Wed, May 15, 2013 at 8:06 PM, Steven D'Aprano wrote: > On Wed, 15 May 2013 13:16:09 +0100, Oscar Benjamin wrote: > > >> I don't generally use super() > > Then you should, especially in Python 3. > > If you're not using super in single-inheritance classes, then you're > merely making your own code harder to read and write, and unnecessarily > difficult for others to use with multiple-inheritance. > > If you're not using super in multiple-inheritance[1] classes, then your > code is probably buggy. > > There really is no good reason to avoid super in Python 3. The Python 3 syntactic sugar is the primary reason that I've finally started using super in single-inheritance classes. The magicalness of it still disturbs me a bit, though. >>> class A: ... def __str__(self): ... return super().__str__() ... >>> class B: ... __str__ = A.__str__ ... >>> A().__str__ > >>> str(A()) '<__main__.A object at 0x0289E270>' >>> B().__str__ > The transplanted __str__ method is considered a method of B by Python... >>> str(B()) Traceback (most recent call last): File "", line 1, in File "", line 3, in __str__ TypeError: super(type, obj): obj must be an instance or subtype of type But you can't use it because the super() call is irrevocably tied to class A. :-P Of course the same is true with the syntax "super(A, self)", but at least with that syntax it is clear that the method is explicitly referencing class A, and so should not be expected to work correctly in class B. By contrast the syntax "super()" looks misleadingly generic. -- http://mail.python.org/mailman/listinfo/python-list
Re: Fractal
On Thu, May 16, 2013 at 5:04 AM, Sharon COUKA wrote: > I have to write the script, and i have one but the zoom does not work That doesn't answer my question. Perhaps if you would share with us what you already have, then we could point out what you need to do and where to get your "zoom" working. -- http://mail.python.org/mailman/listinfo/python-list
Re: Fractal
On Thu, May 16, 2013 at 10:55 AM, Sharon COUKA wrote: > # Register events > c.bind('i', zoom) > c.bind('i', unzoom) > c.bind('i', mouseMove) I'm not an expert at Tkinter so maybe one of the other residents can help you better with that. The code above looks wrong to me, though. As far as I know, 'i' is not a valid event sequence in Tkinter, and besides you probably want to bind these functions to three *different* events. See here for the docs on event sequences: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/event-sequences.html Based on your code, it looks like you would probably want something like: c.bind('', zoom) c.bind('', unzoom) c.bind('', mouseMove) -- http://mail.python.org/mailman/listinfo/python-list
Re: Non-identifiers in dictionary keys for **expression syntax
On Thu, May 23, 2013 at 12:52 PM, Matthew Gilson wrote: > Using Cpython, we can do the following: > > def func(**kwargs): > print kwargs > > d = {'foo bar baz':3} > > So that might lead us to believe that the keys of the mapping do not need to > be valid identifiers. However, the previous function does not work with the > following dictionary: > > d = {1:3} > > because not all the keys are strings. Is there a way to petition to get > this more rigorously defined? The string requirement is probably for optimization, but if the argument is both sent and received using the ** syntax, is there a good reason why only identifiers should be allowed? -- http://mail.python.org/mailman/listinfo/python-list
Re: Solving the problem of mutual recursion
On Sun, May 26, 2013 at 12:13 PM, Peter Brooks wrote: > No, on a multi-core machine it's normal. The machine shows python > running multiple threads - and the number of threads change as the > program runs. Perhaps the OS/X implementation of python does allow > concurrency when others don't. It certainly looks like it! I'm pretty sure that CPython uses the GIL regardless of platform. And yes you can have multiple OS-level threads, but because of the GIL only one will actually be running at a time. Other possibilities include: 1) You're using a different implementation of Python that does not have a GIL, e.g. Jython or IronPython (well, probably not the latter). I believe PyPy also has a GIL-less version, although I don't think this is in the current release yet. 2) You're using a fork of CPython that removes the GIL. There are a number of these, but none to my knowledge that are able to maintain the performance of CPython for a single thread. 3) You're mistakenly looking at multiple Python processes that are running simultaneously and adding their usages together. 4) The utility you're using is reporting the process CPU usage incorrectly. 5) Maybe for some reason the Mac OS X build of CPython is using spin-locks in the GIL. I can't imagine why this would be the case. -- http://mail.python.org/mailman/listinfo/python-list
Re: Solving the problem of mutual recursion
On Sun, May 26, 2013 at 10:36 PM, Peter Brooks wrote: > This makes complete sense - any atomic action should be atomic, so two > threads can't be doing it at the same time. They can be doing anything > else though. > > If two threads create a new object at the same time, for example, > there's potentially the problem that they'll get the same space, so > the object will be owned by both. To prevent this, the new object call > should be run in only one thread. > > If you have two objects running their methods on their own local > variables, then there's no potential for conflict, so there's no need > for them to be blocked. That's not the way it works. The CPython interpreter always runs with the GIL held; the alternative would be to have individual mutex locks on every Python object, which is expensive for performance due to the reference counting mechanism. Python functions can't release the GIL. C functions that are called from the interpreter *can* release the GIL to allow concurrency, but are only permitted to do so as long as they're not working with Python objects, e.g. waiting on I/O or performing a long calculation on C data. There are some more detailed slides on how the GIL works at: http://www.dabeaz.com/python/UnderstandingGIL.pdf Note that the description in Part 1 describes how the GIL worked prior to Python 3.2. The new GIL is described in Part 4, but the basic underlying concept is the same. > This is an interesting subject.. There's nothing wrong with the tool > I'm using to report threads - 'Activity Monitor' is the standard > process monitor. It counts cores as 'CPUs', which seems perfectly > reasonable to me. As I said, other Unixes, such as HP-UX, do the same > thing. I have no problem with that. It's also the default in Linux, where I believe it is called "IRIX mode" (as opposed to "Solaris mode", where the difference is just a factor equal to the number of cores). What I was questioning was whether the actual number being reported was correct. If it's the standard tool for the OS, then it probably is. -- http://mail.python.org/mailman/listinfo/python-list
Re: Solving the problem of mutual recursion
On Sun, May 26, 2013 at 4:16 PM, Chris Angelico wrote: > On Mon, May 27, 2013 at 5:35 AM, Ian Kelly wrote: >> I'm pretty sure that CPython uses the GIL regardless of platform. And >> yes you can have multiple OS-level threads, but because of the GIL >> only one will actually be running at a time. Other possibilities >> include: > > 6) It's spinning in a function that has released the GIL. Python > threads can certainly execute concurrently; they just can't be > manipulating Python objects. Most of the I/O functions will release > the GIL before doing a potentially-blocking operation, and some > CPU-heavy functions can do the same (I'm given to understand that > numpy does this) - just depends on having a long job that involves no > refcounted objects. 7) Since the program being tested does basically nothing except start and exit threads, the extra 40% probably represents the overhead of all that starting and stopping, which would be done outside the GIL. -- http://mail.python.org/mailman/listinfo/python-list
Re: Solving the problem of mutual recursion
On Mon, May 27, 2013 at 12:19 AM, Ian Kelly wrote: > 7) Since the program being tested does basically nothing except start > and exit threads, the extra 40% probably represents the overhead of > all that starting and stopping, which would be done outside the GIL. To test this, I tried running the script in Python 2.7 in Linux with the print statements removed and verified that it was using about 135% of the CPU. However, top also told me that only about 95% of that was user processes; the other 40% was kernel usage. The 40% doesn't seem to be threading overhead though, because I tried adding large xrange loops to slow down the thread creation process and it had no effect on the stats. Then I tried running the same program in Python 3.2, and I got the more expected 100% CPU usage with minimal kernel time. So I'm thinking now that the extra 40% may actually be overhead induced by the GIL. If that's the case then wow, the old GIL really did suck. -- http://mail.python.org/mailman/listinfo/python-list
Re: String object has no attribute "append"
On Tue, May 28, 2013 at 12:25 PM, Matt Graves wrote: > I receive this error while toying around with Functions... > > def pulldata(speclist,speccolumn): > with open('profiles.csv', 'r') as f: > reader = csv.reader(f) > for column in reader: > (speclist).append(column[('speccolumn')]) > > pulldata(speclist = 'numbers', speccolumn = "0") > > >>Traceback (most recent call last): >> File "C:\Desktop\Python\CFI\Devices V2\users.py", line 17, in >>pulldata(speclist = 'numbers', speccolumn = "0") >> File "C:\Desktop\Python\CFI\Devices V2\users.py", line 16, in pulldata >>(speclist).append(column[('speccolumn')]) >>AttributeError: 'str' object has no attribute 'append' > > I'm getting the error because it should say "numbers.append", but it is > reading it as "(speclist).append". > > This is my first time playing with functions, so be gentle. It looks like you're trying to pass in a list called 'numbers' into the pulldata function, but that is not what's happening. Because of the single quotes you have around numbers, you are passing in the /string/ 'numbers' and calling it 'speclist' instead. The same goes for speccolumn as well; I think you mean to pass in the integer 0, but you're passing in the string "0" instead. Try it without the quotes: pulldata(speclist = numbers, speccolumn = 0) -- http://mail.python.org/mailman/listinfo/python-list
Re: String object has no attribute "append"
On Tue, May 28, 2013 at 12:41 PM, Ian Kelly wrote: > On Tue, May 28, 2013 at 12:25 PM, Matt Graves wrote: >> I receive this error while toying around with Functions... >> >> def pulldata(speclist,speccolumn): >> with open('profiles.csv', 'r') as f: >> reader = csv.reader(f) >> for column in reader: >> (speclist).append(column[('speccolumn')]) >> >> pulldata(speclist = 'numbers', speccolumn = "0") >> >> >>>Traceback (most recent call last): >>> File "C:\Desktop\Python\CFI\Devices V2\users.py", line 17, in >>>pulldata(speclist = 'numbers', speccolumn = "0") >>> File "C:\Desktop\Python\CFI\Devices V2\users.py", line 16, in pulldata >>>(speclist).append(column[('speccolumn')]) >>>AttributeError: 'str' object has no attribute 'append' >> >> I'm getting the error because it should say "numbers.append", but it is >> reading it as "(speclist).append". >> >> This is my first time playing with functions, so be gentle. > > It looks like you're trying to pass in a list called 'numbers' into > the pulldata function, but that is not what's happening. Because of > the single quotes you have around numbers, you are passing in the > /string/ 'numbers' and calling it 'speclist' instead. The same goes > for speccolumn as well; I think you mean to pass in the integer 0, but > you're passing in the string "0" instead. Try it without the quotes: > > pulldata(speclist = numbers, speccolumn = 0) And along the same lines, the expression column[('speccolumn')] should just be column[speccolumn]. -- http://mail.python.org/mailman/listinfo/python-list
Re: Short-circuit Logic
On Wed, May 29, 2013 at 8:33 AM, rusi wrote: > 0.0 == 0.0 implies 5.4 == 5.4 > is not a true statement is what (I think) Steven is saying. > 0 (or if you prefer 0.0) is special and is treated specially. It has nothing to do with 0 being special. A floating point number will always equal itself (except for nan, which is even more special), and in particular 5.4 == 5.4. But if you have two different calculations that produce 0, or two different calculations that produce 5.4, you might actually get two different numbers that approximate 0 or 5.4 thanks to rounding error. If you then compare those two ever-so-slightly different numbers, you will find them unequal. -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting a callable for any value?
On Wed, May 29, 2013 at 11:46 AM, Croepha wrote: > Is there anything like this in the standard library? > > class AnyFactory(object): > def __init__(self, anything): > self.product = anything > def __call__(self): > return self.product > def __repr__(self): > return "%s.%s(%r)" % (self.__class__.__module__, self.__class__.__name__, > self.product) In other words, the function (lambda: x) with a repr that tells you what x is? Not that I'm aware of, but you could just do something like: def return_x(): return x And then the repr will include the name "return_x", which will give you a hint as to what it does. Also, "AnyFactory" is a misleading name because the class above is not a factory. > my use case is: > collections.defaultdict(AnyFactory(collections.defaultdict(AnyFactory(None > > And I think lambda expressions are not preferable... What you have above is actually buggy. Your "AnyFactory" will always return the *same instance* of the passed in defaultdict, which means that no matter what key you give to the outer defaultdict, you always get the same inner defaultdict. Anyway, I think it's clearer with lambdas: defaultdict(lambda: defaultdict(lambda: None)) But I can see your point about the repr. You could do something like this: class NoneDefaultDict(dict): def __missing__(self, key): return None def __repr__(self): return "NoneDefaultDict(%s)" % super(NoneDefaultDict, self).__repr__() some_dict = defaultdict(NoneDefaultDict) -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting a callable for any value?
On Wed, May 29, 2013 at 12:19 PM, Fábio Santos wrote: > Are you sure you don't want to use a lambda expression? They are pretty > pythonic. > > none_factory = lambda: None > defaultdict_none_factory = lambda: defaultdict(none_factory) > > collections.defaultdict(defaultdict_none_factory) Gah. If you're going to go to the trouble of assigning a name to the lambda, then just use a def statement: def none_factory: return None def defaultdict_none_factory: return defaultdict(none_factory) collections.defaultdict(defaultdict_none_factory) -- http://mail.python.org/mailman/listinfo/python-list
Re: python b'...' notation
On Wed, May 29, 2013 at 12:33 PM, alcyon wrote: > This notation displays hex values except when they are 'printable', in which > case it displays that printable character. How do I get it to force hex for > all bytes? Thanks, Steve Is this what you want? >>> ''.join('%02x' % x for x in b'hello world') '68656c6c6f20776f726c64' -- http://mail.python.org/mailman/listinfo/python-list
Re: How clean/elegant is Python's syntax?
On Wed, May 29, 2013 at 8:49 PM, rusi wrote: > On May 30, 6:14 am, Ma Xiaojun wrote: >> What interest me is a one liner: >> print '\n'.join(['\t'.join(['%d*%d=%d' % (j,i,i*j) for i in >> range(1,10)]) for j in range(1,10)]) > > Ha,Ha! The join method is one of the (for me) ugly features of python. > You can sweep it under the carpet with a one-line join function and > then write clean and pretty code: > > #joinwith > def joinw(l,sep): return sep.join(l) I don't object to changing the join method (one of the more shoe-horned string methods) back into a function, but to my eyes you've got the arguments backward. It should be: def join(sep, iterable): return sep.join(iterable) Putting the separator first feels more natural to me because I expect the separator to usually be short as compared to the iterable, which is often a longer expression (as is the case in both of your subsequent usages). Placing the separator first also preserves consistency of interface with the str.join and bytes.join functions, as well as the older string.join function. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get an integer from a sequence of bytes
On Thu, May 30, 2013 at 12:26 PM, Mok-Kong Shen wrote: > Am 27.05.2013 17:30, schrieb Ned Batchelder: >> >> On 5/27/2013 10:45 AM, Mok-Kong Shen wrote: >>> >>> From an int one can use to_bytes to get its individual bytes, >>> but how can one reconstruct the int from the sequence of bytes? >>> >> The next thing in the docs after int.to_bytes is int.from_bytes: >> http://docs.python.org/3.3/library/stdtypes.html#int.from_bytes > > > I am sorry to have overlooked that. But one thing I yet wonder is why > there is no direct possibilty of converting a byte to an int in [0,255], > i.e. with a constrct int(b), where b is a byte. The bytes object can be viewed as a sequence of ints. So if b is a bytes object of non-zero length, then b[0] is an int in range(0, 256). -- http://mail.python.org/mailman/listinfo/python-list
Re: How clean/elegant is Python's syntax?
On Thu, May 30, 2013 at 12:44 PM, Chris Angelico wrote: > On Fri, May 31, 2013 at 4:36 AM, Ian Kelly wrote: >> I don't object to changing the join method (one of the more >> shoe-horned string methods) back into a function, but to my eyes >> you've got the arguments backward. It should be: >> >> def join(sep, iterable): return sep.join(iterable) > > Trouble is, it makes some sense either way. I often put the larger > argument first - for instance, I would write 123412341324*5 rather > than the other way around - and in this instance, it hardly seems as > clear-cut as you imply. But the function can't be written to take them > in either order, because strings are iterable too. (And functions that > take args either way around aren't better than those that make a > decision.) The reason I like having the shorter argument first (at least for function calls) is for when I'm reading the code. If I'm interested in the second argument, then to find it I have to scan over the first argument. I would rather scan over something short like '\n' than something longer like a list comprehension. It sounds like a trivial thing, but it really does make it easier to find where an expression starts and ends when the expression is short. -- http://mail.python.org/mailman/listinfo/python-list
Re: Short-circuit Logic
On Thu, May 30, 2013 at 1:30 PM, Neil Cerutti wrote: > On 2013-05-30, Chris Angelico wrote: >> On Thu, May 30, 2013 at 3:10 PM, Steven D'Aprano >> wrote: >>> # Wrong, don't do this! >>> x = 0.1 >>> while x != 17.3: >>> print(x) >>> x += 0.1 >> >> Actually, I wouldn't do that with integers either. > > I propose borrowing the concept of significant digits from the > world of Physics. > > The above has at least three significant digits. With that scheme > x would approximately equal 17.3 when 17.25 <= x < 17.35. > > But I don't see immediately how to calculate 17.25 and 17.35 from > 17.3, 00.1 and 3 significant digits. How about this: while round(x, 1) != round(17.3, 1): pass The second round call may be unnecessary. I would expect the parser to ensure that round(17.3, 1) == 17.3, but I'm not certain that is the case. -- http://mail.python.org/mailman/listinfo/python-list
Re: How clean/elegant is Python's syntax?
On Thu, May 30, 2013 at 1:38 PM, MRAB wrote: > And additional argument (pun not intended) for putting sep second is > that you can give it a default value: > >def join(iterable, sep=""): return sep.join(iterable) One argument against the default is that it is specific to the str type. If you then tried to use join with an iterable of bytes objects and the default sep argument, you would get a TypeError. At least not having the default forces you to be explicit about which string type you're joining. -- http://mail.python.org/mailman/listinfo/python-list
Re: How clean/elegant is Python's syntax?
On Fri, May 31, 2013 at 4:16 AM, Fábio Santos wrote: > On Fri, May 31, 2013 at 10:08 AM, Alister wrote: >> I think that is the winning argument. >> Next question is what should be the default ("", " " or',')? > > join, comma_join, whitejoin, linejoin variants, with different defaults? The more specific versions should not even have the parameter as an argument that can be supplied. Otherwise you could do: comma_join(words, sep=';') which is just unclear, and there is no reason to allow it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Too many python installations. Should i remove them all and install the latest?
On Fri, May 31, 2013 at 9:41 AM, Νικόλαος Κούρας wrote: > Τη Παρασκευή, 31 Μαΐου 2013 6:37:06 μ.μ. UTC+3, ο χρήστης Fábio Santos έγραψε: > >> Check if python3 and python3.3 aren't the same. Run them and look at the >> "intro" > lines. > > root@nikos [~]# python -V > Python 2.6.6 > root@nikos [~]# python3 -V > Python 3.3.0 > root@nikos [~]# python3.3 -V > Python 3.3.0 So it looks like you have two Python installations, one for Python 2 and one for Python 3. Why is that too many? -- http://mail.python.org/mailman/listinfo/python-list
Re: Too many python installations. Should i remove them all and install the latest?
On Fri, May 31, 2013 at 11:10 AM, Νικόλαος Κούρας wrote: > root@nikos [~]# ls -al /usr/bin/python* > -rwxr-xr-x 3 root root 4864 Feb 22 02:00 /usr/bin/python* > lrwxrwxrwx 1 root root6 Apr 5 20:34 /usr/bin/python2 -> python* > -rwxr-xr-x 3 root root 4864 Feb 22 02:00 /usr/bin/python2.6* > -rwxr-xr-x 1 root root 1418 Feb 22 02:00 /usr/bin/python2.6-config* > lrwxrwxrwx 1 root root 24 Apr 7 22:10 /usr/bin/python3 -> > /opt/python3/bin/python3* > lrwxrwxrwx 1 root root 16 Apr 5 20:35 /usr/bin/python-config -> > python2.6-config* > root@nikos [~]# > > so, i should just 'yum remove python3' ? If you're not using it, and if yum isn't going to remove anything else that has it as a dependency, then go ahead. On the other hand, there's really not much harm in leaving it. Python 2.6 is already your default Python. Is this the same system where you recently spent a lot of time upgrading your web scripts to Python 3? -- http://mail.python.org/mailman/listinfo/python-list
Re: Too many python installations. Should i remove them all and install the latest?
On Fri, May 31, 2013 at 11:16 AM, Νικόλαος Κούρας wrote: > root@nikos [~]# which python > /usr/bin/python > root@nikos [~]# which python2 > /usr/bin/python2 > root@nikos [~]# which python3 > /root/.local/lib/python2.7/bin/python3 > root@nikos [~]# which python3.3 > /root/.local/lib/python2.7/bin/python3.3 > root@nikos [~]# > > So i have > 2.6 > 2.7 > 3 > 3.3 > > 4 installations? Oh, I see. The python3 and python3.3 are probably the same binary, though. In any case, since Python 2.7 and Python 3 are both installed under /root/.local, it looks like you didn't install them using yum in the first place. You probably installed them from source. If that's the case, you can probably just rm -rf the python2.7 folder from each of the /root/.local subfolders that has it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Too many python installations. Should i remove them all and install the latest?
On Fri, May 31, 2013 at 11:42 AM, Νικόλαος Κούρας wrote: > OMG i gave by mistake > > root@nikos [/]# rm -rf /root/.local/ > > did i screwed up my remote VPS which i host 10 peoples webpages? I don't know, is that where you were keeping the data? The website still appears to be working, as best I can tell from this computer. I've never actually been able to view it from here, because I get a UnicodeDecodeError at this line: host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] But at least I'm still seeing that error, so the server is still responding to requests. -- http://mail.python.org/mailman/listinfo/python-list
Re: Too many python installations. Should i remove them all and install the latest?
On Fri, May 31, 2013 at 5:30 PM, Νικόλαος Κούρας wrote: > Indeed i have comiled python 2.7 and 3.3 form source after wget and > ./configure an make install > > but i belive somehting is mixed up althouh python works ok. > > root@nikos [/opt/python3/bin]# ls -al > ... > root@nikos [/opt/python3/bin]# make help > make: *** No rule to make target `help'. Stop. > root@nikos [/opt/python3/bin]# > > > cant remove it. The Makefile would be located in the source directory where you built Python, not in the installation directory. But in any case, I don't think the Python Makefile includes an uninstall option. If you want to uninstall Python that was built from source, you need to remove the files by hand. > Why you say i cant just yum install python3.3.2 Because CentOS 6 evidently does not provide a package for any version of Python other than 2.6. If you want to install another version, you will need to do it from source. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyWart: The problem with "print"
On Sun, Jun 2, 2013 at 6:16 PM, Jason Swails wrote: > I'm actually with RR in terms of eliminating the overhead involved with > 'dead' function calls, since there are instances when optimizing in Python > is desirable. I actually recently adjusted one of my own scripts to > eliminate branching and improve data layout to achieve a 1000-fold > improvement in efficiency (~45 minutes to 0.42 s. for one example) --- all > in pure Python. The first approach was unacceptable, the second is fine. > For comparison, if I add a 'deactivated' debugprint call into the inner loop > (executed 243K times in this particular test), then the time of the > double-loop step that I optimized takes 0.73 seconds (nearly doubling the > duration of the whole step). It seems to me that your problem here wasn't that the time needed for the deactivated debugprint was too great. Your problem was that a debugprint that executes 243K times in 0.73 seconds is going to generate far too much output to be useful, and it had no business being there in the first place. *Reasonably* placed debugprints are generally not going to be a significant time-sink for the application when disabled. > The easiest way to eliminate these 'dead' calls is to simply comment-out the > print call, but I would be quite upset if the interpreter tried to outsmart > me and do it automagically as RR seems to be suggesting. Indeed, the print function is for general output, not specifically for debugging. If you have the global print deactivation that RR is suggesting, then what you have is no longer a print function, but a misnamed debug function. -- http://mail.python.org/mailman/listinfo/python-list
Re: Too many python installations. Should i remove them all and install the latest?
On May 31, 2013 6:27 PM, "Chris Angelico" wrote: > Yeah. I know that particular one because I have l aliased to ls -CF > (aka --columns --classify), mainly because it came that way as a > commented-out entry in my first Debian. Have since become quite > accustomed to it; to me, 'l' means 'look' (I do love my MUDs), so I'm > considering aliasing 'gl' to 'pwd' so that I can 'glance' too :) > > Hmm. What other MUD commands have obvious Unix equivalents? > > say --> echo > emote --> python -c > attack --> sudo rm -f Have you ever tried Adventure Shell? -- http://mail.python.org/mailman/listinfo/python-list
Re: Bools and explicitness [was Re: PyWart: The problem with "print"]
On Tue, Jun 4, 2013 at 9:44 AM, Rick Johnson wrote: > It is my firm belief that truth testing a value that is not > a Boolean should raise an exception. If you want to convert > a type to Boolean then pass it to the bool function: > > lst = [1,2,3] > if bool(lst): > do_something > > This would be "explicit enough" That is *exactly* equivalent to the same test without the bool function, and it gives the reader zero additional information about what "lst" is, so it boggles me that you approve of this "if bool(lst):" monstrosity while decrying the equivalent and slightly more efficient "if lst:". I think part of your complaint concerns the fact that the reader must understand the rules by which a truth value is implicitly obtained from lst in the statement "if lst:". But the reader must know the *same* rules in order to understand the more explicit "if bool(lst):", so there is no benefit to the latter in that regard either. > Yes i do care about the length or i would not have asked. > I'm asking Python to tell me if the iterable has members, > amd if it does, i want to execute a block of code, if it > does not, i want to do nothing. But i'm also informing the > reader of my source code that the symbol i am truth testing > is expected to be an iterable with a __len__ method. Caring that the object has a length is not the same as caring about what the object's length is. Steven's point stands, that your code inefficiently asks the object for some property that you don't (yet) care about. > "if lst" does not give me the same answer (or imply the same > meaning to a reader), it merely tells me that the implict > conversion has resulted in a True value, but what if the lst > symbol is pointing to a string? Then i will falsely believe > i have a list with members when i actually have a string > with length greater than zero. Your "if len(lst) > 0" fails to differentiate lists from strings in exactly the same way. > I agree. Summing the list members just to guarantee that the > iterable has members is foolish, however, python gives me no > other choice IF i want to be "explicit enough". In a > properly designed language, the base iterable object would > supply a "hasLength" or "hasMembers" method that would > return a much faster check of: > > try: > iterable[0] > except IndexError: > return False > else: > return True > > That check would guarantee the iterable contained at least > one member without counting them all. You said earlier in your post that "bool(lst)" was "explicit enough", and this is exactly what it does. > When i am writing code i prefer to be "explicit enough" so > that IF my assumptions about the exact type of an object are > incorrect, the code will fail quickly enough that i can > easily find and correct the problem. In a duck-typing language you should not be making assumptions about the "exact type" of an object in the first place. If I'm writing a function that receives a list-like argument, then at the *most specific* I will assume that the object passed in is a MutableSequence (but since I prefer to keep my functions functional where practical, more usually I will assume only that the object is an iterable or a generic sequence). If the caller wants to pass in a deque or some user-defined generic MutableSequence instead, then let them do so. I will also clearly document that assumption; if the caller can't be bothered to read the docs and passes in an object that breaks that assumption, then that's their own damn problem when it doesn't work. This is a programming language for consenting adults. > But we are really ignoring the elephant in the room. Implict > conversion to Boolean is just a drop in the bucket compared > to the constant "shell game" we are subjected to when > reading source code. We so naively believe that a symbol > named "lst" is a list object or a symbol "age" is a integer, > when we could be totally wrong! This is the source of many > subtle bugs!!! I am more likely to believe that an object is a list based on the documentation than on the mere fact that it is named "lst". The variable *does* have documentation, doesn't it? If when debugging I have reason to suspect that the documentation is incorrect or is being ignored, then I'll add an assertion to test it. > There must be some method by which we can truth test an > iterable object and verify it has members, but do so in a > manner that is valid for all types AND exposes the "expected > type" in the method name. hmm... This is nonsense. If it exposes the "expected type" in the name, then it can only be valid for that expected type. > Adding a method like "is_valid" to every object can seem > logical, however, this can fail just as miserably as > Python's current implicit bool. And, more disastrously, an > "is_valid" method is not going to raise an error (where it > should) because it works for all types. Actually it sounds completely illogic
Re: Do you consider Python a 4GL? Why (not)?
On Tue, Jun 4, 2013 at 6:38 PM, Carlos Nepomuceno wrote: > I don't have an opinion yet, but I've found contradictory evidence from many > sources, such as: > > "A domain-specific language (DSL) is a type of programming language or > specification language in software development and domain engineering > dedicated to a particular problem domain, > [...] > The opposite is: > > a general-purpose programming language, such as C, Java or Python," > > http://en.wikipedia.org/wiki/Domain-specific_programming_language > > Since, 4GL is considered a subset of DSLs, this wiki page doesn't consider > Python a 4GL. > > Is is true? Why??? I wasn't previously familiar with the 3GL / 4GL nomenclature, but based upon the definitions given at Wikipedia, Python is clearly a 3GL. That said, virtually all general-purpose languages in common usage today would be 3GLs, so the distinction does not seem terribly useful to me. The terms "4GL" and "5GL" while suggesting a language that is somehow more "advanced" than a 3GL, seem to be mainly 80s hype. -- http://mail.python.org/mailman/listinfo/python-list
Re: Bools and explicitness [was Re: PyWart: The problem with "print"]
On Wed, Jun 5, 2013 at 10:25 PM, Russ P. wrote: > I recall reading a few years ago that Guido was thinking about adding > optional type annotations. I don't know if that went anywhere or not, but I > thought it was a good idea. Eventually I got tired of waiting, and I realized > that I just wanted a statically typed language, so I started using one. Python 3 has support for arbitrary function argument annotations. The language itself ascribes no special meaning to it, so it's up to the user to add a type-checker (or whatever else they might want to use it for). -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Game Development?
On Fri, Jun 7, 2013 at 9:53 AM, wrote: > I was planning on making a small 2D game in Python. Are there any libraries > for this? I know of: > > • Pygame - As far as I know it's dead and has been for almost a year > • PyOgre - Linux and Windows only(I do have those, but I want multi-platform) > • Cocos2D - Won't install and cant find any support > • PyCap - Can't find any documentation > • Panda3D - Dead since 2011 + overkill for what I need > • PyOpenGL - Overkill > > Any help on what to do with this would be appreciated. I am making games > mainly in Lua but I'd like to make one in Python for fun. I also understand > that Python isn't exactly the *BEST* choice programming a game, but I have > heard it is possible. Tell me if it's true. Thanks! Pygame is still quite commonly used, and the most recent commit was in April, so I think it's too early to pronounce it dead (although pgreloaded, which at one point was intended to be a successor to pygame, is looking a bit dormant now). A lot of folks also like pyglet, but I've never used it myself. I suspect it might also be overkill for you. And yes, it's definitely possible to make games in Python. Go to pyweek.org and check out many of the awesome games that have been developed in Python in only one week. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Game Development?
On Fri, Jun 7, 2013 at 10:28 AM, Eam onn wrote: > Do you know of any tutorial for PyGame? Preferably a video tutorial but any > tutorial at all is fine! I can't seem to find any, even on pygame.org!!! I'd start here: http://www.pygame.org/wiki/tutorials -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Game Development?
On Fri, Jun 7, 2013 at 10:35 AM, Ian Kelly wrote: > On Fri, Jun 7, 2013 at 10:28 AM, Eam onn wrote: >> Do you know of any tutorial for PyGame? Preferably a video tutorial but any >> tutorial at all is fine! I can't seem to find any, even on pygame.org!!! > > I'd start here: http://www.pygame.org/wiki/tutorials Also the section under the "Tutorials" heading at http://www.pygame.org/docs/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Game Development?
On Fri, Jun 7, 2013 at 11:53 AM, Eam onn wrote: > Pygame isn't too good. You still need a lot of other libraries from what I > understand(like for physics). Is there any alternative for 2D? I don't know of any Python libraries that provide both a rendering engine and a physics engine. I'm not sure why you say pyame "isn't too good". A library that only does one thing shouldn't be considered a bad library if it does it well. I hear that pygame doesn't scale very well to large games, and it certainly wouldn't be my first choice for a 3D game, but I've never had any major issues with it myself. There's a largish list of alternative libraries that you might consider here: http://wiki.python.org/moin/PythonGameLibraries -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: question regarding references and class relationships
On Mon, Jun 10, 2013 at 7:57 AM, Rui Maciel wrote: > # Case A: this works > model.points[0].position = [2,3,4] > line.points > > # Case B: this doesn't work > test.model.points[0] = test.Point(5,4,7) > line.points > > > > Is there a Python way of getting the same effect with Case B? It's informative to think about what object is actually being mutated in each of those examples. In A, you are mutating the Point instance by replacing its "position" attribute with a new list. Since the Line object references the same Point instance, it "sees" the change. In B, you are actually mutating a list *containing* the Point instance, by replacing the Point in the list with some new Point. The replaced Point itself is not changed at all (apart from having one fewer reference), and so from the perspective of the Line nothing has changed. There are a couple of ways you might get this to work the way you want. One is by adding as an extra layer a proxy object, which could be as simple as: class Proxy(object): def __init__(self, ref): self.ref = ref Instead of adding points to the model, add instances of Proxy that contain the points. When adding points to the lines, add the same Proxy objects instead. Later, when you want to replace a point in the model, leave the Proxy in place but change the Point it contains by modifying the "ref" attribute. Since the Line only directly references the Proxy, it must follow the same ref attribute to access the Point, and so in that way it will "see" the change. The downsides to this approach are that you have to then use the Proxy objects all over the place and explicitly "dereference" them by using the ref attribute all over the place. Another possibility is to subclass the list used to store the points, in order to modify the way that it replaces items. That could look something like this: class UpdateList(list): def __setitem__(self, index, item): if isinstance(index, slice): indices = range(* index.indices(len(self))) items = list(item) if len(indices) != len(items): raise TypeError("Slice length does not match sequence length") for i, x in zip(indices, items): self[i].update(x) else: self[index].update(item) Then you just need to add an "update" method to the Point class (and any other class you might want to use this with) that would update the Point's attributes to match those of another point. The downside here is that this is not very Pythonic, in that somebody familiar with Python who is reading the code would be surprised by the way the model updates work. A third possibility of course would be to just not try to do case B. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGame tutorial?
On Tue, Jun 11, 2013 at 9:47 AM, Eam onn wrote: > Is there a PyGame tutorial out there? I've seen TheNewBoston's tuts, but he > didn't finish his. MetalX100 did a VERY good tutorial. I've been having > trouble with some player movement because he isn't moving smoothly, he jumps. > If I add 5 pixels to his X position if I press a button, jumps to the next 5 > pixels instead of smoothly moving. If I just add 5 pixels normally, he moves > smooth. > > Thanks! Any help is appreciated! There is a whole list of tutorials here: http://www.pygame.org/docs/#tutorials and here: http://www.pygame.org/wiki/tutorials But I already gave you those links, so I don't know what else you are looking for. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGame tutorial?
On Tue, Jun 11, 2013 at 10:56 AM, Eam onn wrote: > Also, is there a specific forum for PyGame or is here fine? Go to pygame.org and click the link "Help (irc, lists)" in the navigation menu. I could give you the direct link, but I want to point out that this stuff is readily available on the pygame website, if you would bother to look. You can ask here, but you would probably find more and better help there. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGame tutorial?
On Tue, Jun 11, 2013 at 10:57 AM, Eam onn wrote: > On Tuesday, June 11, 2013 5:31:22 PM UTC+1, Mark Lawrence wrote: >> Try typing "pygame tutorial" into your favourite search and see what >> comes back, you might be pleasantly surprised. > > Typed it in several times over the past 2 years and nothing. I've been trying > to get into PyGame for 2 years :P I guess it's your lucky day then -- 174,000 hits just went up overnight. -- http://mail.python.org/mailman/listinfo/python-list
Re: Cutting a deck of cards
On Sun, May 26, 2013 at 12:16 PM, Carlos Nepomuceno wrote: > list(range(13 * 4 * decks)) == range(13 * 4 * decks) Not in Python 3. -- http://mail.python.org/mailman/listinfo/python-list
Re: Cutting a deck of cards
On Sun, May 26, 2013 at 12:17 PM, RVic wrote: > Ah, brilliant -- yes, this is so much more elegant in Python: > > #now cut the cards > x = random.randrange(2,range(13 * 4 * decks)) > cards = cards[x:]+cards[:x] Or if for some reason you want to do it in place: cards[x:], cards[:x] = cards[:x], cards[x:] But note that the order of assignments is subtly important there, so unless you have a good reason for doing that, it's probably better just to create a new list for clarity. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get an integer from a sequence of bytes
On Tue, Jun 4, 2013 at 3:49 PM, Chris Angelico wrote: > So... can we cite http://xkcd.com/859/ in two threads at once, or does > that create twice as much tension? No, you just look at one of them upside-down, and then they cancel each other out. -- http://mail.python.org/mailman/listinfo/python-list
Re: My son wants me to teach him Python
On Wed, Jun 12, 2013 at 4:06 PM, John Ladasky wrote: > On Wednesday, June 12, 2013 8:34:15 PM UTC, Chris Angelico wrote: >>Unless you have a good reason for sticking with 2.x, go with 3.x. > > I agree, Chris, I will be teaching my son Python 3 from the start. In fact, > I'm in the middle of a messy upgrade of my own computer to get everything > ready for Python 3. Upgrading my son's machine should be less painful, > because he doesn't need cutting-edge versions of scipy, wxPython or > Matplotlib... but I do hope that some of the game packages, like PyGame, are > Python 3-compatible. I haven't checked into that yet. I've used pygame with Python 3, so it's definitely compatible. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a Super Simple WWW Link, Copy, & Paste into Spreadsheet Program
On Thu, Jun 13, 2013 at 1:41 PM, Joel Goldstick wrote: > there is a python module that reads and writes to excel files. look for > that More than one, actually, and which to use depends on whether "Excel files" means the .xls or .xlsx format. On Windows, the most flexible solution is going to be to just use COM to control the Excel application in reading and writing the files. Outside of Windows, the best bet is usually to work with csv files instead, as Dave suggested. -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't feed the help-vampire
On Fri, Jun 14, 2013 at 6:09 AM, rusi wrote: > Since identifying a disease by the right name is key to finding a > cure: > Nikos is not trolling or spamming; he is help-vampiring. I think he's a very dedicated troll elaborately disguised as a help vampire. Remember that one of the names he previously used to post to this list was "Ferrous Cranus". http://redwing.hutman.net/~mreed/warriorshtm/ferouscranus.htm -- http://mail.python.org/mailman/listinfo/python-list
Re: Timsort in Cpython
On Sat, Jun 15, 2013 at 10:05 PM, wrote: > Yes I've read it. Very interesting read. There are other resources too online > that make it very clear, for instance the wikipedia articles is pretty good. > > Though, if anyone would be interested in helping me out further -- though by > all means, I'm not lazy, I can figure it myself. But, I wanted to pass in > variables into listsort and watch timsort work line by line in gdb. > > listsort(PyListObject *self, PyObject *args, PyObject *kwds) > > I've never worked with Cpython source before, but it looks like PyObject is > just some type of general strut.. I think anyway. How does python represent a > list of ints in source? and what are the two second arguments for, assuming > the first is the list strut. A PyObject* generally references any Python object. The subtype PyListObject* more specifically references a Python list. The above signature corresponds to this Python function signature: def listsort(self, *args, **kwds): The first argument self is the list object to be operated on. The second argument args is a Python tuple containing any other positional arguments that were passed into the method. The third argument kwds is a Python dict containing any keyword arguments that were passed into the method. -- http://mail.python.org/mailman/listinfo/python-list
Re: My son wants me to teach him Python
On Sun, Jun 16, 2013 at 3:55 AM, Cameron Simpson wrote: > On 14Jun2013 20:12, Dennis Lee Bieber wrote: > | [...] PowerShell has been > | available as a download on WinXP and standard on Win7 [PS 3 is a > | download for Win7, stock on real Win8]. > | While I'm not fluent in it, there are some commands I've gotten > | rather engrained... > | > | get-childitem -recurse -filter "*.ad*" | select-string -pattern "with" > | > | finds all the Ada (GNAT convention .ads/.adb) files containing "with" > | statements. And pattern probably is a regex so I could fine tune it to > | just the package withs by using a start of line marker... > > Hmm. > > find . -name '*.ad*' | xargs grep with > > on almost any UNIX system. There's any number of variations on that > depending on exactly what you want. I'm not going to get sucked > into a UNIX/Windows bickerfest here, but your PowerShell example > isn't winning me over. Sound like they reinvented the wheel. Again, > years later:-( As I understand it, PowerShell is intended primarily for automation and scripting, not for interactive console use. -- http://mail.python.org/mailman/listinfo/python-list
Re: Timsort in Cpython
On Wed, Jun 19, 2013 at 11:18 AM, wrote: > The second argument takes the tuple which determines which varialble(key) to > use the comparator on. And the third determines whether to return the list in > ascending or descending order. That's not exactly correct. The arguments are listed in that order, but in fact the arguments to list.sort are keyword-only and cannot be supplied positionally. So the "args" argument is expected to be an empty tuple, and the "kwds" argument is a dict that contains both the "key" and "reverse" arguments, if they were supplied. > But how do these PyObject* look in C? It's a pointer to a struct that contains information like the class and reference count of the object. > How does a PyListObject* look declared in CPython. That's a pointer to a larger struct that shares the same header as the PyObject* struct (which is basically how you do inheritance in C). It adds information like the length and capacity of the list, plus a pointer to an array of PyObject* that stores the contents of the list. > How would something like this list = [2, 1, 5, 6, 10] look in CPython. Or > what about something more complicated -- mlist = [('A',1),('B',2),('C',3)]. To answer that question, you should really delve into the source and see what these structs actually look like. But the first is going to contain an array of five PyObject* values, each of which references an int, while the second is going to contain an array of three PyObject* values, each of which references a tuple. I also recommend that you read the sections of the Python docs that cover the C API, as those should help you understand how these structs are normally handled. -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't feed the troll...
On Wed, Jun 19, 2013 at 4:57 AM, Antoon Pardon wrote: > I don't remember making such a claim. What I do remember is > you among others claiming that the problem was not (so much) > the troll (Nikos) but the others. Count me among those who feel this way. > And your last conclusion is unsound. You forget to include the > fact that once a troll appeared, people reacting badly to the > troll is also to be expected. So with regards to this aspect > there is no difference between the troll and the responders, > both being expected and so no ground to put the preponderance > of blame on the responders. No, I don't agree with that at all. Trolls are to be expected because there will always be those out in the world who want to have a little fun and have no regard for either the list or those who use it. There is nothing to be done about that. On the other hand, the flamers responding to the trolls are regular contributers to the list who presumably do care about keeping the list courteous, respectful, welcoming and enjoyable to participate in. Toward that end, I do not think it is at all unreasonable to expect posters not to throw those principles out the window just because a troll showed up. > Well others don't appreciate you drawing the lines for them > either. If you think others have no business drawing the line > for what is acceptable on this mailinglist/newsgroup then you > have no business drawing such a line yourself. Ultimately there is no enforcement on this list, and all of us must draw our own lines. The question then is: will one draw the line somewhere that is respectful of the list and promotes positive contributions, or somewhere that will push others toward kill-filing one and/or giving up on the list altogether? > I find this a very one-sided view. Those annoyed excessively > by Nikos can't easily ignore him without a cost. There may > be people involved in such a tread they value and like to > read. They can't easily filter the valuable contributions > in such a thread from the nth repeated answer to the same > question either. So their ideal solution is to flame him until he goes away, with the result being that the threads don't exist to begin with? If it's difficult to filter "valuable contributions" from a thread while trying to ignore every other post, think how much harder it will be to got those same "valuable contributions" from a thread that doesn't exist in the first place. Finding anything of value here is clearly not the goal of the flamers, and they might as well just kill the threads at their end -- it's the same net effect for a lot less work, and it doesn't impact the ability of anyone else to interact with those threads if they might wish to. > You ask of others they should tolerate this cost Nikos > brings on for them but you protest when you have to take > on this kind of cost yourself. It's a lot easier to ignore a thread than it is to ignore specific posters within specific threads. And per my response above, your argument that the flamers might not want to just ignore the thread doesn't fly. > I don't know it is that clear. I have the impression it can be > rather effective in cases where the whole community makes it > clear trolls are not welcome. Of course if part of the community > is more bothered by those making trolls feel unwelcome than by > the trolls themselves, such strive will of course attract them. I don't think you understand the troll mindset. They don't care whether the community does or does not welcome them, because they don't view themselves as part of the community. They just want affirmation and attention, which is exactly what they get when somebody flames them. They may even find it amusing that somebody can get so worked up over their disingenuous posts, which then spurs them on to continue trying to get the same reaction. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with the "for" loop syntax
On Wed, Jun 19, 2013 at 3:14 PM, arturo balbuena wrote: > Hello guys... > I´m a begginer in Python, I'm doing a Hangman game, but I'm having trouble > with this blank space. I would be greatful if you help me. :) > > Here's my code: > > http://snipplr.com/view/71581/hangman/ > > When I run the code it says: Invalid Syntax and this is the error: > > http://i.imgur.com/jKYOPMY.png > > http://i.imgur.com/ySoOZFR.png Are you running this in Python 2 or Python 3? In Python 2, print is a statement, not a function, and the end='' arguments would cause a SyntaxError if you're not using the necessary __future__ import. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Thu, Jun 20, 2013 at 11:19 AM, Chris Angelico wrote: > On Fri, Jun 21, 2013 at 3:12 AM, rusi wrote: >> Python (and all the other 'cool' languages) dont have gotchas because >> someone malevolently put them there. >> In most cases, the problem is seen too late and the cost of changing >> entrenched code too great. >> Or the problem is clear, the solution is not etc etc. > > Or, in many MANY cases, the choice was the right one, but isn't > obvious to everyone. I think it's worth pointing out that changing function defaults to late-binding would merely change the nature of the gotcha, not eliminate it. words = ("one", "two", "red", "blue", "fish") def join_strings(strings=words): return ' '.join('%s %s' % (s, strings[-1]) for s in strings[:-1]) # Later: words = open("gettysburg_address.txt", "r").read().split() # Oops, the default argument of join_strings just changed. Additionally, with late-binding semantics the default values would no longer be default *values*. They would be initialization code instead, which sort of flies in the face of the idea that late-binding would somehow be better for functional programming -- if the default expressions have no side effects and since they don't depend on the function arguments, why should they need to run more than once? If the goal is indeed to make the the functions more functional, then the proper solution would be to keep the binding early but just disallow mutable defaults altogether -- which is tricky to achieve in Python, so we simply emulate it with the advice "don't use mutable function defaults". -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't feed the troll...
On Thu, Jun 20, 2013 at 3:41 AM, Antoon Pardon wrote: > There are two problems with your reasoning. The first is that you > are equivocating on "expect". "Expect" can mean you will be surprised > if it doesn't happen but it can also mean you will feel indignant or > disappointed or something similar when it doesn't happen. Perhaps I am, but it doesn't change my argument in any way. When a troll shows up I am not happy about it, but I am not disappointed either, because Trolls Happen. I am disappointed when members of the community act in ways that are detrimental to the community. Better? > The second problem is that I find it a one sided view. If you want > a courteous, respectful, welcoming and enjoyable to participate in > list, shouldn't you also be careful in not encouraging trollish > behaviour? Being courteous to or cooperating with someone behaving > trollishly, is IMO enabling that kind of behaviour and so those > doing so, seem to already throw those priciples out the window because > they are cooperating with the troll who is making this list less > courteous, respectful, welcoming and enjoyable to participate in > for a significant number of people. You'll note that I haven't engaged Nikos at all in some time. That's because I think he's a troll. I think though that those who are continuing to help him do so because they do not think that he is a troll. I am not going to try to thrust my own opinion of who is or is not a troll and who can or cannot be given help upon the list -- that is their opinion, they are entitled to it, and maybe they see something in the exchange that I don't. That is different in my eyes from somebody who does identify Nikos as a troll and then goes on to egg him on anyway, whether it be courteous or belligerent. -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't feed the troll...
On Fri, Jun 21, 2013 at 3:18 AM, Antoon Pardon wrote: > Op 21-06-13 04:40, Ian Kelly schreef: > >> On Thu, Jun 20, 2013 at 3:41 AM, Antoon Pardon >> wrote: >>> There are two problems with your reasoning. The first is that you >>> are equivocating on "expect". "Expect" can mean you will be surprised >>> if it doesn't happen but it can also mean you will feel indignant or >>> disappointed or something similar when it doesn't happen. >> >> Perhaps I am, but it doesn't change my argument in any way. When a >> troll shows up I am not happy about it, but I am not disappointed >> either, because Trolls Happen. I am disappointed when members of the >> community act in ways that are detrimental to the community. Better? > > But that last one doesn't ring true. Enabling a troll is also acting > in a way that is detrimental to the community. But I haven't seen > you express disappointment in that. I've already explained why that is. First, it's less anguish to kill-file one troll than several vitriolic regulars (and I realize that he keeps changing his name, but fortunately I think he's only used three different /addresses/ in the time that he's been posting). Second, I don't want to bully anybody into not trying to help a user where they want to and believe that they can. It may be "enabling" for the troll, but it's unhealthy for the list in general. > Those that expressed their disappointment with the enabling behaviour > were more or less told they should deal with it. So tell me, why > should your disappointment merrit more consideration? When did I ever say that it should? I'm just putting my own opinions on the subject out there. > If you want the python list to be a hospitable place, you have > to be attentive for signals from other contributors that the > level of hospitability is decreasing for them. If you ignore > them or brush them off you then risk loosing them as cooperators > to that goal. So if later you find the level of hospitability > is decreasing for you, you are more likely to get ignored or > brushed off too. The level of hospitality is already decreasing for me. That's why I'm speaking up. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Fri, Jun 21, 2013 at 7:15 PM, Steven D'Aprano wrote: > On Fri, 21 Jun 2013 23:49:51 +0100, MRAB wrote: > >> On 21/06/2013 21:44, Rick Johnson wrote: > [...] >>> Which in Python would be the "MutableArgumentWarning". >>> >>> *school-bell* >>> >> I notice that you've omitted any mention of how you'd know that the >> argument was mutable. > > That's easy. Just call ismutable(arg). The implementation of ismutable is > just an implementation detail, somebody else can work that out. A > language designer of the sheer genius of Rick can hardly be expected to > worry himself about such trivial details. While we're at it, I would like to petition for a function terminates(f, args) that I can use to determine whether a function will terminate before I actually call it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Fri, Jun 21, 2013 at 7:15 PM, Rick Johnson wrote: >> > Let's imagine for a second if Python allowed mutable keys in >> > a dictionary, >> which it does > > Am i just to take your word for this? You cannot provide an > example? Here, allow me to "break the ice": > > # Literal > py> d = {[1]:2} > Traceback (most recent call last): > File "", line 1, in > d = {[1]:2} > TypeError: unhashable type: 'list' > # Symbol > py> lst = [1] > py> d = {lst:2} > Traceback (most recent call last): > File "", line 1, in > d = {lst:2} > TypeError: unhashable type: 'list' > > Hmm, maybe only certain mutables work? Great, more esoteric > rules! Feel free to enlighten me since i'm not going to > waste one second of my time pursuing the docs just to learn > about ANOTHER unintuitive PyWart i have no use for. The answer to this conundrum is staring you in the face. Note that the TypeError complains that you passed it an "unhashable" type, and not that you passed it a "mutable" type. If you want to take a mutable type and make it hashable, just add a __hash__ method. class HashableList(list): def __hash__(self): return 42 >>> d = dict() >>> hl = HashableList(range(5)) >>> hl2 = HashableList(range(6, 10)) >>> d[hl] = 10 >>> d[hl2] = 20 >>> d {[0, 1, 2, 3, 4]: 10, [6, 7, 8, 9]: 20} Additionally, instances of user-defined classes are, by default, both mutable and hashable. This is safe because equality and hashing for such objects are by default based on identity. If you override the __eq__ method though, then you lose hashability unless you explicitly override __hash__ as well. > >> Now, I don't really believe that you think that the user >> shouldn't be protected from doing one idiotic thing with >> mutable dict keys but should be protected from doing >> another idiotic thing with mutable default arguments, >> especially as you've already been given a use case for the >> latter. So I assume that The Benevolent Approach is not >> the approach you would have gone for if you had designed >> the language, right? If so then let's ignore it. > > You are correct. Finally, we can agree on something. > >> > >> > The Apathetic Approach: >> > >> > I could just assume that a programmer is responsible for the >> > code he writes. If he passes mutables into a function as >> > default arguments, and then mutates the mutable later, too >> > bad, he'll understand the value of writing solid code after >> > a few trips to exception Hell. >> >> It seems to me that this is exactly what currently happens. > > (is this lazy readers day? I swear i explained this earlier) > > And here is where you are wrong. In the current implementation > python functions carry the state of mutable default arguments > between successive calls. That's a flaw. Observe: > > py> def foo(arg=[]): > ... arg.append(1) > ... print(arg) > ... > py> foo() > [1] > py> foo() > [1, 1] > py> foo() > [1, 1, 1] > > No, no, NO! That's wrong! Subroutines should be stateless. > That means that an empty mutable default argument will > ALWAYS be empty at each call of the subroutine. This is > what should happen: > > py> def foo(arg=[]): > ... arg.append(1) > ... print(arg) > ... > py> foo() > [1] > py> foo() > [1] > py> foo() > [1] > > Yes, Yes, YES! That is intuitive! That is sane! Now, what if > we pass a reference to a mutable object? What then. Well, let's > see: > > py> lst = range(5) > py> lst > [0, 1, 2, 3, 4] > py> def foo(arg=lst): > ... arg.append(1) > ... print(arg) > ... > py> foo() > [0, 1, 2, 3, 4, 1] > py> foo() > [0, 1, 2, 3, 4, 1, 1] > > That's fine. Because the object was already created OUTSIDE > the subroutine. So therefore, modifications to the mutable > are not breaking the fundamental of statelessness INSIDE > subroutines. The modification is merely a side effect, and > the subroutine is unconcerned with anything that exists > beyond it's own scope. > > IS ALL THIS REGISTERING YET? DO YOU UNDERSTAND? > >> > >> > The Malevolent Approach (disguised as beneva-loon-icy): >> > >> > I could use early binding to confuse the hell out of him and >> > enjoy the laughs with all my ivory tower buddies as he falls >> > into fits of confusion and rage. Then enjoy again when he >> > reads the docs. Ahh, the gift that just keeps on giving! >> My question was about how you think the language should >> work, not about what your buddies should or shouldn't >> enjoy. > > My buddies? This design flaw is NOT my brain child. Your > barking up the wrong tree pal. > >> In terms of how a language actually works, is th
Re: Default Value
On Fri, Jun 21, 2013 at 7:37 PM, Chris Angelico wrote: class HashableList(list): > def __hash__(self): > return 42 Hey, we both picked exactly the same example! -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Sat, Jun 22, 2013 at 10:49 AM, Dennis Lee Bieber wrote: > On Fri, 21 Jun 2013 19:27:42 -0600, Ian Kelly > declaimed the following: > >>While we're at it, I would like to petition for a function >>terminates(f, args) that I can use to determine whether a function >>will terminate before I actually call it. > > Maybe in a universe with different physical constants... > > Otherwise I think you have encountered > http://en.wikipedia.org/wiki/Halting_problem (consider: could your function > conclude that it terminates when fed it's own code) Yes, that was the joke. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can i fix this?
On Sat, Jun 22, 2013 at 3:50 PM, Борислав Бориславов wrote: > this doesent help me at all It shows you how to include multiple statements in the body of the if block. If you're having trouble getting it to work, then please copy and paste the exact code that you're running for us along with the error message that you get. But we can't help you solve your problem if we don't know what it is. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Sat, Jun 22, 2013 at 9:20 PM, Steven D'Aprano wrote: > * on the down side, automatic delegation of special double-underscore > methods like __getitem__ and __str__ doesn't work with new-style classes. I actually consider that an up side. Sure it's inconvenient that you can't delegate all such methods at once just by overriding __getattribute__, but it would be more troublesome to *accidentally* implement such methods because you implemented __getattribute__. And then there are methods that really should not be delegated in the first place, like __del__. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Sat, Jun 22, 2013 at 11:23 PM, Steven D'Aprano wrote: > On Sat, 22 Jun 2013 22:27:10 -0600, Ian Kelly wrote: >> I actually consider that an up side. Sure it's inconvenient that you >> can't delegate all such methods at once just by overriding >> __getattribute__, but it would be more troublesome to *accidentally* >> implement such methods because you implemented __getattribute__. > > It's hard to see a case where that would be a bad thing. > > 1) If the proxied object doesn't include __dunder__ methods, then the > proxy will just end up up calling the default object dunder methods, > exactly as if they weren't proxied. > > 2) If the proxied object does include dunders, then you generally want > the proxy to call them, with perhaps one or two exceptions, which need to > be overridden regardless of whether they are dunders or not. Proxying objects is not the only use of __getattribute__. >> And >> then there are methods that really should not be delegated in the first >> place, like __del__. > > If you're using __del__, you're probably doing something wrong :-) > > I suppose that __del__ is a good counter-example, but (1) hardly any > classes use __del__, and (2) for those that do, it's *way* simpler to > manually override __del__ in the proxy than to manually delegate every > dunder method you care about. There are typically a lot of dunder methods > you care about. If you manually override __del__ in the proxy, then as far as the garbage collector is concerned, your proxy object has a __del__ method (even if it does nothing), and so it will be treated differently from an object without a __del__ method. > It is not the case that dunder methods cannot be automatically proxied > because somebody deliberately designed Python to work that way. It's an > accidental side-effect of the way new-style classes resolve method calls, > due to decisions made for other reasons having nothing to do with > delegation. Can you elaborate or provide a link? I'm curious to know what other reason there could be for magic methods to behave differently from normal methods in this regard. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Sun, Jun 23, 2013 at 7:35 AM, Adam Jiang wrote: > Another question raised here is that what is the proper way to refer > to parent class? For example, > > class A(object): > def __init__(self, arg): > print "A" > > class B(A): > def __init__(self, arg): > super(B, self).__init__(arg) > > Is this correct? As the result, whenever you wanted to refer to a > method in parent class, super() functions has to be called. This seems > inefficient. Generally, use super() any time you want to refer to a class attribute (such as a method) in a parent class that is overridden in the child class. Also note that in Python 3, the call "super(B, self)" can be condensed to just "super()". If you're worried about efficiency, you can also explicitly name the superclass in order to call the method directly, like: A.__init__(self, arg) However, super() is generally considered the right way to do this, in order to avoid repeating the parent class name, for brevity in Python 3, and because it is needed to correctly handle some cases of multiple inheritance. > How to refer to a field defined in parent class? For instance attributes or attributes that haven't been overridden, just write "self.attribute_name". -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Sun, Jun 23, 2013 at 10:49 AM, Roy Smith wrote: > One thing I've never understood about Python 2.x's multiple inheritance > (mostly because I almost never use it) is how you do something like this: > > class Base1(object): >def __init__(self, foo): > self.foo = foo > > class Base2(object): >def __init__(self, bar): > self.bar = bar > > class Derived(Base1, Base2): >def __init__(self, foo, bar): > # now what??? > > I need to call __init__() in both of my base classes. I don't see how > super() can do that for me. I assume I would just do: > >def __init__(self, foo, bar): > Base1.__init__(self, foo) > Base2.__init__(self, bar) > > am I missing something here? Yes, you're missing that super() does not simply call the base class, but rather the next class in the MRO for whatever the type of the "self" argument is. If you write the above as: class Base1(object): def __init__(self, foo, **kwargs): super(Base1, self).__init__(**kwargs) class Base2(object): def __init__(self, bar, **kwargs): super(Base2, self).__init__(**kwargs) class Derived(Base1, Base2): def __init__(self, **kwargs): super(Derived, self).__init__(**kwargs) And then you create an instance of Derived by calling Derived(foo='foo', bar='bar') and trace the call chain, you find that Derived.__init__ will call Base1.__init__(foo='foo', bar='bar'), which extracts its argument and then calls (surprise!) Base2.__init__(bar='bar'), which again extracts its argument and then calls object.__init__(), ending the chain. Of course if you create an instance of Base1, then the Base1 super call will next call object.__init__ directly, instead of Base2.__init__. This happens because Base2 occurs after Base1 in the MRO for the class Derived, but Base2 does not appear at all in the MRO for the class Base1. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Sun, Jun 23, 2013 at 11:08 AM, Ian Kelly wrote: > On Sun, Jun 23, 2013 at 10:49 AM, Roy Smith wrote: >> am I missing something here? > > Yes, you're missing that super() does not simply call the base class, > but rather the next class in the MRO for whatever the type of the > "self" argument is. If you write the above as: Incidentally, although super() is useful, it's not perfect, and this is one of my grievances with it: that a user can, based upon the name, draw an inaccurate assumption about what it does without reading or fully understanding the documentation on it, which might then result in misusing it. There might still be some code I wrote out there from when I first started using Python that looks something like: def __init__(self): super(Base, self).__init__() Mixin.__init__(self) Which is simply wrong, wrong, wrong. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Sun, Jun 23, 2013 at 11:36 AM, Steven D'Aprano wrote: > On Sun, 23 Jun 2013 11:18:41 -0600, Ian Kelly wrote: > >> Incidentally, although super() is useful, it's not perfect, and this is >> one of my grievances with it: that a user can, based upon the name, draw >> an inaccurate assumption about what it does without reading or fully >> understanding the documentation on it, which might then result in >> misusing it. > > Wait a second... are you saying that the Python developers created an > advanced language feature relating to multiple inheritance, one of the > most complex OOP concepts around, so difficult that most other languages > simply prohibit it completely, and it wasn't instantly and correctly > intuited by every single programmer based only on the name? Oh my stars, > somebody call Ranting Rick, he needs to write a PyWart post to expose > this scandal!!! Mostly I'm saying that super() is badly named. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Sun, Jun 23, 2013 at 12:46 PM, Steven D'Aprano wrote: > All is not lost, there are ways to make your classes cooperative. The > trick is to have your classes' __init__ methods ignore keyword arguments > they don't know what to do with. object used to do the same thing, but it > no longer does, so you need to add an extra class just before object to > swallow any args before they read object. > > > class Blocker(object): > def __init__(self, **kwargs): > # Block kwargs from reaching object > super(Blocker, self).__init__() I don't like the idea of doing this with a cooperative __init__ method. If any keyword arguments were passed that weren't consumed, that is probably a bug, and this just swallows the exception instead of reporting it. Of course, if you're doing cooperative inheritance with some other method that doesn't exist on object, then this technique is necessary to prevent the topmost class from trying to call that method on object and erroring out. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Sun, Jun 23, 2013 at 12:50 PM, Steven D'Aprano wrote: > What else would you call a function that does lookups on the current > object's superclasses? Well, as James Knight points out in the "Super Considered Harmful" article, the equivalent in Dylan is called "next-method", which isn't a valid identifier in Python but seems like a reasonable starting point. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Mon, Jun 24, 2013 at 9:00 AM, Rotwang wrote: > On 24/06/2013 07:31, Steven D'Aprano wrote: > >> I daresay that there are good reasons why new-style classes don't do the >> same thing, but the point is that had the Python devs had been >> sufficiently interested in keeping the old behaviour, and willing to pay >> whatever costs that would require, they could have done so. > > > Sure, though the above behaviour was probably easier to achieve with > old-style classes than it would have been with new-style classes because all > instances of old-style classes have the same type. But I don't doubt that > you're correct that they could have done it if they wanted. It seems to me that the important difference with new-style classes is that they suddenly have metaclasses and are themselves just ordinary objects, and so it is important that they consistently resolve calls in the same way that all other objects do. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Mon, Jun 24, 2013 at 9:58 AM, Mark Janssen wrote: >>> Mostly I'm saying that super() is badly named. >> >> What else would you call a function that does lookups on the current >> object's superclasses? > > ^. You make a symbol for it. ^__init__(foo, bar) On the one hand, eww. On the other hand, with the changes to super in Python 3 to make it more magical, it might as well be syntax. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this PEP-able? fwhile
On Mon, Jun 24, 2013 at 1:52 PM, 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'. I would advocate using the break myself. Another alternative is this: for X in itertools.takewhile(lambda X: conditionZ, ListY): ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this PEP-able? fwhile
On Mon, Jun 24, 2013 at 1:52 PM, wrote: > Syntax: > > fwhile X in ListY and conditionZ: Also, this syntax is ambiguous. Take for example the statement: fwhile X in ListA and ListB and ListC and ListD: At which "and" does the iterable expression stop and the condition expression begin? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this PEP-able? fwhile
On Mon, Jun 24, 2013 at 3:01 PM, Ian Kelly wrote: > On Mon, Jun 24, 2013 at 2:34 PM, Fábio Santos > wrote: >> This can probably be best achieved by adding to the existing for loop, >> so maybe taking advantage of the existing for...if syntax and adding >> for...while would be a better idea? > > The for...if syntax only exists for comprehensions and generators. If > we're going to add for...while for loops, then we might as well go > ahead and add for...if loops there as well. Which of course brings us to the for...if...while loop. Or should it be for...while...if? Or do we allow both, and if so, are the semantics the same or different? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this PEP-able? fwhile
On Mon, Jun 24, 2013 at 2:34 PM, Fábio Santos wrote: > This can probably be best achieved by adding to the existing for loop, > so maybe taking advantage of the existing for...if syntax and adding > for...while would be a better idea? The for...if syntax only exists for comprehensions and generators. If we're going to add for...while for loops, then we might as well go ahead and add for...if loops there as well. That said, I do like this syntax better than "fwhile". -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this PEP-able? fwhile
On Mon, Jun 24, 2013 at 4:41 PM, Fábio Santos wrote: > > On 24 Jun 2013 22:29, "Ian Kelly" wrote: >> >> On Mon, Jun 24, 2013 at 2:34 PM, Fábio Santos >> wrote: >> > This can probably be best achieved by adding to the existing for loop, >> > so maybe taking advantage of the existing for...if syntax and adding >> > for...while would be a better idea? >> >> The for...if syntax only exists for comprehensions and generators. If >> we're going to add for...while for loops, then we might as well go >> ahead and add for...if loops there as well. >> >> That said, I do like this syntax better than "fwhile". > > Good point. Still, I don't see why for..if doesn't exist in for loops > anyway. It may be lack of foresight, but I don't understand why at all. Because it adds more syntax to learn when learning the language, it introduces more maintenance overhead, and it offers no clear benefit over simply nesting an if inside a for. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this PEP-able? fwhile
On Mon, Jun 24, 2013 at 4:35 PM, Chris Angelico wrote: > On Tue, Jun 25, 2013 at 8:30 AM, 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 > > True. There are times I do wish for a 'goto'. But if goto were > implemented, I would also use it for jumping _into_ loops, and I'm not > sure that's going to make the feature popular :) You can have labeled break and continue without going all the way to a goto statement. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this PEP-able? fwhile
On Mon, Jun 24, 2013 at 6:41 PM, wu wei wrote: > It's still possible by raising a StopIteration within the condition > function: > > def is_part_of_header(x): > if header_condition: > return True > else: > raise StopIteration Which is basically just taking the break and moving it to somewhere else in the code, and meanwhile rendering the is_part_of_header function non-reusable. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Sat, Jun 22, 2013 at 8:40 AM, Antoon Pardon wrote: > Are you two guys now egging on Rick Johnson? No. Rick is incorrigible, and I would have been surprised if he responded to that anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this PEP-able? fwhile
On Mon, Jun 24, 2013 at 2:33 PM, wrote: > Ian, > > Regarding your first message breaks are anathema (for many) and your other > alternative is complicated. > > Regarding your second post, anding of lists is allowed, but generally > returns non-utile results, but point taken. > I guess technically it could be the last statement, with the condition just > being ListD in your example. To make > the condition more complex (in your example) you'd have to add parens. I'd probably have gone with the first "and". The condition is more likely to use ands than the iterable, and also I expect it would be easier to parse with the simple rule that the first "and" divides it. The ambiguity is nonetheless a black mark against the syntax. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this PEP-able? fwhile
On Tue, Jun 25, 2013 at 1:21 AM, Chris Angelico wrote: > On Tue, Jun 25, 2013 at 2:20 PM, Benjamin Kaplan > wrote: >> The reason I was given (which I promptly ignored, of course) is that >> it's "best practice" to only have one exit point for a block of code. >> Only one way of terminating your loop, only one "return" per function, >> never use exceptions, etc. I think it originally came about as a way >> to make sure that your clean-up code was called (and to make it easier >> for code reviewers to make sure your clean up code was called) and >> then started being passed around as a rule among programming teachers >> who didn't have any experience outside the classroom. > > I've heard that "one exit point" rule before, too, but never any > justification for it. Your explanation does at least make sense > (albeit only in a language without even RAII), but I don't like silly > rules like that :) In my experience the sorts of people who preach "one exit point" are also all about defining preconditions and postconditions and proving that the postconditions follow from the preconditions. I think that the two are linked, because the "one exit point" rule makes those sorts of proofs simpler. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Sun, Jun 23, 2013 at 1:33 PM, Antoon Pardon wrote: > Op 23-06-13 18:35, Steven D'Aprano schreef: >> Please don't. This is false economy. The time you save will be trivial, >> the overhead of inheritance is not going to be the bottleneck in your >> code, and by ignoring super, you only accomplish one thing: >> >> - if you use your class in multiple inheritance, it will be buggy. > > > Which is why I don't understand that the python standard library still > contains that kind of code. At least it did in 3.2 and I saw nothing > in the 3.3 release notes that would make me suspect this has changed. This bothers me as well. If you look at Raymond Hettinger's "super() considered super" article, he includes the (correct) advice that super() needs to be used at every level of the call chain. At the end of the article, he offers this example to show how "easy" multiple inheritance can be: from collections import Counter, OrderedDict class OrderedCounter(Counter, OrderedDict): 'Counter that remembers the order elements are first seen' def __repr__(self): return '%s(%r)' % (self.__class__.__name__, OrderedDict(self)) def __reduce__(self): return self.__class__, (OrderedDict(self),) oc = OrderedCounter('abracadabra') Which is pretty cool in its simplicity, but here's the rub (which I have previously noted on this list): OrderedDict doesn't use super. Counter does, but not cooperatively; it just calls super().__init__() with no arguments. So the fact that this example works at all is basically luck. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
On Sat, Jun 22, 2013 at 8:49 PM, Gene Heskett wrote: > On Saturday 22 June 2013 22:46:51 christheco...@gmail.com did opine: > >> Writing simple program asking a question with the answer being >> "yes"...how do I allow the correct answer if user types Yes, yes, or >> YES? >> >> Thanks > > AND each character coming in from the keyboard with $DF before adding it to > the comparison buffer. Makes it all uppercase. Then compare it to the > uppercase YES. It's not working for me. >>> ''.join(chr(ord(c) & 0xdf) for c in 'ναί') == 'ΝΑΊ' False >>> ''.join(chr(ord(c) & 0xdf) for c in 'ναί') '\x9d\x91\x8f' -- http://mail.python.org/mailman/listinfo/python-list
Re: Limit Lines of Output
On Tue, Jun 25, 2013 at 2:31 PM, Joshua Landau wrote: > 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() Or simply: $ python my_script.py | less It works the same way in Windows: C:\> python my_script.py | more -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Tue, Jun 25, 2013 at 3:58 PM, Mark Janssen wrote: > Ah, and here we see the weakness in the object architecture that has > evolved in the past decade (not just in Python, note). It hasn't > really ironed out what end is what. Here's a proposal: the highest, > most "parental", most general object should be in charge, not > subclasses calling specific parent's init methods > (Parent.__init__(myparams)), etc. -- ***THIS IS WHERE WE WENT > WRONG***. > > After the "type/class unification", python tried to make the most > generic, most useless class be the parent of *all of them*, but > there's been no use whatsoever in that. It was a good idea in the > beginning, so pure as it was, but it has not panned out in practice. > Sorry... So instead of super(), you would have sub()? It's an interesting concept, but I don't think it changes anything. You still have to design your classes cooperatively if you expect to use them with multiple inheritance. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Tue, Jun 25, 2013 at 4:17 PM, Chris Angelico wrote: > The main problem is getting to the top/end of the call chain. Classic > example is with __init__, but the same problem can also happen with > other calls. Just a crazy theory, but would it be possible to > construct a black-holing object that, for any given method name, > returns a dummy function that ignores its args? (Other forms of > attribute lookup aren't going to be a problem, I think, so this can be > just methods/functions.) Then you just subclass from that all the > time, instead of from object itself, and you should be able to safely > call super's methods with whatever kwargs you haven't yourself > processed. Would that work? class BlackHole(object): def __getattr__(self, attr): return lambda *args, **kwargs: None There's no way to restrict it to just methods, because there's no fundamental difference in Python between methods and other attributes, and at the point that you're looking it up you have no way of knowing whether the result is about to be called or not. And even if there were, this would be an excellent way to hide bugs. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Tue, Jun 25, 2013 at 4:38 PM, Mark Janssen wrote: > Sorry my last message got sent prematurely. Retrying... > >> So instead of super(), you would have sub()? It's an interesting >> concept, but I don't think it changes anything. You still have to >> design your classes cooperatively if you expect to use them with >> multiple inheritance. > > Yes, and let new instances of the child classes automatically ensure > the contracts of the parent classes -- managed within the Python > interpreter, not the developer. It sounds like you want to be using Eiffel, not Python. > As for sub(), I suppose it could be called delegate(). You can call it that, but you'll just be muddying the waters since there's already a perfectly good pattern by that name, which involves having multiple distinct objects and has nothing to do with inheritance. > The issue of classes cooperating isn't as big as it seems, because > since you're working now from a useful, agreed-upon common base (the > non-negotiable, but also non-arbitrary) machine types, you're now all > (the python and ideally the *object* community) speaking the same > language. Who's going to argue about integers (as the atomic type) > and sets (as the most basic grouping type) being THE common set of > bases for everything else? I mean, it doesn't get anymore ideal and > pure than integers and sets. Combining integers with sets I can make > a Rational class and have infinite-precision arithmetic, for example. I don't see how this solves anything. At some point you have to be able to add methods and attributes to your objects. For example, your Rational class is going to need some sort of "reduce" method to reduce a Rational instance to lowest terms. That's not a method that belongs on an integer or set type. If you can't add functionality, then all you will ever have are integers and sets, and if you can add functionality, then what difference does it make what your fundamental base class is? >From a programming perspective, I think it is proper that "object" is the most fundamental base class, because all it has is identity. Integers and sets add other functionality on top of that. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Tue, Jun 25, 2013 at 5:07 PM, Ian Kelly wrote: > On Tue, Jun 25, 2013 at 4:38 PM, Mark Janssen > wrote: >> The issue of classes cooperating isn't as big as it seems, because >> since you're working now from a useful, agreed-upon common base (the >> non-negotiable, but also non-arbitrary) machine types, you're now all >> (the python and ideally the *object* community) speaking the same >> language. Who's going to argue about integers (as the atomic type) >> and sets (as the most basic grouping type) being THE common set of >> bases for everything else? I mean, it doesn't get anymore ideal and >> pure than integers and sets. Combining integers with sets I can make >> a Rational class and have infinite-precision arithmetic, for example. > > I don't see how this solves anything. At some point you have to be > able to add methods and attributes to your objects. For example, your > Rational class is going to need some sort of "reduce" method to reduce > a Rational instance to lowest terms. That's not a method that belongs > on an integer or set type. If you can't add functionality, then all > you will ever have are integers and sets, and if you can add > functionality, then what difference does it make what your fundamental > base class is? Oh, and just in case you're not aware, Python already has a Fraction class that supports unlimited-precision arithmetic. It doesn't need to inherit from tuple to accomplish this, and in fact that would be a bad way to approach it, since a fraction is *not* a tuple. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Tue, Jun 25, 2013 at 5:19 PM, Mark Janssen wrote: >>> Combining integers with sets I can make >>> a Rational class and have infinite-precision arithmetic, for example. >> >> Combining two integers lets you make a Rational. > > Ah, but what is going to group them together? You see you've already > gotten seduced. Python already uses a set to group them together -- > it's called a Dict and it's in every Class object. When you inherit a "set" to make a Rational, you're making the statement (to the interpreter, if nothing else) that a Rational is-a set. When a Python class uses an instance dict to store the numerator and denominator of a Fraction, it's not *inheriting* Fraction from dict, which is good because a Fraction is not a dict. It's merely *using* a dict. It comes back once again to the distinction between inheritance and composition. >> Also, you need an >> ordered set - is the set {5,3} greater or less than the set {2} when >> you interpret them as rationals? > > The ordering (and hence the interpretation) is done WITHIN the Class > (i.e. the SET as I say above). So "set" is just your name for a class? I understood earlier that with integers and sets you were trying to derive your type system from number theory. Now it sounds like you want sets to be containers of attributes. Which is it? -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Tue, Jun 25, 2013 at 7:07 PM, Mark Janssen wrote: >> When you inherit a "set" to make a Rational, you're making the >> statement (to the interpreter, if nothing else) that a Rational is-a >> set. > > No you don't *inherit* a set to make a Rational, although you gain a > set to make it. Okay, then. Since you started this discussion from the topic of multiple inheritance I was under the impression that you were talking about using inheritance to construct Rationals from integers and sets. Evidently that is not so, and you've been talking about composition all along, in which case I have no idea how any of this relates to your original suggestion of putting superclasses "in charge" of their subclasses. -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't feed the troll...
On Mon, Jun 24, 2013 at 7:37 AM, Antoon Pardon wrote: > What do you mean with not a participant in the past? As far > as I can see his first appearance was in dec 2011. That is > over a year ago. It also seems that he always find people > willing to engage with him. Is how the group treats him > not also an aspect in deciding whether he belongs or not? Although it's true that he's been around for a while, it has in my mind only been very recently that his posts have started to become a problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Wed, Jun 26, 2013 at 5:54 PM, Steven D'Aprano wrote: > No. But "the current object" is not Base1, but an instance of Derived, > and Base2 *is* an ancestor of Derived. Perhaps if I had said "self" > instead of current object, you wouldn't have made this error. If so, I > apologise for confusing you. If I am reading a class definition and see the code super().__init__(), and I am not familiar with super() and do not bother to go look it up in the docs because it looks "obvious" (or perhaps I have read a tutorial that simply mentions that super() is used to call methods from a superclass and elides over the details) -- my assumption is not going to be that super() is looking into superclasses relative to the class of self, but more simply that super() is looking into superclasses relative to the class that I'm currently reading. Why? Because that's the way that "super" works in every other language I know of that has it. Java: super looks depth-first from the contextual class (no multiple inheritance allowed) Ruby: super looks depth-first from the contextual class (no multiple inheritance allowed) Objective-C: super looks depth-first from the contextual class (no multiple inheritance allowed) Perl 5: by default, super looks depth-first from the contextual class (multiple inheritance IS allowed; the C3 linearization (MRO) CAN be used, but it must first be explicitly enabled with a pragma directive) Now if you're coming from Java, Ruby, or Objective-C and reading a Python super() statement, then hopefully you will stop and think, "Hey, wait a minute. [Other language] doesn't have multiple inheritance and Python does, so how does super() work here?" More likely though you're not even thinking about multiple inheritance when you read that statement, and you just assume that it works exactly like the super keyword that you're used to, and you move on. -- http://mail.python.org/mailman/listinfo/python-list