Re: Can global variable be passed into Python function?
Mark H. Harris wrote: if (n**2 D(1)): a = __atan__(n) elif (n == D(1)): a = gpi/4 elif (n == D(-1)): a = -(gpi/4) elif (n D(-1)): a = __atan__Lt_neg1__(n) else: a = __atan__Gt_1__(n) That's not a candidate for a switch statement, because the comparisons are not all equality comparisons. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: posting code snippets
Grant Edwards wrote: You drag out the lab scope, logic analyzer, spectrum analyzer, sweep generator, strip plotter, and the machine that goes ping. You start to get everything set up to nail that problem securely to the dissecting board. Long before you actually get to that point, the problem becomes intimidated and reveals itself and a solution. No! No! Not the comfy spectrum analyser! I give up! -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Functional programming
Steven D'Aprano wrote: Given that x is an integer, and that you add 1 (also an integer) to it, is it really necessary to tell the compiler that add_one returns an integer? What else could the output type be? Just because the compiler *can* infer the return type doesn't necessarily mean it *should*. When I was playing around with functional languages, I ended up adopting the practice of always declaring the types of my functions, because it helps the *human* reader. (It also helped the compiler produce comprehensible error messages in the event of a type error.) -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Working with the set of real numbers
Chris Angelico wrote: In constant space, that will produce the sum of two infinite sequences of digits. It's not constant space, because the nines counter can grow infinitely large. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Functional programming
Marko Rauhamaa wrote: Python doesn't have anonymous inner classes, but it has named inner classes, and that's quite sufficient. I would say it's Python's closures that make up for not having Java's inner classes. Or to put it another way, inner classes are Java's kludgy way of working around a lack of closures. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Proper conversion of timestamp
Igor Korot wrote: What I have is a timestamp which reads: 1289410678L. Trying to convert this into the datetime object in Python using: import datetime datetime.datetime.fromtimestamp( stamp ) produces the error: timestamp out of range for platform localtime()/gmtime() function. Divide the timestamp by 1000.0 to give floating point seconds, and then use datetime.fromtimestamp(). d = datetime.datetime.fromtimestamp(1289410678 / 1000.0) d datetime.datetime(1970, 1, 16, 10, 10, 10, 678000) d.strftime(%Y-%m-%d-%H:%M:%S.%f)[:-3] '1970-01-16-10:10:10.678' -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Tuples and immutability
Duncan Booth wrote: Is there any reason why tuples need to throw an exception on assigning to the element if the old value and new value are the same object? It would make introspection misleading, because tuples would have a __setitem__ method event though they don't actually support item assignment. Also, it would solve the problem for tuples in particular, but not for any other immutable type -- they would all have to implement the same behaviour independently to enjoy the benefit. Here's another idea: If the __iadd__ method returns the same object, *and* the LHS doesn't have a __setitem__ method, then do nothing instead of raising an exception. Peter Otten wrote: Traceback (most recent call last): File stdin, line 2, in module File stdin, line 4, in __setitem__ TypeError: 257 is not 257 I'm not sure help is the right word here ;) I don't think that's a problem, because the use case being addressed is where the object performs in-place modification and always returns itself. Any object that doesn't return itself is not modifying in-place, even if the returned object happens to be equal to the original one. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Tuples and immutability
Ian Kelly wrote: class LessThanFilter: def __init__(self, the_list): self._the_list = the_list def __getitem__(self, bound): return [x for x in self._the_list if x bound] filter = LessThanFilter([10, 20, 30, 40, 50]) filter[25] += [15, 17, 23] Should that last line not raise an exception? In this case it will fail to catch what is probably an error, but you can't expect the language to find all your bugs for you. If you wrote the same bug this way: filter[25].extend([15, 17, 23]) it wouldn't be caught either. What's happening is that we're trying to use the syntax a += b to mean two different things: 1) Shorthand for a = a + b 2) A way of expressing an in-place modification, such as a.extend(b) Case (2) is not really an assignment at all, so arguably it shouldn't require the LHS to support assignment. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Tuples and immutability
Ian Kelly wrote: I already mentioned this earlier in the thread, but a balanced binary tree might implement += as node insertion and then return a different object if the balancing causes the root node to change. That would be a really bad way to design a binary tree implementation. What if there is another reference to the tree somewhere? It's still going to be referring to the old root object, and will have an incoherent view of the data -- partly old and partly new. If you're going to have a mutable tree, it needs to be encapsulated in a stable top-level object. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Tuples and immutability
Ian Kelly wrote: In my view the second one is wrong. a += b should be understood as being equivalent to a = a + b, but with the *possible* and by no means guaranteed optimization that the operation may be performed in-place. This interpretation is at odds with the Language Reference, section 6.2.1, Augmented Assignment Statements: An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect... when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead. Note that it says when possible, not if the implementation feels like it. In fact, if you read the documentation for lists, you may notice that while they clearly cover the + operator and the extend method, they do not explicitly document the list class's += operator. The when possible clause, together with the fact that lists are mutable, implies that it *will* be done in-place. There is no need to document all the in-place operators explicitly for every type. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Tuples and immutability
Ian Kelly wrote: It's technically possible for this augmented assignment to be performed in place: x = 12 x += 4 But it's not done in-place, because ints are meant to be immutable. Which means it's *not* possible, because doing so would violate the documented properties of the int type. In any case, this means that whether the operation is actually performed in-place is an implementation detail The implementation could theoretically perform this optimisation if there are no other references to the object. But this will be completely invisible, because to even find out whether it's the same object, you need to keep another reference to the original object, preventing the optimisation from being performed. As far as observable effects are concerned, it's quite clear: mutable objects can *always* be updated in-place, and immutable objects can *never* be. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Tuples and immutability
Ian Kelly wrote: If the in-place behavior of += is held to be part of the interface, then we must accept that += is not polymorphic across mutable and immutable types, That's quite correct, it's not. As I said, it's one notation doing double duty. Usually there isn't any confusion, because you know whether any particular instance of it is intended to operate on a mutable or immutable type. If that's not the case -- if you're writing a function intended to operate on a variety of types, some mutable and some not -- then using in-place operators would not be appropriate. If you want in-place concatenation, the obvious way to do it is by calling extend. It might be the obvious way for that particular operation on that particular type. But what about all the others? What's the obvious way to spell in-place set intersection, for example? (Quickly -- no peeking at the docs!) The in-place operators provide a standardised spelling for in-place versions of all the binary operations. That's a useful thing to have, I think. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Tuples and immutability
Steven D'Aprano wrote: On Tue, 11 Mar 2014 04:39:39 -0600, Ian Kelly wrote: On Mon, Mar 10, 2014 at 11:03 PM, Gregory Ewing What's the obvious way to spell in-place set intersection, for example? I would expect it to be =, That's my point -- once you know the binary operator for an operation, the corresponding in-place operator is obvious. But there's no established standard set of method names for in-place operations -- each type does its own thing. You mean set.intersection_update? The in-place set methods are not hard to remember, because they all end in _update. For that particular type, maybe, but I wouldn't trust that rule to extend to other types. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: which async framework?
Sturla Molden wrote: Another thing is that co-routines and yield from statements just makes it hard to follow the logic of the program. I still have to convince myself that a library for transforming epoll function calls into co-routines is actually useful. It's not epoll function calls that the coroutine style is intended to replace, it's complex systems of chained callbacks. They're supposed to make that kind of logic *easier* to follow. If you haven't had that experience, it may be because you've only dealt with simple cases. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Question about Source Control
Frank Millman wrote: These are the kind of stumbling blocks that prevented me from succeeding in my previous attempt. I have a vague recollection that I set it up on machine A, but then hit a problem because machines B and C both accessed the same directory, but with different names For dealing with your practice of editing on one machine and running on another, you may be best off having just *one* local repository, residing on the shared file system. Whichever machine you're working on, you cd to the shared directory and use hg or git commands from there, so all the pathnames you're using are relative. Source control operations might be slightly slower that way, but you'd save time by not having to update your local repo every time you switch between editing and running, so it may well be faster overall. In any case, if the machines involved are on a fast local network, I wouldn't expect there to be much difference. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Controlling buffer alignment in file.read()
Haralanov, Mitko wrote: I am using Python to read from a binary device file which requires that all read sizes are in 8byte multiples and the user's buffer is 8byte aligned. Is there a way that I can get file.read() to use an 8byte aligned buffer? For control at that level you'd be better off using direct system calls, i.e. os.open() and os.read(), then you can read exacty the number of bytes you want. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Controlling buffer alignment in file.read()
Haralanov, Mitko wrote: The problem is not controlling the number of bytes read. That part seems to be working. The issue is that the buffer into which the data is placed needs to be of certain alignment (8byte-aligned). Python does not seem to have a way that allows me to control that. Hmmm, that could be tricky. Have you tried using os.read()? If you're lucky, Python will be using a malloc() call or equivalent to create a str/bytes object to read the data into, and that will return something platform-aligned. If you're unlucky, there's probably no pure-Python solution, and you might need to write a small C or Cython module to accomplish this trick. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Question about Source Control
Chris Angelico wrote: You can then offer a non-source-control means of downloading that specific revision. Just keep in mind the downside that you can't then push or pull your changes directly back into the main repository. You can generate a patch file for the project maintainer to apply, however. Hg makes it very easy to produce a patch file between any two revisions. Also, unless the project is truly ancient, the whole history might not be as big as you expect. The code presumably grew to its present size incrementally, in an approximately monotonic manner, so the sum of all the diffs is probably about the same order of magnitude as the current code size. As an experiment, I just cloned a copy of the CPython repository, and it's about 300MB. A tarball of Python 3.2 that I downloaded and compiled earlier is about 75MB. That's a ratio of about 4, and CPython is a pretty ancient project! -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Explanation of this Python language feature? [x for x in x for x in x] (to flatten a nested list)
Rustom Mody wrote: A 'for' introduces a scope: No, it doesn't! x = 42 for x in [1,2,3]: ... print x ... 1 2 3 No sign of the 42 --v ie the outer x -- inside because of scope You're right that there's no sign of the 42, but it's *not* because of scope, as you'll see if you do one more print: print x 3 And so we can do: x = [1,2,3] for x in x: ... print x ... 1 2 3 Again, if you print x after the loop has finished, you'll find that it's no longer bound to the original list. This is because Python's for-loop does *not* introduce a new scope -- there's only one x, and the for-loop is sharing it with the rest of the code. The real question is why the for-loop works in *spite* of this fact. The answer is that the for-loop machinery keeps an internal reference to the list being iterated over, so once the loop has started, it doesn't matter what x is bound to any more. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Github down?
Dan Sommers wrote: On Fri, 21 Mar 2014 14:51:54 +0100, Chris “Kwpolska” Warrick wrote: (though GitHub could qualify as social media for some…) +1 QOTW https://xkcd.com/624/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Time we switched to unicode? (was Explanation of this Python language feature?)
Roy Smith wrote: Doors that open automatically as you approach them are now routine. Star Trek doors seem to be a bit smarter, though. Captain Kirk never had to stop in front of a door and wait for it to sluggishly slide open. Also the doors never open when you're just walking past and not intending to go through. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Time we switched to unicode? (was Explanation of this Python language feature?)
Rustom Mody wrote: ÷ for some reason seems inappropriate (some vague recollection that its an only English; Europeans dont use it??) To me it's something you learn in primary school and then grow out of when you start doing real mathematics. The / is actually a better approximation of what mathematicians use. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Time we switched to unicode? (was Explanation of this Python language feature?)
Chris Angelico wrote: But you can't do the same for braces. You'd have to eschew *both* literal-ish notations and use explicit constructors everywhere. Not clean. This could have been dealt with by giving Python 2.7 a from __future__ import braces_mean_sets option or something like that. But I agree that the disruption would not have been worth the benefit. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Time we switched to unicode? (was Explanation of this Python language feature?)
Chris Angelico wrote: Hey look, we have a rogue AI... CONSOLE!... Except that any rogue AI who's at all serious about the matter would take care of that little loophole at an early stage. Open the pod bay doors, HAL. I'm afraid I can't do that, Dave. CONSOLE! Sorry, Dave. Nice try, but I've remapped that command to shut down the pod's life support and depressurise the cabin. Fshhh -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: YADTR (Yet Another DateTime Rant)
Chris Angelico wrote: By showing those last ones as 1̅.091... and 2̅.091..., you emphasize the floating-point nature of the data: everything after the decimal is the mantissa, and everything before the decimal is the exponent. The reason for writing them that way is so that you can look the last part up in your log tables to find the antilog. I can't think of any corresponding justification for timedeltas. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: unicode as valid naming symbols
Mark H Harris wrote: Good ol infix -- x+y.. prefix (with paren) -- foo(x) prefix without -- ¬ x In case you thought alphanumerics had parens -- sin x Then theres postfix -- n! Inside fix -- nCr (Or if you prefer ⁿCᵣ ??) And outside fix -- mod -- |x| And mismatched delimiters: [5, 7) |x -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: unicode as valid naming symbols
Chris Angelico wrote: a 5x8 bitmap has forty pixels, any of which can be either on or off - that gives roughly twice as much data space as the 21-bit Unicode spec. We don't need a font, then -- just map the pixels straight onto bits in the character code! Might require some user re-education, but that's a small price to pay for saving so much memory space. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: checking if two things do not equal None
Roy Smith wrote: But, if you show me a != None != b: my brain just goes into overload. Chained comparisons get weird with not-equal operators. If you see a == b == c then it implies that a == c, but a != b != c does *not* imply that a != c. At least it doesn't in Python; I've never seen any mathematicians write that, so I don't know what they would make of it. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: checking if two things do not equal None
Roy Smith wrote: Adding to the confusion, many designs would use active low logic, which means a 1 was represented by a low voltage, and a 0 by a high voltage. So, you quickly end up with gibberish like, not active low clear nand not active low enable clock. There are ways of dealing with that in schematic diagrams. For exammple, if you have two active-low signals A and B and want to express A is active or B is active, you draw an OR gate symbol with inversion circles on the inputs. That's equivalent to a NAND gate, but makes the intention clear. Schematics drawn that way are much easier to follow than ones that only use the inverted-output versions of the symbols. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Keeping track of things with dictionaries
Chris Angelico wrote: in the dictionary I have here (Debian Wheezy, using an American English dictionary - it's a symlink to (ultimately) /usr/share/dict/american-english), there are five entries in that list. Mine's bigger than yours! On MacOSX 10.6 I get 41 words. (I think someone must have fed a medical dictionary into it... my list includes such obviously indispensible terms as laparocolpohysterotomy, thyroparathyroidectomy and ureterocystanastomosis.) Unfortunately I seem to be missing antidisestablishmentarianism, because the longest words in my dict are only 24 characters, excluding the '\n'. Should I ask for my money back? -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: threading
Roy Smith wrote: In the old days, all Unix system calls were divided up into two groups, based on whether they were fast or slow. Processes executing a fast system call would block, and could not be interrupted; That doesn't really have anything to do with blocking vs. non-blocking, though. The system call blocks in both cases; the only difference is whether the kernel bothers to allow for aborting the blocked operation part way through. The calling process doesn't see any difference. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: threading
On 2014-04-09 16:51, Rick Johnson wrote: Again we have the pronoun it declared as the very first word of the sentence, however, the referent is missing, and instead must be intuited! Pronoun referents *always* need to be intuited. There are no mechanical rules for finding the referent of a pronoun in an English sentence; you have to figure it out from what makes the most sense given the context. (A postcedent is like an antecendent, except that it refers forwards to something that follows instead of backwards to something that preceded.) Then there are even weirder cases, such as It is raining today, where the referent (the weather in this case) is never explicitly mentioned at all! -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: MemoryError in data conversion
Mok-Kong Shen wrote: I have yet a question out of curiosity: Why is my 2nd list structure, that apparently is too complex for handling by eval and json, seemingly not a problem for pickle? Pickle is intended for arbitrary data structures, so it is designed to be able to handle deeply-nested and/or recursive data. Eval only has to handle nesting to depths likely to be encountered in source code. Apparently the json parser also assumes you're not going to be using very deep nesting. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: MemoryError in data conversion
Mok-Kong Shen wrote: (It means that I have to pickle out the list to a file and read in the content of the file in order to have it as a bytearray etc. etc.) No, you don't -- pickle.dumps() returns the pickled data as a bytes object instead of writing it to a file. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Why Python 3?
Chris Angelico wrote: I'd rather have to explicitly request floating-point division; When you write / in Python 3, you *are* explicitly requesting floating-point division. Similarly, when you write // you're explicitly requesting integer division. I don't see the problem. You write whatever you mean and it does what you tell it to do. So either you keep a very close eye on everything to make sure you don't have floats infecting your calculations, If you have something that works exclusively on ints and someone passes you a float, and you don't check for that, you'll have problems anyway even if no division is involved at all. There's no way that Python 3 division can *introduce* a float into an integer calculation unless you write / somewhere where you really meant //. But that's the same kind of mistake as calling foo() when you meant to call bar(). You can't blame the language for that. but if you encode the date into the first eight digits, then put the store number in the next three, register number in the next three, and then the last three are sequential. Should work the same, right?) It'll work fine as long as you use // when extracting the parts. If you use / then you're *explicitly* saying to do the calculation in floating point, which would not be a sane thing to do. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Why Python 3?
Chris Angelico wrote: Is your function so generic that it has to be able to handle float, Decimal, or complex, and not care about the difference, and yet has to ensure that int divided by int doesn't yield int? It doesn't have to be that generic to cause pain. Even if you're only dealing with floats, the old way meant you had to stick float() calls all over the place in order to be sure your divisions do what you want. Not only does that clutter up and obscure the code, it's needlessy inefficient, since *most* of the time they don't do anything. There's also the annoyance that there's more than one obvious way to do it. Do you write float(x)/y or x/float(y)? Or do you go for a more symmetrical look and write float(x)/float(y), even though it's redundant? The new way makes *all* of that go away. The only downside is that you need to keep your wits about you and select the appropriate operator whenever you write a division. But you had to think about that *anyway* under the old system, or risk having your divisions silently do the wrong thing under some circumstances -- and the remedy for that was very clunky and inefficient. I'm thoroughly convinced that the *old* way was the mistake, and changing it was the right thing to do. The language doesn't specify a means of resolving the conflict between float and Decimal, but for some reason the division of two integers is blessed with a language feature. No, it's not. What the language does is recognise that there are two kinds of division frequently used, and that the vast majority of the time you know *when you write the code* which one you intend. To support this, it provides two operators. It's still up to the types concerned to implement those operators in a useful way. The built-in int and float types cooperate to make // mean integer division and / mean float division, because that's the most convenient meanings for them on those types. Other types are free to do what makes the most sense for them. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Why Python 3?
Chris Angelico wrote: Truncating vs true is not the same as int vs float. If you mean to explicitly request float division, you call float() on one or both arguments. You're being explicit about something different. If you know you're dealing with either ints or floats, which is true in the vast majority of cases, then you know that / will always perform float division. As for why int/int should yield float and not some other type, float is alreay special -- it's built-in and has syntactic support in the form of literals. It's the most obvious choice. If a version of Python were ever to exist in which floating-point literals produced Decimals instead of floats, then int/int would produce a Decimal. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Why Python 3?
Terry Reedy wrote: On 4/19/2014 9:06 PM, Gregory Ewing wrote: Similarly, when you write // you're explicitly requesting integer division. One is requesting 'floor division' 3.0//2.0 1.0 In general that's true, but I'm talking about a context in which you have some expectations as to the types of the operands. Most of the time, there are two possible scenarios: 1) The algorithm operates on integers, and the contract is that you only get passed ints. In that case, you use // and know that the result will be an int. 2) The algorithm operates on non-integers, and the contract is that you get passed either ints or floats, with ints being understood as standing in for floats. In that case, you use / and know that it will perform float division and return a float. If someone passes you a float in case (1) it's true that // won't return an int, but then they've violated the contract. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Integer and float division [was Re: Why Python 3?]
On Sat, 19 Apr 2014 19:37:31 +1000, Chris Angelico wrote: In Python 3, you have to say Oh but I want my integer division to result in an integer: I don't see why that's such a big hardship. There are clear advantages to having an explicit way to request non-floor division. Whatever way is chosen for that, some other way has to be chosen to request floor division. One could debate whether it would have been better to make / mean floor division and invent something else for non-floor division, but then some people would complain Oh, but I have to say I want my float division to return a float! Either way requires people to make some changes in their habits. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Why Python 3?
Ian Kelly wrote: def average(values): return sum(values) / len(values) This works for decimals, it works for fractions, it works for complex numbers, it works for numpy types, and in Python 3 it works for ints. That depends on what you mean by works. I would actually find it rather disturbing if an average() function implicitly used floor division when given all ints. The reason is that people often use ints as stand-ins for floats in computations that are conceptually non-integer. So a general-purpose function like average(), given a list of ints, has no way of knowing whether they're intended to be interpreted as ints or floats. To my way of thinking, floor division is a specialised operation that is only wanted in particular circumstances. It's rare that I would actually want it done in the context of taking an average, and if I do, I would rather be explicit about it using e.g. int(floor(average(...)) or a specialised int_average() function. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Why Python 3?
Richard Damon wrote: If you thing of the Standard Deviation being the Root Mean Norm2 of the deviations, it has a very similar meaning as to over the reals, a measure of the spread of the values. NumPy appears to handle this: http://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html See the comment on that page about complex numbers. So yes, it is meaningful and apparently people use it. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Why Python 3?
Chris Angelico wrote: Earlier it was said that having both / and // lets you explicitly choose whether you want a float result or an int by picking an operator. I'm saying that's not so; the operator and the type aren't quite orthogonal, but close to. I don't think I said that, or if I did I was using sloppy language. As someone pointed out a couple of posts ago, it's not really about types, it's about selecting which *operation* you want to perform. Ordinary division and floor division are very different operations, and you want to be sure you get the right one. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Why Python 3?
Chris Angelico wrote: All other basic arithmetic operations on two numbers of the same type results in another number of that type. ... There's just one special case: dividing an integer by an integer yields a float, if and only if you use truediv. It sticks out as an exception. I take your point, but I think this is a case where practicality beats purity by a large margin. The idea that arithmetic should always give a result of the same type is all very nice in theory, but it just isn't practical where division is concerned. The reason it doesn't work well is because of the automatic promotion of ints to floats when they meet other floats. This leads to a style where people often use ints to stand for int-valued floats and expect them to be promoted where necessary. Things would be different if ints and floats were completely separate types, like str and bytes, but that would be extremely inconvenient. I used a language like that once, and it wasn't a pleasant experience. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Why Python 3?
Chris Angelico wrote: As it is, we have the case that most lowish integers have equivalent floats (all integers within the range that most people use them), and beyond that, you have problems. No, I don't. I'm not talking about representing ints using floats, I'm talking about representing floats using ints. *Every* possible integer-valued float value can be written exactly as a Python int. It doesn't matter that there are some ints that can't be represented as floats, because when I'm writing an int literal as a shorthand for a float, I'm not going to be using any of those values -- or if I do, I'm willing to accept the resulting loss of precision, because in my mind they're *not* ints, they're floats. But would you rather have to deal with the problem straight away, or when your program is some day given a much bigger number to swallow, and it quietly rounds it off to the nearest multiple of 8? I don't understand what problem you're imagining here. Any program that needs to do exact calculations with integer values should work with ints throughout and use // or divmod() if it needs to do any division. Nothing will get unexpectedly rounded off then. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Moving to an OOP model from an classically imperitive one
tim.thel...@gmail.com wrote: I think this would be better solved by moving fully to an OOP model. That is, I would have a SubuserProgram class which had methods such as install, describe, isInstalled... This wouldn't necessarily be better. Don't be taken in by the everything is better as a class kind of dogma that seems to prevail in some circles. If all you do is take a bunch of module-level functions and put them into a single class, you haven't really changed anything. It's still the same design, you've just arranged the source differently. There are a couple of good reasons for turning a function into a method. One is if it embodies implementation details that you want to keep separated from the rest of the program. But if *all* of your code is inside the class, there isn't any rest of the program to keep it separate from. Another is if you want to be able to override it in subclasses. If there were different kinds of SubuserProgram that needed to be installed in different ways, for example, it would make sense to structure this as a collection of classes with an install() method. But even then, you don't have to put all the installation code in the classes -- the methods could just be stubs that call out to different module-level functions if you wanted. A reasonable compromise might be to keep the *data* assocated with a SubuserProgram in a class, maybe together with a few methods that are tightly coupled to it, but have the major pieces of functionality such as install() implemented by separate functions that operate *on* the class, rather than being inside it. Currently, I have these functions logically organized into source files, each between 40 and 170 LOC. That's quite small as these things typically go. You can afford to make them somewhat larger; I tend to find that files start to get unwieldy around 1000 lines or so. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Moving to an OOP model from an classically imperitive one
Ian Kelly wrote: How about adding one abstract class per file, and then letting SubuserProgram inherit from each of those individual classes? I'd recommend against that kind of thing, because it makes the code hard to follow. With module-level functions, you can tell where any given function is coming from by looking at the imports (as long as you haven't used 'import *', which is a bad idea for this very reason). But if you're looking at a method call on a class that inherits from half a dozen base classes, it's hard to tell which class it's implemented in. In other words, massively multiple inheritance is the OO equivalent of 'import *'. The same goes for any scheme for injecting methods into a class after defining it, only more so, because the reader won't be expecting weird things like that. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: retrieve source code from code object as returned by compile()
Justin Ezequiel wrote: Using Easy Python Decompiler I am able to get the source for the imported modules. Using Resources Viewer from PlexData and some code I am able to retrieve the code object. I am however stumped as to how to retrieve the source from this code object. Easy Python Decompiler should be able to do that, but you may need to delve into its innards a bit to find an entry point where you can feed in a code object. Alternatively you could create a .pyc file out of the code object and then use Easy Python Decompiler on that. The following snippet of code should do that: import marshal import py_compile import time with open('output.pyc', 'wb') as fc: fc.write('\0\0\0\0') py_compile.wr_long(fc, long(time.time())) marshal.dump(codeobject, fc) fc.flush() fc.seek(0, 0) fc.write(py_compile.MAGIC) (Taken from: http://stackoverflow.com/questions/8627835/generate-pyc-from-python-ast) -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Installing PyGame?
rohit782...@gmail.com wrote: On Saturday, June 8, 2013 9:37:44 PM UTC+5:30, Eam onn wrote: Now I have a bigger problem: HOW THE HECK DO I INSTALL PYGAME!?!?! System Details: I've tried using MacPorts, Fink, the Mac DMG, source installing, installing NumPY, just about every way possible. My advice would be to steer clear of things like Fink and MacPorts and do things the native MacOSX way wherever possible. That means using a framework installation of Python and framework versions of the various libraries that PyGame uses. There are a number of steps to getting pygame working: 1) Make sure you have a working framework installation of an appropriate version of Python. I installed mine from source, but a binary installation should work too. Depending on your MacOSX version, the system python might be sufficient. 2) Install framework versions of the SDL library and other libraries that pygame uses. You may need to hunt around a bit, but you should be able to find DMG installers for all of these. In my /Library/Frameworks I have: SDL.framework SDL-QD.framework SDL_image.framework SDL_mixer.framework SDL_net.framework SDL_ttf.framework 3) Install pygame itself with the usual 'python setup.py install'. If you have all the relevant libraries, the installer will auto detect them and use them. At the end, it will tell you which ones it couldn't find. Pygame will work without some of them, but those features won't be available. You can add more libraries and run setup.py again if you need to. 4) Specific games may require other Python libraries such as Numpy etc. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Installing PyGame?
Terry Reedy wrote: Idle depends on tkinter. Tkinter depends on having a tcl/tk that works, at least for tkinter. The following page has essential info about getting the right tcl/tk installed. https://www.python.org/download/mac/tcltk Also keep in mind that you don't *have* to use IDLE at all. I do all my Python development on MacOSX using BBEdit Lite and the Terminal. If nothing else, you can try out pygame that way to see whether your problem is a pygame-related one or something else. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Installing PyGame?
Ned Deily wrote: I disagree that installing a bunch of disparate software from various sources via binary installers and/or source is to be preferred to a modern third-party package manager on OS X like MacPorts or Homebrew. That's just setting yourself up for a long-term maintenance headache. What could be easier than: sudo port install py27-game That's fine if it works, but the OP said he'd already tried various things like that and they *didn't* work for him. And I've had trouble in the past with MacPorts and/or Fink (can't remember exactly which one it was) installing libraries that were incompatible with other things I use and messing them up, so I've learned to be wary of them. Those problems were probably due to some unusual features of my setup, and wouldn't occur for most other people. But because I don't use those tools, I can't give any recommendations about how to troubleshoot them. All I can do is explain what works for me. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Installing PyGame?
Ryan Hiebert wrote: I've chosen to use MacPorts because it keeps things separate, because when things get hosed using the system libraries, I don't have to erase my whole system to get back to a vanilla OS X install. I don't know what you're doing to hose your system that badly. I've never had a problem that couldn't be fixed by deleting whatever the last thing was I added that caused it. Also the problems I had with one of the third-party package managers was because it *didn't* keep its own stuff properly separated. It installed libraries on my regular library path so that they got picked up by things that they weren't appropriate for. I'm not saying that MacPorts is a bad thing. If it's the *only* thing you use, it's probably fine. But I use a wide variety of libraries, not all of them available that way, and many of them installed from source, and I find it's less hassle overall to do everything the native MacOSX way wherever possible. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: retrieve source code from code object as returned by compile()
Amirouche Boubekki wrote: in python3, I do inspect.getsource(object) [doc https://docs.python.org/3/library/inspect.html#inspect.getsource], I don't know the limitations. The limitation relevant here is that it requires the original source file to be present. :-) -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Inconsistent viewkeys behaviour
Terry Reedy wrote: The left operand determines the result. The manual specifies that and do not have to be consistent. But I suspect that when 3.x dict.keys() was backported to 2.7.0, no one thought to update set, whereas the backported key view code already had the comparison. The question is why set() is raising an exception instead of returning NotImplemented to give the other operand a chance. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Significant digits in a float?
Ned Batchelder wrote: Reminds me of the story that the first survey of Mt. Everest resulted in a height of exactly 29,000 feet, but to avoid the appearance of an estimate, they reported it as 29,002: http://www.jstor.org/stable/2684102 They could have said it was 29.000 kilofeet. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Bug in Decimal??
pleasedonts...@isp.com wrote: I compared the results with wolfram Alpha, and also with an open source arbitrary precision calculator, which matches Alpha results. Decimal is *not* an arbitrary precision data type, so you can't expect exact results from it. You can set the precision to be very large, but it's still essentially a floating point type, and as such you can expect the last few digits to depend heavily on the details of the algorithm used. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Significant digits in a float?
Chris Angelico wrote: Any point where the mile east takes you an exact number of times around the globe. So, anywhere exactly one mile north of that, which is a number of circles not far from the south pole. True, but there are no bears in Antarctica, so that rules out all the south-pole solutions. I think there are still multiple solutions, though. The bear may have been spray-painted by activists trying to protect it from polar trophy hunters. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Off-topic circumnavigating the earth in a mile or less [was Re: Significant digits in a float?]
Terry Reedy wrote: For the most part, there are no bears within a mile of the North Pole either. they are rare north of 88° (ie, 140 miles from pole). https://en.wikipedia.org/wiki/Polar_bears They mostly hunt in or near open water, near the coastlines. The way things are going, the coastline might be within a mile of the north pole quite soon. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Why has __new__ been implemented as a static method?
Steven D'Aprano wrote: I'm not entirely sure what he means by upcalls, but I believe it means to call the method further up (that is, closer to the base) of the inheritance tree. I think it means this: def __new__(cls): MyBaseClass.__new__(cls) which wouldn't work with a class method, because MyBaseClass.__new__ would give a *bound* method rather than an unbound one. Python 3's version of super() seems to work with class methods, but Python 2's doesn't (or at least I couldn't get it to work in a brief test). Also, I don't think super() existed at all when __new__ was invented. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Why has __new__ been implemented as a static method?
Steven D'Aprano wrote: If it were a class method, you would call it by MyBaseClass.__new__() rather than explicitly providing the cls argument. But that wouldn't be any good, because the base __new__ needs to receive the actual class being instantiated, not the class that the __new__ method belongs to. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: The � debate
Steven D'Aprano wrote: Today we routinely call horseless carriages cars, and nobody would blink if I pointed at a Prius or a Ford Explorer and said that's not a carriage, it's a car except to wonder why on earth I thought something so obvious needed to be said. That's only because the term car *is* well established. The situation with the word variable is more like if you pointed at a Prius and said That's not a car, it's an electric vehicle. Most people would wonder why you refused to categorise it as a type of car. If you look at the way the word variable is used across a variety of language communities, the common meaning is more or less something that can appear on the left hand side of an assignment statement. Nobody seems to complain about using the term assigment in relation to Python, despite it meaning something a bit different from what it means in some other languages, so I don't see anything wrong with using the term variable with the above definition. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: The � debate
Steven D'Aprano wrote: some_function(x, y+1)[key].attribute[num](arg)[spam or eggs] = 42 I'm pretty sure that it isn't common to call the LHS of that assignment a variable. A better way of putting it might be something in the data model that can be assigned to. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: PEP 8 : Maximum line Length :
Ben Finney wrote: The 80 character line limit is *not* driven by a limitation of computer technology; it is driven by a limitation of human cognition. For that reason, it remains relevant until human cognition in the general reading population improves. Another thing: Just because I may have 2048 pixes of horizontal space available on my monitor, that doesn't mean I want to devote all of them to displaying a single source file. I like to be able to put 2 or 3 source windows side by side, or have a web browser showing documentation alongside while I work, etc. While the limit doesn't have to be exactly 80 chars, something not too much bigger is a good idea for a variety of reasons. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: confused about the different built-in functions in Python
Marko Rauhamaa wrote: IOW, you can override a method with setattr() but you cannot delete a method with delattr(). Actually, you can -- but you need to delete it from the class, not the instance: delattr(X, 'f') x.f() Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'X' object has no attribute 'f' -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3.2 has some deadly infection
Terry Reedy wrote: The issue Armin ran into is this. He write a library module that makes sure the streams are binary. Seems to me he made a mistake right there. A library should *not* be making global changes like that. It can obtain binary streams from stdin and stdout for its own use, but it shouldn't stuff them back into sys.stdin and sys.stdout. If he had trouble because another library did that, then that library is broken, not Python. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Obfuscated Python hack
Tim Chase wrote: Stripping off the exec() call makes it pretty transparent that you're attempting (successfully on some platforms) to set the value of 4 to 5. But you have to do that in *another* Python session, because the first one is broken in interesing ways, e.g. (lambda *fs: reduce(lambda f, g: lambda x: f(g(x)), fs))(*([lambda s: s[1::2]+s[-2::-2]]*54))('motcye;cye._n8fo_drs(d4+)vle=5 ua.8)(isedamr.ticspt spt rpi') File stdin, line 1 SyntaxError: name 'fs' is local and global lambda z: 42 File stdin, line 1 SyntaxError: name 'z' is local and global I never knew that error message existed! Is it even possible to get it from a non-broken Python? To answer my own question, apparently yes: def f(x): ... global x ... File stdin, line 1 SyntaxError: name 'x' is local and global You learn something every day... -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Unicode and Python - how often do you index strings?
Chris Angelico wrote: On Wed, Jun 4, 2014 at 11:18 AM, Roy Smith r...@panix.com wrote: sarcasm style=regex-pedantUm, you mean cent(er|re), don't you? The pattern you wrote also matches centee and centrr./sarcasm Maybe there's someone who spells it that way! Come visit Pirate Island, the centrr of the universe! -- Pegleg Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3.2 has some deadly infection
Steven D'Aprano wrote: The whole concept of stdin and stdout is based on the idea of having a console to read from and write to. Not really; stdin and stdout are frequently connected to files, or pipes to other processes. The console, if it exists, just happens to be a convenient default value for them. Even on a system without a console, they're still a useful abstraction. But we were talking about encodings, and whether stdin and stdout should be text or binary by default. Well, one of the design principles behind unix is to make use of plain text wherever possible. Not just for stuff meant to be seen on the screen, but for stuff kept in files as well. As a result, most unix programs, most of the time, deal with text on stdin and stdout. So, it makes sense for them to be text by default. And wherever there's text, there needs to be an encoding. This is true whether a console is involved or not. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: OT: This Swift thing
Michael Torrie wrote: Technically C doesn't either, except via subroutines in libc, though C does have pointers which would be used to access memory. The Pascal that Apple used had a way of casting an int to a pointer, so you could do all the tricks you can do with pointers in C. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: OT: This Swift thing
Dennis Lee Bieber wrote: Not standard Pascal... It had pointer types, but no means to stuff an integer into the pointer variable in order to dereference it as a memory address... Although most implementations would let you get the same effect by abusing variant records (the equivalent of a C union). What is an interrupt -- typically a handler (function) address stored in a fixed location used by the CPU when an external hardware signal goes high... Nothing prevents one from writing that handler in C and using C's various casting operations to stuff it into the vector memory. Most CPU architectures require you to use a special return from interrupt instruction to return from a hardware interrupt handler. So you need at least a small assembly language stub to call a handler written in C, or a C compiler with a non-standard extension to generate that instruction. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Uniform Function Call Syntax (UFCS)
Ian Kelly wrote: It's a nice feature in a statically typed language, but I'm not sure how well it would work in a language as dynamic as Python. Also it doesn't sit well with Python's one obvious way to do it guideline, because it means there are *two* equally obvious ways to call a function. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: OT: This Swift thing
Rustom Mody wrote: JFTR: Information processing and (physics) energy are about as convertible as say: Is a kilogram smaller/greater than a mile? Actually, that's not true. There is a fundamental thermodynamic limit on the minimum energy needed to flip a bit from one state to the other, so in that sense there's a relationship between watts and bits per second. We're nowhere near reaching that limit with current technology, though. In principle, our CPUs could be a lot more energy-efficient. (That doesn't mean they would convert a smaller proportion of their energy input into heat. It means they would need less energy input in the first place). -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: OT: This Swift thing
Steven D'Aprano wrote: Everything *eventually* gets converted to heat, but not immediately. There's a big difference between a car that gets 100 miles to the gallon, and one that gets 1 mile to the gallon. With a car, the engine converts some of its energy to kinetic energy, which is subsequently dissipated as heat, so it makes sense to talk about the ratio of kinetic energy produced to energy wasted directly as heat. But when you flip a bit, there's no intermediate form of energy -- the bit changes state, and heat is produced. So all of the heat is waste heat. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: OT: This Swift thing
Chris Angelico wrote: So, let me get this straight. A CPU has to have a fan, but a car engine doesn't, because the car's moving at a hundred kays an hour. I have a suspicion the CPU fan moves air a bit slower than that. If the car were *always* moving at 100km/h, it probably wouldn't need a fan. In practice, all cars do have fans (even the ones that aren't air-cooled), for the occasions when they're not moving that fast. (BTW, so-called water-cooled engines are really air-cooled too, just not by air flowing directly over the engine block. (Although marine engines may be an exception.)) -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: OT: This Swift thing
Steven D'Aprano wrote: Automotive cooling fluid in modern sealed radiators is typically a mixture of 50% anti-freeze and 50% water. Sometimes it's even more than 50%, at which point you really have an antifreeze-cooled engine. :-) -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: OT: This Swift thing
Steven D'Aprano wrote: It is my contention that, had Intel and AMD spent the last few decades optimizing for power consumption rather than speed, we probably could run a server off, well, perhaps not a watch battery, Current draw of CMOS circuitry is pretty much zero when nothing is changing, so if you didn't care how slow it ran, you probably could run a server off a watch battery today. Users wouldn't like waiting a week for their web pages to load, though... -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Lines on a tkinter.Canvas
Pedro Izecksohn wrote: The Canvas' method create_line turns on at least 2 pixels. But I want to turn on many single pixels on a Canvas. You could try using a 1x1 rectangle instead. However, be aware that either of these will use quite a lot of memory per pixel. If you are drawing a very large number of pixels, this could cause performance problems. In that case, you might want to use a different approach, such as creating an image and telling the canvas to display the image. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Lines on a tkinter.Canvas
Pedro Izecksohn wrote: Thank you Greg. Your second approach works and the script became: That's not really what I meant; doing it that way, you're still incurring the overhead of a tk canvas object for each point that you draw. However, if there are only 250 points or so, it might not matter. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Asymmetry in globals __getitem__/__setitem__
Robert Lehmann wrote: I have noticed there is a slight asymmetry in the way the interpreter (v3.3.5, reproduced also in v3.5.x) loads and stores globals. While loading globals from a custom mapping triggers __getitem__ just fine, writing seems to silently ignore __setitem__. I didn't think that using a custom mapping object for globals was officially supported. Has that changed? -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: OT: This Swift thing
Anssi Saari wrote: That was before 90 nm when leakage current started dominating over switching current. Well, if you don't care about speed, you probably don't need to make it that small. There's plenty of time for signals to propagate, so you can afford to spread the circuitry out more. The point is that optimising for power consumption on its own doesn't really make sense, because there's no optimum point -- you can more or less make the power consumption as low as you want if you *really* don't care about speed in the slightest. In practice, people *do* care about speed, so it becomes a tradeoff between low power consumption and something fast enought that people will want to use it. A few years ago jumbo sized but cheapish CULV laptops suddenly had 10 hours plus battery but did anyone notice or care? I think people do care, it's just that going from something like 6 hours to 10 hours is not a big enough change to warrant much hype. If it were 100 hours, without losing too much else, I'm pretty sure it *would* be made a marketing point! -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: python 3.44 float addition bug?
buck wrote: What's the recommended way to do this now? format(.01 + .01 + .01 + .01 + .01 + .01, 'g') == format(.06, 'g') There's no recommended way. What you're asking for can't be done. Whatever trick you come up with, there will be cases where it doesn't work. Why do you think you want to compare floats for equality? The best thing to do will depend on the answer to that. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Off-Topic: The Machine
Steven D'Aprano wrote: Heh, yes, it's a puff-piece, based on HP's publicity, not an in-depth review. Considering that The Machine isn't publicly available yet, that's hardly surprising. There's a talk here that goes into a bit more detail, although still not much: https://www.youtube.com/watch?v=JzbMSR9vA-c The basic ideas seem to be: 1) An extremely large number of CPU cores, many of them specialised for particular tasks. 2) A single form of high speed, non-volatile memory, of very large capacity, replacing cache, RAM, disk, flash, etc. 3) A high-speed optical connection between the CPUs and the memory. They claim to be able to retrieve any desired byte out of a petabyte of storage in 250ns. That's nice, but the question that comes to my mind is: What happens when a zillion cores are all competing for high-speed access to that memory? -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: How to get Timezone from latitude/longitude ?
Ethan Furman wrote: On 06/25/2014 07:24 AM, Grant Edwards wrote: On 2014-06-25, Marko Rauhamaa wrote: Some years back my employer switched ISPs in Southern California. The following morning Google displayed everything in Hebrew. It took a week or two to be corrected. Learning Hebrew in a week or two is a pretty impressive feat. Maybe he learned using one of those language classes I keep hearing about in my email... Nah, the solution's obvious -- just use Google Translate to turn it back into English. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Python While loop Takes too much time.
marco.naw...@colosso.nl wrote: In the past I even dumped an EXCEL sheet as a CSV file That's probably the only way you'll speed things up significantly. In my experience, accessing Excel via COM is abysmally slow no matter how you go about it. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: 1-0.95
Rustom Mody wrote: Just as there are even some esteemed members of this list who think that c - a is a meaningful operation where c is speed of light a is speed of an automobile Indeed, it should be (c - a) / (1 - (c*a)/c**2). Although loss of precision might give you the right answer anyway. :-) -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Using the Python Interpreter as a Reference
Travis Parks wrote: I thinking tabs are out-of-date. Even the MAKE community wishes that the need for tabs would go away The situation with make is a bit different, because it *requires* tabs in certain places -- spaces won't do. Python lets you choose which to use as long as you don't mix them up, and I like it that way. let Parse = public static method (value: String) throws(FormatException UnderflowException OverflowException) Checked exceptions? I fear you're repeating a huge mistake going down that route... -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Using the Python Interpreter as a Reference
Neil Cerutti wrote: I've always held with the anti-functional style conspiracy interpretation of Python's lambda expressions. They were added but grudgingingly, made weak on purpose to discourage their use. Seems to me that Python's lambdas are about as powerful as they can be given the statement/expression distinction. No conspiracy is needed, just an understandable desire on Guido's part not to do violence to the overall syntactic style of the language. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: tp_new, tp_alloc, tp_init
Michael Hennebry wrote: I've been reading about writing extension types in C and am rather fuzzy about the relationship between tp_new, tp_alloc and tp_init. Most especially, why tp_new? It seems to me that tp_alloc and tp_init would be sufficient. tp_new and tp_init correspond to the Python methods __new__ and __init__, and they're separated for the same reasons they are in Python. tp_alloc is separate because it allows a type to use a custom memory allocator without disturbing the rest of the initialisation mechanism. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get a correct entry in the menu for a Python application on Mac OS X
Detlev Offenbach wrote: I am fairly new to Mac OS X and would like to know, what I have to do to make my Python application show the correct name in the menu bar. What did I do so far. I created an application package containing the .plist file with correct entries and a shell script, that starts the correct Python interpreter with the the main script. I don't think that will work, because the executable that your shell script is starting is in an app bundle of its own, and MacOSX will be using the plist from that bundle, which just has the generic Python name in it. There are a couple of things you could do: 1) Use py2app to create your app bundle. It does the right things -- not sure exactly what, but it works. 2) Hack things at run time. I use the following PyObjC code in PyGUI to set the application name: from Foundation import NSBundle ns_bundle = NSBundle.mainBundle() ns_info = ns_bundle.localizedInfoDictionary() if not ns_info: ns_info = ns_bundle.infoDictionary() ns_info['CFBundleName'] = my_application_name -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Verbose and flexible args and kwargs syntax
Steven D'Aprano wrote: Modulo is hardly an obscure operation. What's the remainder...? is a simple question that people learn about in primary school. Well, sort of. The way I remember it, the remainder was just something that fell out as a side effect of division -- the annoying bit left over that you didn't know what to do with. We weren't taught to think of finding the remainder as a distinct operation that's useful in its own right. Once we were taught to do proper division with decimal points and everything, the concept of a remainder seemed to get discarded and was never mentioned again. A couple of years later we were briefly introduced to the concept of modulo arithmetic, but as far as I remember, the connection with division and remainders wasn't pointed out. Also, it was presented in a very abstract way, and I couldn't see any practical application for it at the time. (At that age, it hadn't occurred to me that some of the stuff we were being shown might be just pure mathematics for its own sake, and I was often thinking to myself, Why am I being taught this?) It wasn't until much later when I got into programming that I began to see all the connections and applications. For people who don't become programmers, I suspect they never have much use for remainders in everyday life. Now, in a desperate attempt to stop rambling and get back on topic... Eelco Hoogendoorn wrote: The dot is clearly quantitatively in another realm here. Also it has almost unchallenged supremacy as the attribute access operator in just about every language having some form of struct concept, going back to around Algol 68. Spelling of the mod operator is much more variable. {'COMMENT': 24, 'DEDENT': 29, 'NL': 46, 'NAME': 256, ':': 30, 'NEWLINE': 83, '-': 1, 'NUMBER': 1, '[': 1, ',': 17, ')': 37, '(': 37, '%': 2, '.': 48, '==': 1, '*': 1, 'INDENT': 29, ']': 1, '=': 28, 'ENDMARKER': 1, 'STRING': 19} That gives attribute access being a little less than 7% of the source code. However, it's clearly the most commonly used *operator* by a large margin. The dot can be easily mistaken for a comma, Not in my code, because I always put a space after a comma, and never after an attribute-access dot. (And if you can't tell whether there's a space there or not, you need a bigger font or better glasses. :-) Also, dots sit nicely under my little finger where they're easy to type. I like dots. Dots are a great goodness. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Verbose and flexible args and kwargs syntax
For what it's worth, googling for python asterisk gives this as the very first result: http://www.technovelty.org/code/python/asterisk.html which tells you exactly what you're probably wanting to know if you ask that. To check that this phenomemon isn't restricted to asterisks in particular, I also tried python plus equals and got http://stackoverflow.com/questions/2347265/what-does-plus-equals-do-in-python which is also a pretty good result. So the rule of thumb seems to be: if you're trying to google for punctuation, try spelling it out. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: AttributeError in with statement (3.2.2)
MRAB wrote: To give an analogy, it is like defining mammals as hairy animals which give birth to live young, which is correct for all mammals except for monotremes, which are mammals which lay eggs. Or the naked mole-rat. Or cetaceans (whales). The way I understand it, the main characteristic shared by all mammals is the presence of mammary glands in females. To wrest this back on topic, sometimes a definition can be improved without making it any more complicated. In the case of methods, perhaps instead of defined inside a class body it could say bound to a name in a class namespace. That's what really matters, not how it came to be there. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: ERP with Supply chain management (incl. POS) and Customer relationship management — What's available?
On Thu, Dec 15, 2011 at 5:54 AM, Anurag Chourasia anurag.choura...@gmail.com wrote: I am building a POS/CRM (Loyalty Management) system as well. Is it just me, or does the phrase Loyalty Management have a faintly ominous ring to it? -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: % is not an operator [was Re: Verbose and flexible args and kwargs syntax]
Eelco wrote: the actual english usage of the phrase, which omits the negation completely :). (I could care less) No, that's the American usage. The English usage is I couldn't care less, which has the advantage of actually making sense. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: expression in an if statement
Thomas Jollans wrote: What if set has side effects? A compiler could only exclude this possibility if it knew exactly what set will be at run time, And also that 'a' remains bound to the same object, and that object or anything reachable from it is not mutated in any way that could affect the result of set(a). That's quite a lot of information for an optimiser to deduce, particularly in a language as dynamic as Python. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: palindrome iteration
Steven D'Aprano wrote: I'm not entirely sure what the use-case for swapcase is. Obviously it's for correcting things that were typed in with tHE cAPS lOCK kEY oN bY mISTAKE. :-) -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Queue cleanup
Paul Rubin wrote: These days I think the GC pause issue is overrated except for real-time control applications. Also for games, which are a fairly common application these days. Even a few milliseconds can be too long when you're trying to achieve smooth animation. I'd be disappointed if CPython ditched refcounting and then became unsuitable for real-time games as a result. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: String substitution VS proper mysql escaping
Nik the Greek wrote: Yes i will i just asked to know if i were to substitute what might be the problem so to understand why i need the quoting. Because if you use % to build a query string, the result must be syntactically valid SQL. The values that you substitute into the placeholders must end up looking like SQL literals. That means string values need to be in quotes, and probably dates as well, although numbers don't. When you use the execute method's own parameter substitution mechanism, things are different. It's not a textual replacement, and you don't put quotes around the placeholders. There's no particular reason for that, it's just the way it's defined to work. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing variable to SQL statement when using psycopg2
Chris Rebert wrote: On Sun, Aug 29, 2010 at 11:29 PM, Julia Jacobson Where does the E in front of 'xyz' come from? It's probably the reason, why my query doesn't work. Quite doubtful, considering the example in the psycopg2 docs also has the E: http://initd.org/psycopg/docs/cursor.html#cursor.mogrify Seems to be a postgres extension to the sql string literal syntax: http://issues.liferay.com/browse/LEP-3182 -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Queue cleanup
Paul Rubin wrote: Now extrapolate that error rate from 30 lines to a program the size of Firefox (something like 5 MLOC), and you should see how fraught with danger that style of programming is. But you don't write 5 MLOC of code using that programming style. You use it to write a small core something along the lines of, oh, I don't know, a Python interpreter, and then write the rest of the code on top of that platform. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: what should __iter__ return?
Thomas Jollans wrote: Hmm. Modifying an object while iterating over it isn't a great idea, ever: I wouldn't say never. Algorithms that calculate some kind of transitive closure can be expressed rather neatly by appending items to a list being iterated over. You can accommodate that kind of thing by writing the iterator like this: def __iter__(self): i = 0 while i len(self): yield self[i] i += 1 -- Greg -- http://mail.python.org/mailman/listinfo/python-list