Can't use subprocess.Popen() after os.chroot() - why?
Hi All,
I'm trying to do the following:
import os
from subprocess import Popen, PIPE
os.chroot("/tmp/my_chroot")
p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout_val, stderr_val = p.communicate()
print stdout_val
but the Popen call is dying with the following exception:
Traceback (most recent call last):
File "./test.py", line 7, in
p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE)
File "/home/erik/lib/python2.7/subprocess.py", line 679, in __init__
File "/home/erik/lib/python2.7/subprocess.py", line 1224, in _execute_child
File "/home/erik/lib/python2.7/pickle.py", line 1382, in loads
File "/home/erik/lib/python2.7/pickle.py", line 858, in load
File "/home/erik/lib/python2.7/pickle.py", line 971, in load_string
LookupError: unknown encoding: string-escape
Am I missing something here? does the chroot environment need to be populated
with more than just the date executable in this case? I can't seem to find any
examples of this & would appreciate any insight.
Thanks,
Erik.
--
http://mail.python.org/mailman/listinfo/python-list
Re: a *= b not equivalent to a = a*b
On 26/08/16 08:44, [email protected] wrote: Here's the key: $ python2 Python 2.7.10 ... 1/2 0 $ python Python 3.5.1 ... 1/2 0.5 1//2 0 I read about this awhile ago, but it's not until it bites you that you remember fully. How is this related to your question? The example explicitly says Python 2 and doesn't use the '//' operator. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: a *= b not equivalent to a = a*b
On 26/08/16 08:14, [email protected] wrote: I was being facetious, but behind it is a serious point. Neither the APL nor the J languages use precedence even though their inventor, Ken Iverson, was a mathematician. That was to support functional programming dating back to the 1970's. Precedence is not the issue here anyway. Both '*' and '/' have the same precedence. The two operations in your expressions have to be evaluated in SOME order - either left-to-right or right-to-left. The issue is twofold: Firstly, the compound assignments will always evaluate their RHS before performing the assignment - this is not the same as operator precedence - they have to, else what does Python pass to the function that knows what the compound assignment means for that type (e.g. sequences may be extended for '*=')? So for compound assignments there is always effectively an implicit set of parentheses around the RHS compared to the expression without the assignment operator (if you think of the compound assignment as being a _part_ of the overall expression). Secondly, the way you have chosen to layout your code has fooled your brain into thinking that the division is performed before the multiplication. Python doesn't care that you jammed the sub-expression together with no whitespace ;) E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question on multiple Python users in one application
On 06/10/16 22:11, Paul Rubin wrote: "Jolly Good Spam" writes: Can someone please suggest what I should be looking at and doing to be able to effectively run multiple independent Pythons in a single program? Put each Python in a separate process and communicate by IPC. Loren says that this is to be CPython embedded into an existing application (in which each user can be identified somehow). We need to understand first what the process/threading/per-user model of the existing application is. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question on multiple Python users in one application
On 06/10/16 22:40, Loren Wilton wrote: the multi-user program is a virtual machine implementation That's not relevant (unless you mean each user is running in their own VM, in which case you _really_ need to describe your execution environment). BTW, you _really_ need to describe your execution environment ;) and the programs running on the machine have resources like variables, arrays, files, and databases Python variables? Python arrays (lists? tuples?)? Or some other sort of "variables" and "arrays" that exist outside of Python? You _really_ need to describe your execution environment ;) E ;) -- https://mail.python.org/mailman/listinfo/python-list
Re: Halp in if
Hi, On 13/11/16 20:09, [email protected] wrote: HI want to make a script that if somthing happens, it stop, and if it doesnt, it couninues. I dont finding a smart way. Read the documentation for the "while", "break" and "continue" keywords. Regards, E. -- https://mail.python.org/mailman/listinfo/python-list
Re: help on "from deen import *" vs. "import deen"
On 15/11/16 14:43, Michael Torrie wrote: As you've been told several times, if you "import deen" then you can place a new object into the deen namespace using something like: deen.foo=bar Importing everything from an imported module into the current module's namespace is not the best idea But "from foo import *" is not importing "everything". It's the opposite - it's importing everything _that the module wants to explicitly expose_ (i.e., a subset of everything ;)). It *used* to be everything in the module's namespace, but then the possibly misnamed "__all__" magic variable made it a subset of whatever the module's author wanted to expose. However, "import foo" _does_ import "everything", and also gives the importer the power to re-bind names within that module's namespace too (which is the crux of the original question). This is not usually a good thing unless the importing module is incestuous with the imported module. So this brings up another point - not sure if it has been made before: should a module have a way of *not* allowing an importer to re-bind its local bindings? For example, something like a "__bindable__" variable such that all names not included may not be bound by any other module? And/or something like an "__export__" variable that says what gets exposed to a simple "import foo" (sometimes one might want to "import foo" and sometimes "from foo import *" for namespace reasons, but why should those two statements import different things)? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: The right way to 'call' a class attribute inside the same class
On 13/12/16 06:14, Gregory Ewing wrote: Ned Batchelder wrote: if a C++ constructor raises an exception, will the corresponding destructor be run, or not? (No, because it never finished making an object of type T.) So it just leaks any memory that's been allocated by the partially-run constructor? If you're referring to resources in general that a constructor (in the C++ sense) allocates - memory, file descriptors, whatever - then it's up to the constructor to release those resources before throwing the exception should something fail. Destructors are not executed for objects that were not constructed. If the constructor is not written to that standard, then yes - it will leak resources. The memory allocated for the _object_ itself will be released though. Regards, E. -- https://mail.python.org/mailman/listinfo/python-list
Re: The right way to 'call' a class attribute inside the same class
On 12/12/16 23:23, Chris Angelico wrote: In JavaScript, it's normal to talk about "calling a function as a constructor". When you do, there is a 'this' object before you start. No there isn't. There is an implicit binding of a variable called "this" based on the syntactic sugar of whether you're calling a function as method on an object or not. In "strict" mode, this has been redefined to be "undefined" (i.e., there is no object) for when you're not - otherwise it will be a binding to the global "document" object (and in Node.js, I think something else entirely. It's a mess ...). Ultimately, every language has slightly different semantics You're not wrong ;) E. -- https://mail.python.org/mailman/listinfo/python-list
Re: The right way to 'call' a class attribute inside the same class
On 16/12/16 01:17, Chris Angelico wrote: On Fri, Dec 16, 2016 at 11:36 AM, Erik wrote: On 12/12/16 23:23, Chris Angelico wrote: In JavaScript, it's normal to talk about "calling a function as a constructor". When you do, there is a 'this' object before you start. No there isn't. There is an implicit binding of a variable called "this" based on the syntactic sugar of whether you're calling a function as method on an object or not. In "strict" mode, [blah, blah, blah] I'm talking about when you call a function as a constructor: "new Foo()". Doesn't that have a 'this' object before the function starts? Yes, in that case there is (I didn't grok that you meant using 'new' by "calling a function as a constructor", but it's obvious now you spell it out). I wish I could find the resource I originally learned this stuff from, because it's quite enlightening and I'd like to link to it here - if one understands how things work generally under the covers it all makes much more sense, but I guess that's also a bad advert for a language (and why a lot of people get confused at first, and why it's a bit of a mess ;)). But yes you're correct, in the case of using "new Func()" then "Func" is called with an implicit binding of 'this' that is to a newly created object. Regards, E. -- https://mail.python.org/mailman/listinfo/python-list
Re: The right way to 'call' a class attribute inside the same class
NOTE: If you found this message by searching for help on how Python
works, be aware that it's discussing how JavaScript works, not Python!
Look elsewhere :)
Chris, this isn't directed at you (I think you get it) - just following
up with some detail for anyone who might discover this sub-thread when
searching in future.
On 18/12/16 01:21, Chris Angelico wrote:
On Sun, Dec 18, 2016 at 12:01 PM, Erik wrote:
I wish I could find the resource I originally learned this stuff from,
because it's quite enlightening and I'd like to link to it here
Sounds like how Michael Schwern introduces his "Git for Ages 4 and Up"
talk
Just in case anyone is remotely interested, I've found a reasonable link
(but it's not the one I was looking for).
I realise this is off-topic for a Python list, but it has come up
because of a Python question so I thought why not ... (I wish someone
had explained this to me in roughly-Python terms when I first had to
deal with JS ;)).
In short, AIUI, all JS functions have an implicit initial parameter
which is named 'this'. What that parameter is bound to depends on the
context of the call to that function object. In Python the callable is
of a particular type (method, function, generator) but on JS (for the
purposes of this discussion (pun intended ;)) they are all equal and
it's the calling context that determines what happens.
A JS function, whether declared with "function Foo(a, b, c) {}" or as an
expression "function (a, b, c) {}" has an implicit initial parameter
which is bound to the variable 'this' (so they are really "function
Foo(this, a, b, c) {}", "function (this, a, b, c) {}").
The value of that initial first parameter is determined by how they are
called. There are three main ways:
1) Method call:
"obj.foo(1, 2, 3)" is syntactic sugar for "obj.foo(obj, 1, 2, 3)".
2) Function call:
"foo(1, 2, 3)" is syntactic sugar for "foo(GLOBAL_OBJECT, 1, 2, 3)"
where "GLOBAL_OBJECT" is whatever the execution environment defines as
being the global object. In a browser, I think it's "window", in the JS
strict mode, I think it's "undefined" (i.e., no object), in Node.js I
think it might be something else entirely.
3) Constructor call:
"new foo(1, 2, 3)" is syntactic sugar for "foo(NEWOBJ, 1, 2, 3)"
where NEWOBJ is a newly allocated, empty object.
The other way of invoking a function object is via its "call" method
where the initial 'this' parameter can be explicitly given -
"foo.call(SPAM, 1, 2, 3)" - which is how to implement bound methods and
that sort of thing.
The main area of confusion seems to be when passing function expressions
(closures) as a callback to another function:
function Foo() {
ham(this.a, this.b, function (x) { this.frobnicate(x); });
}
Let's assume this is called with "obj.Foo();". In the function itself,
'this', is bound to 'obj'. However, in the body of the (anonymous)
function expression/closure (which sort of looks to be at the same scope
as everything else) 'this' is bound according to the rules above being
applied to at the point it is called - the object it is bound to almost
certainly doesn't have the "frobnicate" method expected.
This is why the following works:
function Foo() {
_this = this;
ham(this.a, this.b, function (x) { _this.frobnicate(x); });
}
The closure now knows how to address the 'this' object for the original
method even though it is called later by whatever 'ham()' does. Using a
bound function as the callback works in the same way.
Anyway, off-topic as I said, but if it helps other Pythoneers get to
grips with some of the weird JS semantics, it's all good :)
The link I *did* find (which probably has a bit more depth) is:
https://rainsoft.io/gentle-explanation-of-this-in-javascript/
Cheers, E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Cleaning up conditionals
On 30/12/16 23:00, Deborah Swanson wrote: Oops, indentation was messed up when I copied it into the email. Should be this: if len(l1[st]) == 0: if len(l2[st]) > 0: l1[st] = l2[st] elif len(l2[st]) == 0: if len(l1[st]) > 0: l2[st] = l1[st] That's even worse! Anyway, ignoring all that, if what you are trying to do is just do some action based on a set of fixed comparisons that are known at the top of the function (and do not mutate depending on the path through the function), then you can just cache the comparisons and then compare the resulting set of boolean results (note that my examples are NOT based on your use-case, it's just pseudo-code which happens to use your expressions): state = (len(l1[st]) == 0, len(l2[st]) > 0) if state == (True, False): pass elif state == (False, True): pass ... etc. If the len() comparisons are tri-state (i.e., in some cases you want to know if the length is <, ==, or > 0, depending on one of the other comparisons) then you can do something like: def clamp(foo): return min(max(-1, foo), 1) state = (clamp(cmp(len(l1[st]), 0), cmp(len(l2[st]), 0)) if state == (0, -1): pass elif state == (1, -1): pass ... etc. I'm not sure this makes it much more readable though - but if you make the RHS of those comparisons a symbolic name you might be getting somewhere - ACTION1 = (0, -1) ACTION2 = (1, -1) if state == ACTION1: pass elif state == ACTION2: pass Hope that helps, E. -- https://mail.python.org/mailman/listinfo/python-list
Re: learning and experimenting python.
On 30/12/16 23:34, [email protected] wrote: You are also confusing me. But there mustbe some reason. What happens if your student questions you like this.? And may be those who questions like this will surely be the developer of its successor language. Because out of thousands, only one may asks this, whom you all will consider fool, but he's the only genius Do not feed the troll. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Cleaning up conditionals
On 31/12/16 00:26, Deborah Swanson wrote: As Mr. Bieber points out, what I had above greatly benefits from the use of conjunctions. It now reads: if not len(l1[st]) and len(l2[st]): IMHO, "if not len(l)" is a _terrible_ way of spelling "if len(l) == 0" (mentally, I have to read that as "if length of 'l' is not not equal to 0" - and a double negative won't never cause problems ( ;) )). Also, in that particular expression, having to know off the top of their head the precedence of 'not' and 'and' will cause at least some percentage of your maintenance audience in the future to get it wrong. What's wrong with: if len(l1[st]) == 0 and len(l2[st]) != 0: ... ? There is _no way_ someone could read that and get the wrong idea. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: learning and experimenting python.
On 31/12/16 05:22, Wildman via Python-list wrote: On Fri, 30 Dec 2016 19:23:17 -0700, Michael Torrie wrote: On 12/30/2016 07:05 PM, Wildman via Python-list wrote: On Fri, 30 Dec 2016 23:39:43 +, Erik wrote: Do not feed the troll. E. Please explain how what I said is trolling. Perhaps it was a little snide but I tend to get that way when trying to explain the obvious. Hmm. I thought he was referring to einstein1410... It was his message he was replying to, not yours, and I took it as a request to the rest of us (sorry, Erik--couldn't resist posting). I took it to mean that he was telling einstein1410 to not feed the trolls. If I am wrong then my apologies to Erik. Yes, my message was to everyone, using a quote from 'einstein1410' that I thought demonstrated the point. The vast majority of the messages in this thread are from 'einstein' nd are short, nonsensical retorts to others who are trying to be helpful, that just seem designed to get a further response and nothing more. Whether or not it's on purpose, he's just trolling. I may be wrong, but it just looks like the result of a bet to me - perhaps there's a similar thread on a Perl group somewhere and whoever gets the most replies wins. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Clickable hyperlinks
Hi. On 03/01/17 19:46, Deborah Swanson wrote: Excel has a formula: When you start a new topic on the list, could you please write a new message rather than replying to an existing message and changing the title/subject? For those reading the list in a threaded email client, this message is shown as a continuation of your "Cleaning up conditionals" thread, and that whole thread in turn shows up as a continuation of the "mentor training python Romania with certification" discussion (which you had presumably "reply"ed to originally) ... Thanks. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Screwing Up looping in Generator
Hi, On 03/01/17 22:14, Deborah Swanson wrote: ...you have to create the generator object first and use it to call the next function. And I really don't think you can use a generator as your range in a for loop. So I'd use a 'while True', and break out of the loop when you hit the StopIteration exception: files = rootobs() while True: try: file = files.next() except StopIteration: break base = os.path.basename(file.name) . . . (etc) What you have done there is taken an understanding of the underlying machinery that allows the 'for' loop to be syntactic sugar over any iterable and spelled it out, instead of just using 'for'! Without all that, your example is: for file in rootobs(): base = os.path.basename(file.name) . . . (etc) [In fact, the machinery would also cope with the return value from rootobs() being an iterable but not an iterator by using "files = iter(rootobjs)"]. You seem to be reading up on how the stuff works under the covers (i.e., from the point of view of an implementer of a class or library) and then suggesting that that's what the *caller* of that class or library needs to do. They don't - for a caller, 'for x in seq:' is all they need to know - the mechanics are handled by the interpreter coupled with the dunder methods that the class may implement. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Screwing Up looping in Generator
On 03/01/17 23:05, Deborah Swanson wrote: And yes, we usually used for loops for generators, unless you don't know when the generator will be exhausted. As in this case, where the number of files the generator can provide is unknown. Then we used the while True, break on StopIteration method. Out of interest, *why* was it deemed necessary to do something different if you don't know how many items the generator will generate? Was any rationale given for that? for x in foo: bar(x) ... where foo is any iterable (something that has a __iter__ method defined - including generators) will just bind each value in turn to 'x' and will exit when the StopIteration exception is raised under the covers by the iterator that is iterating over the iterable. Some generators are infinite (and their iterator will never raise a StopIteration exception). E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
On 03/01/17 23:56, Chris Angelico wrote: On Wed, Jan 4, 2017 at 10:49 AM, wrote: #think of a number computer_number = number.randint(1,100) What's wrong is that you aren't showing us the exception you get on this line. *Copy and paste* that exception - the whole thing. It's very helpful. I doubt it's getting that far (I can see at least one syntax error in the code pasted). cr2001: I echo Chris's sentiment though - what is the error you are seeing (in it's entirety)? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: How Best to Coerce Python Objects to Integers?
On 03/01/17 22:47, Chris Angelico wrote:
On Wed, Jan 4, 2017 at 9:42 AM, Ethan Furman wrote:
Aside from calling "except Exception" a "naked except"
If you read the comments, you'll see that he originally had an actual
bare except clause, but then improved the code somewhat in response to
a recommendation that SystemExit etc not be caught.
But, as stated at the top of the article, his brief was: "The strings
come from a file that a human has typed in, so even though most of the
values are good, a few will have errors ('25C') that int() will reject.".
What he *should* have done is just validated his input strings before
presenting the string to int() - i.e., process the input with knowledge
that is specific to the problem domain before calling the
general-purpose function.
He mentions temperature sensors, so perhaps stripping a trailing 'c' or
'C' is a reasonable thing to do (or even, if there's a trailing 'f' or
'F', performing a numerical conversion after the value is known).
Instead, he tried to patch around int() rejecting the strings. And then
decided that he'd patch around int() rejecting things that weren't even
strings even though that's not what the function has (apparently) been
specified to receive.
The "bulletproof" result will convert "25C" to None even though 25 is
probably a reasonable result for that string in his domain problem domain.
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
Hi Callum,
On 04/01/17 00:02, Callum Robinson wrote:
> When i check the code it comes up with invalid syntax and my writing
line gets re directed here
>
> def is_same(target, number:
> if target == number:
> result="win"
> elif target > number:
> result="low"
> else:
> result="high"
> return result
OK, good. That implies it's something wrong with the function definition
('def'). Look at that very carefully :) (*)
E.
(*) My emoticon may give you a hint ...
--
https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
Hi Callum, On 04/01/17 00:30, Callum Robinson wrote: I feel like im missing something so blatantly obvious. That's because you are ;). I don't want to come across as patronising, but I want you to see it for yourself, so, here's a function definition similar to yours that doesn't have the same syntax error that yours does: def foo(spam, ham): if spam == ham: return "same" return "different" See the difference? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
On 04/01/17 00:32, Callum Robinson wrote: I forgot a bloody bracket xD Cool, you got it ;) It's the sort of thing your brain will see instantly once you've done it a few times :D and now theirs a new error ill try to figure this out on my own. You need to look back to Chris's original reply, I suspect (his reply was pointing out a runtime issue that will happen once the syntax issue is resolved) ... E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Screwing Up looping in Generator
Hi, On 04/01/17 01:12, Deborah Swanson wrote: The main reason you might want to catch the StopIteration exception is to do something else before your code simply stops running. If all you're doing is run a generator til it's out of gas, and that's all you want it to do, then there's no need to catch anything. Ah! OK, I see where the lines are being crossed now ;) Although StopIteration is an exception, it is something that the 'for/iter' machinery handles for you under the covers. Each 'for' statement effectively has a 'try' block around it that catches 'StopIteration' and just terminates that particular 'for' loop and continues on with the remainder of your script. Raising a 'StopIteration' is an internal mechanism used to determine when an iterator (i.e., the thing a 'for' loop is looping over) has exhausted itself. It's not something a regular user is ever expected to know about let alone catch. When execution falls out of the bottom of a generator, StopIteration is raise (compared to a regular function or method returning 'None'). E. -- https://mail.python.org/mailman/listinfo/python-list
Re: How Best to Coerce Python Objects to Integers?
On 04/01/17 01:10, Steve D'Aprano wrote: On Wed, 4 Jan 2017 11:22 am, Erik wrote: What he *should* have done is just validated his input strings before presenting the string to int() - i.e., process the input with knowledge that is specific to the problem domain before calling the general-purpose function. That's the Look Before You Leap solution. But in this case, given the scenario described (a text file with a few typos), the best way is to ask for forgiveness rather than permission: Yes, probably, in this case ;) OK, in the case where the function you're calling is sane (and Python's int() is - it won't blindly accept "0x101" as a hex value, for example) then it's probably right that leaping first and then, on failure, processing the value and leaping again is the right thing to do. [I tend to work in an environment where things I'm calling may not be sane (and in some cases I may never know), so I will usually consider LBYL as a way of CMA ;)]. In this whole discussion there has been no mention of what happens when the function returns None, though. Another thought: if he is receiving human generated input, there is an argument to be made for accepting "look alikes" -- e.g. maybe the data was entered by Aunt Tilly, who was a typist in the 1960s and can't break the habit of using l or I interchangeably for 1, and O for 0. Sure - and that's what I meant by processing the string according to his problem "domain". If he has Aunt Tillys doing his data input, then l->1 and 0->O may be a reasonable thing (I recently did a project where things like converting Icelandic's Eth and Thorn runic letters to 'D' and 'P' - though morally wrong ;) - was a reasonable character translation because that's what people actually typed in). E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
On 04/01/17 02:24, Callum Robinson wrote: On Wednesday, January 4, 2017 at 3:05:48 PM UTC+13, MRAB wrote: What values can 'is_same' return? Which of those values are you checking for in the loop? I'm sorry but i do not completely understand what you are stating You need to think about the specific things (their type, their exact values) that your functions might return. Printing some trace output is a classic way of debugging your program. If, after this line: higher_or_lower = is_same(computer_number, guess) ... you added: print (higher_or_lower) ... what values do you then see being output? How will those values be processed by the conditions you see that work on the "higher_or_lower" variable? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
On 04/01/17 02:47, Callum Robinson wrote: On Wednesday, January 4, 2017 at 3:35:53 PM UTC+13, Erik wrote: I did it and this is what it states when i run it hello. I have thought of a number between 1 and 100. Can you guess it? 5 Low Sorry , you are too high. Try again. Does this mean the number i entered is to low but the code is still stating it is to high? The last code you posted will return "low", "high" or "win" from the "is_same()" function. How does that relate to the "Low" that you are now printing? You must have changed something. If you are testing strings as return values then they must be _exactly_ the same - including case and spaces etc. Always remember that your computer is an idiot. It's the fastest idiot that you'll ever know, and it could become your best friend. But it IS an idiot ;) E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
On 04/01/17 03:25, Steven D'Aprano wrote: On Wednesday 04 January 2017 12:25, Callum Robinson wrote: Hey man thanks, the sad thing is i have no idea why i put that in. I must be having a terrible day. Don't worry about it. The difference between a beginner and an expert is *not* that experts make fewer mistakes, but that experts know how to fix those mistakes so quickly that they don't even notice them. Hmm. An expert at what? Telling a beginner how to spell something is not the same as coaxing that same beginner to think about something or approach a problem from a particular angle and come to their own solution. We all could have told him the answer up-front. What has that achieved? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Clickable hyperlinks
Hi. On 03/01/17 19:46, Deborah Swanson wrote: > Excel has a formula: When you start a new topic on the list, could you please write a new message rather than replying to an existing message and changing the title/subject? For those reading the list in a threaded email client, this message is shown as a continuation of your "Cleaning up conditionals" thread, and that whole thread in turn shows up as a continuation of the "mentor training python Romania with certification" discussion (which you had presumably "reply"ed to originally) ... Thanks. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Screwing Up looping in Generator
Hi, On 03/01/17 22:14, Deborah Swanson wrote: > ...you have to create the generator object first and use it to call the > next function. And I really don't think you can use a generator as your > range in a for loop. So I'd use a 'while True', and break out of the > loop when you hit the StopIteration exception: > > files = rootobs() > > while True: > try: > file = files.next() > except StopIteration: > break > > base = os.path.basename(file.name) >. >. >. > (etc) What you have done there is taken an understanding of the underlying machinery that allows the 'for' loop to be syntactic sugar over any iterable and spelled it out, instead of just using 'for'! Without all that, your example is: for file in rootobs(): base = os.path.basename(file.name) . . . (etc) [In fact, the machinery would also cope with the return value from rootobs() being an iterable but not an iterator by using "files = iter(rootobjs)"]. You seem to be reading up on how the stuff works under the covers (i.e., from the point of view of an implementer of a class or library) and then suggesting that that's what the *caller* of that class or library needs to do. They don't - for a caller, 'for x in seq:' is all they need to know - the mechanics are handled by the interpreter coupled with the dunder methods that the class may implement. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
On 03/01/17 23:56, Chris Angelico wrote: > On Wed, Jan 4, 2017 at 10:49 AM, wrote: >> #think of a number >> computer_number = number.randint(1,100) > > What's wrong is that you aren't showing us the exception you get on > this line. *Copy and paste* that exception - the whole thing. It's > very helpful. I doubt it's getting that far (I can see at least one syntax error in the code pasted). cr2001: I echo Chris's sentiment though - what is the error you are seeing (in it's entirety)? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Screwing Up looping in Generator
On 03/01/17 23:05, Deborah Swanson wrote: > And yes, we usually used for loops for generators, unless you don't know > when the generator will be exhausted. As in this case, where the number > of files the generator can provide is unknown. Then we used the while > True, break on StopIteration method. Out of interest, *why* was it deemed necessary to do something different if you don't know how many items the generator will generate? Was any rationale given for that? for x in foo: bar(x) ... where foo is any iterable (something that has a __iter__ method defined - including generators) will just bind each value in turn to 'x' and will exit when the StopIteration exception is raised under the covers by the iterator that is iterating over the iterable. Some generators are infinite (and their iterator will never raise a StopIteration exception). E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
Hi Callum,
On 04/01/17 00:02, Callum Robinson wrote:
> When i check the code it comes up with invalid syntax and my writing
line gets re directed here
>
> def is_same(target, number:
> if target == number:
> result="win"
> elif target > number:
> result="low"
> else:
> result="high"
> return result
OK, good. That implies it's something wrong with the function definition
('def'). Look at that very carefully :) (*)
E.
(*) My emoticon may give you a hint ...
--
https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
On 04/01/17 00:32, Callum Robinson wrote: > I forgot a bloody bracket xD Cool, you got it ;) It's the sort of thing your brain will see instantly once you've done it a few times :D > and now theirs a new error ill try to figure this out on my own. You need to look back to Chris's original reply, I suspect (his reply was pointing out a runtime issue that will happen once the syntax issue is resolved) ... E. -- https://mail.python.org/mailman/listinfo/python-list
Re: How Best to Coerce Python Objects to Integers?
On 03/01/17 22:47, Chris Angelico wrote:
> On Wed, Jan 4, 2017 at 9:42 AM, Ethan Furman wrote:
>> Aside from calling "except Exception" a "naked except"
>
> If you read the comments, you'll see that he originally had an actual
> bare except clause, but then improved the code somewhat in response to
> a recommendation that SystemExit etc not be caught.
But, as stated at the top of the article, his brief was: "The strings come from
a file that a human has typed in, so even though most of the values are good, a
few will have errors ('25C') that int() will reject.".
What he *should* have done is just validated his input strings before
presenting the string to int() - i.e., process the input with knowledge that is
specific to the problem domain before calling the general-purpose function.
He mentions temperature sensors, so perhaps stripping a trailing 'c' or
'C' is a reasonable thing to do (or even, if there's a trailing 'f' or
'F', performing a numerical conversion after the value is known).
Instead, he tried to patch around int() rejecting the strings. And then decided
that he'd patch around int() rejecting things that weren't even strings even
though that's not what the function has (apparently) been specified to receive.
The "bulletproof" result will convert "25C" to None even though 25 is probably
a reasonable result for that string in his domain problem domain.
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
Hi Callum, On 04/01/17 00:30, Callum Robinson wrote: > I feel like im missing something so blatantly obvious. That's because you are ;). I don't want to come across as patronising, but I want you to see it for yourself, so, here's a function definition similar to yours that doesn't have the same syntax error that yours does: def foo(spam, ham): if spam == ham: return "same" return "different" See the difference? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Screwing Up looping in Generator
Hi, On 04/01/17 01:12, Deborah Swanson wrote: > The main reason you might want to catch the StopIteration exception is > to do something else before your code simply stops running. If all > you're doing is run a generator til it's out of gas, and that's all you > want it to do, then there's no need to catch anything. Ah! OK, I see where the lines are being crossed now ;) Although StopIteration is an exception, it is something that the 'for/iter' machinery handles for you under the covers. Each 'for' statement effectively has a 'try' block around it that catches 'StopIteration' and just terminates that particular 'for' loop and continues on with the remainder of your script. Raising a 'StopIteration' is an internal mechanism used to determine when an iterator (i.e., the thing a 'for' loop is looping over) has exhausted itself. It's not something a regular user is ever expected to know about let alone catch. When execution falls out of the bottom of a generator, StopIteration is raise (compared to a regular function or method returning 'None'). E. -- https://mail.python.org/mailman/listinfo/python-list
Re: How Best to Coerce Python Objects to Integers?
On 04/01/17 01:10, Steve D'Aprano wrote: > On Wed, 4 Jan 2017 11:22 am, Erik wrote: >> What he *should* have done is just validated his input strings before >> presenting the string to int() - i.e., process the input with knowledge >> that is specific to the problem domain before calling the >> general-purpose function. > > That's the Look Before You Leap solution. But in this case, given the > scenario described (a text file with a few typos), the best way is to ask > for forgiveness rather than permission: Yes, probably, in this case ;) OK, in the case where the function you're calling is sane (and Python's int() is - it won't blindly accept "0x101" as a hex value, for example) then it's probably right that leaping first and then, on failure, processing the value and leaping again is the right thing to do. [I tend to work in an environment where things I'm calling may not be sane (and in some cases I may never know), so I will usually consider LBYL as a way of CMA ;)]. In this whole discussion there has been no mention of what happens when the function returns None, though. > Another thought: if he is receiving human generated input, there is an > argument to be made for accepting "look alikes" -- e.g. maybe the data was > entered by Aunt Tilly, who was a typist in the 1960s and can't break the > habit of using l or I interchangeably for 1, and O for 0. Sure - and that's what I meant by processing the string according to his problem "domain". If he has Aunt Tillys doing his data input, then l->1 and 0->O may be a reasonable thing (I recently did a project where things like 0-> converting Icelandic's Eth and Thorn runic letters to 'D' and 'P' - though 0-> lly wrong ;) - was a reasonable character translation because that's what 0-> le actually typed in). E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
On 04/01/17 02:24, Callum Robinson wrote: > On Wednesday, January 4, 2017 at 3:05:48 PM UTC+13, MRAB wrote: >> What values can 'is_same' return? >> >> Which of those values are you checking for in the loop? > > I'm sorry but i do not completely understand what you are stating You need to think about the specific things (their type, their exact values) that your functions might return. Printing some trace output is a classic way of debugging your program. If, after this line: higher_or_lower = is_same(computer_number, guess) ... you added: print (higher_or_lower) ... what values do you then see being output? How will those values be processed by the conditions you see that work on the "higher_or_lower" variable? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
On 04/01/17 03:25, Steven D'Aprano wrote: > On Wednesday 04 January 2017 12:25, Callum Robinson wrote: > >> Hey man thanks, the sad thing is i have no idea why i put that in. I must be >> having a terrible day. > > Don't worry about it. The difference between a beginner and an expert is *not* > that experts make fewer mistakes, but that experts know how to fix those > mistakes so quickly that they don't even notice them. Hmm. An expert at what? Telling a beginner how to spell something is not the same as coaxing that same beginner to think about something or approach a problem from a particular angle and come to their own solution. We all could have told him the answer up-front. What has that achieved? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Hey, I'm new to python so don't judge.
On 04/01/17 02:47, Callum Robinson wrote: > On Wednesday, January 4, 2017 at 3:35:53 PM UTC+13, Erik wrote: > I did it and this is what it states when i run it > > hello. > I have thought of a number between 1 and 100. > Can you guess it? > 5 > Low > Sorry , you are too high. Try again. > > Does this mean the number i entered is to low but the code is still stating it is to high? The last code you posted will return "low", "high" or "win" from the "is_same()" function. How does that relate to the "Low" that you are now printing? You must have changed something. If you are testing strings as return values then they must be _exactly_ the same - including case and spaces etc. Always remember that your computer is an idiot. It's the fastest idiot that you'll ever know, and it could become your best friend. But it IS an idiot ;) E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Using namedtuples field names for column indices in a list of lists
On 10/01/17 00:54, Deborah Swanson wrote:
Since I won't change the order of the records again after the sort, I'm
using
records.sort(key=operator.attrgetter("Description", "Date"))
once, which also works perfectly.
So both sorted() and sort() can be used to sort namedtuples. Good to
know!
As people keep saying, the object you have called 'records' is a *list*
of namedtuple objects. It is not a namedtuple.
IIRC, you create it using a list comprehension which creates the
records. A list comprehension always creates a list.
The sorted() function and the list.sort() method can be used to sort a
list containing any objects - it's just a case of telling them how to
obtain the key values to compare (which, in the case of simple attribute
access which the namedtuple objects allow, "operator.attrgetter()" will
do that). This is why sorting the list works for you.
You could sort objects of different types - but you might need to supply
a function instead of operator.attrgetter() which looks at the type of
each object and returns something that's obtained differently for each
type (but which the sort function can compare).
When you say 'Foo = namedtuple("Foo", "spam ham")', you are creating a
"factory" which is able to generate "Foo" objects for you.
When you say "x = Foo(1, 2)" you are using the factory to create an
object for you which has its "spam" and "ham" attributes set to the
values 1 and 2 respectively.
When you say "records = [Foo(x, y) for x, y in some_iterable()]", you
are creating a list of such objects. This is the thing you are then sorting.
Does that make sense?
Regards, E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Using namedtuples field names for column indices in a list of lists
On 10/01/17 03:02, Deborah Swanson wrote: Erik wrote, on January 09, 2017 5:47 PM IIRC, you create it using a list comprehension which creates the records. A list comprehension always creates a list. Well no. The list is created with: records.extend(Record._make(row) for row in rows) No, the list is _extended_ by that code. The list is _created_ with a line that will say something like "records = []" or "records = list()" (or "records = "). It's nice to see you agree that it's a list though. Oh, hold on ... ;) I'm not exactly sure if this statement is a list comprehension. No, it's not. I was remembering an old message where someone suggested using the _make() method and that was expressed as a list comprehension. What you have there is a call to list.extend() passing a _generator_ comprehension as its only parameter (which in this case you can consider to be equivalent to a list comprehension as all of the data are generated greedily). You see that I said "list.extend()". That's because 'records' is a list. type(records) Yes, it's an instance of the list class. A list object. A list. >>> type(list()) >>> type([]) >>> class foo: pass ... >>> type(foo()) >>> ... type() will tell you what class your object is an instance of. "" tells you that your object is a list. And it behaves like a list sometimes, but many times not. I think that's impossible. I'm 100% sure it's a list. Please give an example of when 'records' does not behave like a list. The only thing I don't think you have 100% correct is your assertion that records is a list. It's a list. But that's just a quibble. The important thing in this context is that both .sort() and sorted() treat it like a list and DTRT. That's because it's a list :) E. -- https://mail.python.org/mailman/listinfo/python-list
Re: How can I make a sentinel value NOT be initialized in a class/method - OOP?
Hi, On 13/01/17 22:26, [email protected] wrote: The issue I am having is that when i enter the sentinel value of QUIT, it gets initialized as the name and printed out. How can I get around this? If I understand the question correctly (which looks like it's just a re-worded homework question (*)), you need to look at the 'if' statement: https://docs.python.org/3/tutorial/controlflow.html#if-statements E. (*) If it is a homework question, you'd look better on the list to state it as such, and post some code that at least tries to answer the question before you're likely to get a useful response. However, as you have indicated a specific problem, I'll assume you have actually written some code. -- https://mail.python.org/mailman/listinfo/python-list
Re: How can I make a sentinel value NOT be initialized in a class/method - OOP?
[Replying to direct email. David - please respond to the list so that you can receive other people's suggestions also] Hi David, On 14/01/17 15:30, David D wrote: > 1) No this is not homework, I am doing this all on my own. In that case I apologise - I gave you the benefit of the doubt though as I was only half-suspicious. FWIW, listing specific constructs that must be used is often a thing that a tutor would write in an assignment (because the purpose of the assignment is to get you to learn about those particular constructs). That's what raised the flag for me. Anyway ... > 2) I am changing the class to cars. > > 3) A second question arose that I thought would work, but I am getting > this error :*can't assign to a function call* > > What I am trying to do is this pseudo code : Firstly, there's little point in posting pseudo code if you are reporting a specific compiler or run-time error. The errors you get are very specific to your code and in some cases are caused by *subtle* things in your code. We generally need to see the actual code (or a cut-down example) that allows the subtleties to be described to you. > count= 0 > > class car > initialize all of the values and put self so they are available to the > entire class > def __init__(self, model...) > self.mode=model etc > > > while loop > input model =what is the model > input serial = what is the serial > input doors = how many doors > count = count + 1 > #create the instance/object > mycar (count) = car(model, serial, doors) > > input do you want another car in the database? > if yes > continue > if no > break > > The issue is that when creating an object/instance, python won't let me > use this syntax of having -- car(count) which would give me multiple > objects (car1, car2, car3 etc) with the count variable. I am not sure why. The syntax "foo(spam)" will *call* the function "foo" and pass it the value "spam". It doesn't make any sense to _assign a value_ to a function call operation (you're effectively trying to assign a value - the thing after the '=' - to another value - the return value of the function call). So, what is "mycar"? How do you create it? In Python, the built-in structure for a group of objects which can be dynamically extended with new entries in the way you want is a list. Create an empty one with: mycar = [] or mycar = list() Lists have an 'append()' method which will add the parameter it is called with to the end of the list object it is called on: mycar.append(car(model, serial, doors)) You don't have to worry about keeping track of 'count'. Lists will grow dynamically as you add things. Use "len(mycar)" to see how many items it holds and "for vehicle in mycar:" to step through them all or "mycar[n]" to address as specific entry. From the Python prompt, type "help(list)" Hope that helps. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: working with classes, inheritance, _str_ returns and a list
Hi, On 15/01/17 19:58, David D wrote: I am creating a parent class and a child class. I am inheriting from the parent with an additional attribute in the child class. I am using __str__ to return the information. When I run the code, it does exactly what I want, it returns the __str__ information. This all works great. BUT 1) I want what is returned to be appended to a list (the list will be my database) 2) I append the information to the list that I created 3) Whenever I print the list, I get a memory location So how do I take the information that is coming out of the child class (as a __str__ string), and keep it as a string so I can append it to the list? [snip] Here is where it goes wrong for me allcars.append(car1) This adds the object (of the child or parent class) to the list. If you _really_ want the *string* returned by __str__() to be appended to the list then you would do: allcars.append(str(car1)) (The str() function returns what the object's __str__() method returns if it has one - otherwise it will return SOME sort of string representation of your object, but you can't rely on the format of that). I'm a bit confused though as to why you would want to create that object only store its __str__() value and discard the object itself. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Emulating Final classes in Python
Hi Steven, On 17/01/17 07:05, Steven D'Aprano wrote: I wish to emulate a "final" class using Python, similar to bool: [snip] It doesn't have to be absolutely bulletproof, but anyone wanting to subclass my class should need to work for it, which hopefully will tell them that they're doing something unsupported. When someone brings up something like this you usually quote the "consenting adults" argument, so I'll throw it back at you - why not just add it to your documentation? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Need reviews for my book on introductory python
On 27/01/17 21:36, MRAB wrote: "loose"? Don't you mean "lose"? (Or possible "lack"?) Don't you mean 'Or possibly "lack"'? https://en.wikipedia.org/wiki/Muphry%27s_law ;) E. -- https://mail.python.org/mailman/listinfo/python-list
Re: How coding in Python is bad for you
On 29/01/17 14:42, Steve D'Aprano wrote: 1. for...else is misspelled, and should be for...then; 2. Same for while...else; I don't think I'll ever agree with you on this one. "then", to me, implies the code following it is always executed. "else" implies it's conditional. In those constructs it's conditional and therefore, to me, "else" is a better reminder of that. It would be even better if it was "else if not break:" to make the meaning clearer. I would agree that it would be even better than that if it was "then if not break:" (apart from needing the new keyword ;)), as then the conditional aspect is explicit. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: How coding in Python is bad for you
On 30/01/17 02:14, Steve D'Aprano wrote:
On Mon, 30 Jan 2017 10:52 am, Erik wrote:
It would be even better if it was "else if not break:" to make the
meaning clearer.
break is not the only way to exit the for loop
Fine - "else if not break or raise or return:", then ;) [that is not a
serious suggestion]
You're conflating two types of exit though. One is a way of exiting the
innermost loop construct and nothing more. The others are ways of
exiting a separate, outer construct (be that a try block or a
function/method).
I'm specifically talking about the interaction between 'break' and
'else'. The other things are at a different level.
I would agree that it would be even better than that if
it was "then if not break:" (apart from needing the new keyword ;)), as
then the conditional aspect is explicit.
But it isn't conditional.
Yes it is. When one reads the code, the statements in the "else:" (or
your theoretical "then:") block will be executed only if a "break" was
not executed in the loop statements the "then:" is associated with. How
is that NOT conditional?
Your syntax implies that the interpreter keeps
some sort of flag did_we_reach_the_end_of_the_loop_without_break or
something, and then it checks the state of that flag. There is no such
flag.
You are correct and I never said there was - you're now arguing against
a point that you have made and I didn't!
I have written more than my fair share of assembly code in the past and
can identify the "for/while" vs "else" construct as a loop with two exit
targets that are jumped to unconditionally. In fact, that was one of the
"oh, nice!" moments when I first learned Python - I'd never seen a high
level language do that before (even C doesn't have it!).
All I have said is that the *spelling* of "else:" could be "else if not
break:" or - because you mentioned it and I think it actually reads
better - "then if not break:".
They hoped to use the same flag the for-loop used.
Well, _logically_ there is a flag (in as much as it could be thought of
like that to make it easy to understand - and in C, that's pretty much
what you have to actually do unless you really want to use 'goto').
Not a single condition to be seen, anywhere. Its all unconditional jumps.
To anticipate a possible objection: it is possible that the FOR_ITER
bytecode is implemented with a conditional test, but even so, all that
tests for is whether to enter the main body of the for-loop (10
STORE_NAME ...) or jump to (18 LOAD_NAME ...).
Again, you're arguing against something I didn't say. I never suggested
"if not break" (whether following "else" or "then") should generate code
that dynamically tests some sort of flag. It's just a different way of
spelling exactly the same construct we have today, generating exactly
the same bytecode.
I can see what you're trying to say, but a naked "then:" really doesn't
do it for me.
while 1:
break
then:
print ("Yes!")
while 1:
break
then if not break:
print ("Yes!")
It would be interesting to know what novices thought those meant. Maybe
"if not break:" is not the answer either. I just don't think "then:" is ;)
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to know what to install (Ubuntu/Debian) for a given import?
On 01/02/17 23:20, Wildman via Python-list wrote: On Wed, 01 Feb 2017 21:29:00 +, Chris Green wrote: Wildman wrote: On Wed, 01 Feb 2017 19:15:13 +, Chris Green wrote: OK, no problem, but isn't it very non-portable? I don't see why not. It should work on any system that has Python3 installed, at least that is my understanding. I'm sure someone will correct me if I'm wrong. OTOH if you want in insure 100% portability with any script, you can use pyinstaller. To install for Python2: pip install pyinstaller For Python3: pip3 install pyinstaller Out of interest (as someone who grew up on the great 1.5.7 ;)) - is there a definitive resource that explains all of the various packaging and installation options that exist for Python modules these days (both for an author and a user)? A lot of Linux distributions have Python-related packages (other than the language itself) which can be installed using the system installer. Then there's "pip", which is an installer which is installed using the system installer. Now, apparently, there's "pyinstaller" which can be installed using the "pip" installer! I'd like to understand the differences and how this all fits together. Thanks, E. -- https://mail.python.org/mailman/listinfo/python-list
Re: How coding in Python is bad for you
On 02/02/17 02:05, MRAB wrote: Both suggestions are a little long-winded. Couldn't we just abbreviate them to "else:"? :-) You are not wrong ;) E. -- https://mail.python.org/mailman/listinfo/python-list
Re: How coding in Python is bad for you
On 02/02/17 01:41, Chris Angelico wrote: On Thu, Feb 2, 2017 at 10:49 AM, Erik wrote: Well, _logically_ there is a flag (in as much as it could be thought of like that to make it easy to understand - and in C, that's pretty much what you have to actually do unless you really want to use 'goto'). The last time I wanted a for-else in C, I used a goto. And no velociraptor came and ate me. Thanks for your input. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Strange range
On 01/04/16 15:34, Marko Rauhamaa wrote: Chris Angelico : *A range object is not an iterator.* We now have learned as much. However, doesn't that extra level of indirection seem like an odd choice? If you write your own class which has an __iter__ method, would you expect: >>> o = MyClass() >>> i1 = iter(o) >>> i2 = iter(o) >>> list(i1) ['foo', 'bar', 'baz'] >>> list(i2) [] ? Or, would you expect both iterators to be independent and both return the 'foo', 'bar', 'baz' sequence (where that is the hypothetical result of iterating over your object)? If you now replace MyClass() with range(10), why would you expect the two iterators to be related? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Beginner] - Hanging in the code, can't figure out what's wrong
Hi Loop.IO, On 03/04/16 15:41, Loop.IO wrote: If you don't want the user to enter anything, then I explained how before, just use: name='C:\\Documents\\PythonCoding\\launch2.bat' if that's the file name you need. -- Bartc Hi Bartc, i tried that, didn't work FYI, for the future. Telling someone what _didn't_ happen is generally not very useful to them if you expect them to try to help further. If you tell them what _did_ happen (be that an error message or a weird file created or a pain in your leg or whatever), then that is much more likely to be productive ;) If you would like someone to diagnose your illness, you must explain your symptoms ... E. -- https://mail.python.org/mailman/listinfo/python-list
Re: i cant seem to figure out the error
Hi Anthony, On 03/04/16 16:06, anthony uwaifo wrote: please i need help with this assignment. I have written a code and i still get an error. please help me debug my code. We see this assignment come up a lot. The "tutor" list is a better place to go, but well done for at least attempting it and coming up with quite a good result. - Create a method called `withdraw` that takes in cash withdrawal amount and updates the balance accordingly. if amount is greater than balance return `"invalid transaction"` Read this carefully. Read it _literally_. What does your 'withdraw' method return? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Beginner] - Hanging in the code, can't figure out what's wrong
On 03/04/16 20:54, Loop.IO wrote: The original post said what did happen, the code runs and hangs on the create file, and once i press Enter it then finishes and creates the file, not sure how you missed that but thanks Yes, I read your original post. That was days ago. The comment I was replying to was you telling BartC that what he had suggested "didn't work" (with no further information). Please pay attention to the context of the email you are responding to. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Beginner] - Hanging in the code, can't figure out what's wrong
Loop.IO: On 03/04/16 21:25, Loop.IO wrote: On Sunday, April 3, 2016 at 9:15:22 PM UTC+1, Erik wrote: On 03/04/16 20:54, Loop.IO wrote: The original post said what did happen, the code runs and hangs on the create file, and once i press Enter it then finishes and creates the file, not sure how you missed that but thanks Yes, I read your original post. That was days ago. The comment I was replying to was you telling BartC that what he had suggested "didn't work" (with no further information). Please pay attention to the context of the email you are responding to. E. Erik It was a syntax error. But sure, thanks. So, you reply to my advisory on how to report your problem by saying that your original post said what did happen. Your original post said: "the code runs and hangs on the create file, and once i press Enter it then finishes and creates the file" But it turns out that "It was a syntax error". If it was a syntax error, them how did the code run and "hang on the create file"? Don't try to sweep my suggestion (that you should describe your symptoms properly) under the carpet. It's a very important lesson to learn for people trying to report bugs/issues. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Beginner] - Hanging in the code, can't figure out what's wrong
On 03/04/16 22:49, Loop.IO wrote: You now seem to be on some sort of rampage I offered you some valuable advice. *plonk* E. -- https://mail.python.org/mailman/listinfo/python-list
Re: good way to avoid recomputations?
Hi Maurice, On 05/04/16 21:54, Maurice wrote: Hi. I working on a project where I have 5 scripts loading the same file at the very beginning so I would like to know the best way I can get this file without having to compute it 5 times. I also perform, in all the scripts, a list comprehension using this file that takes 30s to run. Would be cool to always have access to it as well. It sort of depends on what data you are extracting from the file (so expect people to ask for more information), but my initial gut reaction is to suggest writing a class that ingests the file. Create an object of that class, giving it the filename to ingest, and then use it in each of the 5 places. Or are you saying that each script is entirely separate? If so, then one approach might be to write a single script that "loads" the file and runs the comprehension and then "pickle" (look it up in the docs) the resulting structure. Your other scripts can then load the pickled version of the pre-computed comprehension much faster. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: python script for .dat file
Hi Muhammad, On 05/04/16 22:49, Muhammad Ali wrote: Would any one paste here some reference/sample python code for such extraction of data into text file? You haven't really explained what you want to achieve. What is the input format, what is the output format, what constraints are there on those two formats and the data within them and what transformation between the two are you trying to perform? If you're on a Linux system, then: $ cat A.dat B.dat C.dat > result.txt ... will do something that is close to what you have asked for so far. But I bet it's not what you want. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Fraud
On 16/04/16 23:02, Joel Goldstick wrote: On Sun, Apr 17, 2016 at 3:12 AM, Mel Drosis via Python-list wrote: My phone my accounts my home network have all been affected because of someone using coding from Python and Linux and GitHub and json. I don't even know what this stuff is but how do I get rid of it all. It's ruined my life. I'm curious as to what makes you think all this trouble was caused by python, etc. Did they leave a note? If this is genuine, then I don't want to be dismissive of the plea. However, given that Chris's response is quite enough for a genuine request to find a solution, I'll say that I smell a feint hint of troll ... :) E -- https://mail.python.org/mailman/listinfo/python-list
Re: Need help understanding list structure
On 02/05/16 22:30, [email protected] wrote: Can someone help me understand why or under what circumstances a list shows pointers instead of the text data? When Python's "print" statement/function is invoked, it will print the textual representation of the object according to its class's __str__ or __repr__ method. That is, the print function prints out whatever text the class says it should. For classes which don't implement a __str__ or __repr__ method, then the text "" is used - where CLASS is the class name and ADDRESS is the "memory pointer". > If I iterate over the list, I do get the actual text of each element > and am able to use it. > > Also, if I iterate over the list and place each element in a new list > using append, then each element in the new list is the text I expect > not memory pointers. Look at the __iter__ method of the class of the object you are iterating over. I suspect that it returns string objects, not the objects that are in the list itself. String objects have a __str__ or __repr__ method that represents them as the text, so that is what 'print' will output. Hope that helps, E. -- https://mail.python.org/mailman/listinfo/python-list
Re: for / while else doesn't make sense
On 20/05/16 00:51, Gregory Ewing wrote: It's not so bad with "else" because you need to look back to find out what condition the "else" refers to anyway. With my tongue only slightly in my cheek, if it was desirable to "fix"/clarify this syntax then I would suggest adding some optional (existing) trailing keywords to 'else' in this context that spells it out: for item in seq: if foo(item): break else if not break: nomatch() I would rule out "elif not break" - this is just about adding additional trailing words to existing syntax to spell it out (which might be a good teaching aid as well as turn into personal preferred style). I guess that it _could_ be a syntax error to reference "break" if the for/while loop does not contain the keyword in its body - this could actually address one of the "confusing" things mentioned in this thread, like: seq = [] for item in seq: pass else if not break: pass # Syntax error - "break" referenced in "for/else" clause but not present in loop body. Someone also pointed out that there are other flow control mechanisms that could prevent the 'else' from being executed: "return" and "raise". One could extend the above to allow one or more of those to be specified: else if not break or return or raise: That looks like a lot of noise, but again it could help make code more explicit (both to the human reader, and to a compile-time check): for item in seq: if foo(item): break if bar(item): return else if not return: pass # Syntax error - extended "for/else" clause does not reference "break", which exists in loop body. I would _not_ suggest that the above should ever mean "if it doesn't return, this code is executed regardless of whether 'break' happened" - one would remove the 'else' clause altogether for that. "raise" is more problematic as an exception can always be raised by pretty much _anything_ in the body without the keyword being present. Perhaps "or raise" is just a completely benign, optional keyword for the completists. Or perhaps it's simply not mentioned at all and is always implied (as is true of exceptions in other constructs such as plain "if/else", and just generally). The additional keywords would effectively just be a static checked filter - the original bare "else" would effectively mean "else if not any_flow_control_out_of_the_loop" (which is what it means today). In summary: Adding the "if not" extension is the suggestion, with "break" as the filter. "return" as an additional filter is a possibility which may add something, "raise" as an additional filter is a possibility which probably doesn't add anything (and may actually be distracting). I'm not entirely sure if _I_ like this yet (there are some things I've suggested that I like and some I'm not sure about and some I don't like but I've mentioned them anyway) - I'm just throwing it out there ;) E. -- https://mail.python.org/mailman/listinfo/python-list
Re: for / while else doesn't make sense
On 20/05/16 01:06, Steven D'Aprano wrote:
In my experience, some people (including me) misunderstand "for...else" to
mean that the else block runs if the for block *doesn't*. It took me the
longest time to understand why this didn't work as I expected:
for x in seq:
pass
else:
print("seq is empty")
So why don't we consider if that should be a syntax error - "else"
clause on "for" loop with no "break" in its body? I know that doesn't
change your fundamental mental model, but it's a hint that it's wrong :)
As it's backwards-incompatible, it could be introduced using a
__future__ import (a precedent is 'generators' and the "yield" keyword
back in the day) which those who would like the new check could add to
the top of their sources.
But also, as you say, any instances of that construct in the wild is
almost certainly a bug, so it would be good to be able to test code
using a command-line or similar switch to turn on the behaviour by
default for testing existing bodies of code.
I notice that pylint complains about this (as a warning). Is there any
reason why this should _not_ just be considered an error and be done
with it?
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: for / while else doesn't make sense
On 21/05/16 11:39, Steven D'Aprano wrote:
Just for the record, that's not my mental model *now*.
Sure. And I should have written "one's mental model" - the model of
anyone writing that code (not you personally) who thought the same at
the time.
It took me a long time to work out what for...else was actually doing, but
some years ago I finally managed to do so.
Coming from a partly assembler background, I happened to get it straight
away just because the thought of separate jump targets for the loop
condition being satisfied and breaking out of the loop being different
was quite natural (and a very nice feature to have in a high level
language!).
But you do ask a good question. Why isn't for...else with no break a syntax
error? I suppose it could be. But that's a *stylistic* question, and Python
generally treats that as "none of the compiler's business". It's not the
business of the compiler to enforce good code, only legal code.
On 21/05/16 08:29, Chris Angelico wrote:
> It's up to the linter, and ONLY the linter, to tell you about this.
Apologies for joining two threads here, but my reply is the same to
both, so it makes sense to me.
Let me tell you a story ;) Back in the mid-to-late
1980s I worked with C compilers on hardware that could take several
minutes to compile even a fairly trivial program. They errored on
syntactically incorrect code and happily compiled syntactically correct
code. Sometimes the output of the compiler wouldn't execute as expected
because of "undefined behaviour" of some parts of the language (which
the compilers could quite legally accept but would not produce valid
code for - even illegal ops are fair game at that point). They would
create valid code for the valid syntax of buggy code ("if (x = y) {
foo(); }") without a whimper.
At that time, we had a program called 'lint'. Every so often we might
run it on our sources and find all sorts of questionable behaviour that
our code might have that we should look harder at (such as that above).
We didn't run it all the time because it took so much longer to run than
the compiler itself.
Over time, some compilers started adding the checks and advisories that
"lint" gave to their messages. For some branded compilers ("Green
Hills", "SAS/C"), this even became a selling point. They started to do
this while still retaining the original compilation speed.
Things got faster, more was added to the compiler, and once the compiler
started to do everything it did and more, lint died(*).
And now, today, the compilers all do far more than the original 'lint'
program did in almost zero time every time some source is compiled. It
is free; it is not something one has to remember to run every so often.
So, back to Python ;)
The responses of "we can all write suspect/bad/ineffectual code - so
just run the linter" takes me back those 30 years to when we HAD to do
that with our C code too ...
There must be a better way.
I realise that Python has the issue that sometimes the person doing the
compilation is the end user (by virtue of them executing a .py file), so
lint-style compiler warnings aren't really appropriate - and that's the
reason why I suggested a syntax error: I understand that it's not really
any such thing, but it's all I had to work with and it ensured such code
could not get as far as the end user.
So I guess my question is perhaps whether Python compilers should start
to go down the same path that C compilers did 30 years ago (by starting
to include some linter functionality) but in a way that only outputs the
messages to developers and not end users. Also, the current "pylint"
blurs the edges between style (identifier names) and questionable code
("for/else" with no "break").
E. <-- waiting to be shot down again.
(*) Though to be fair, there are now even more deeply checking
(commercial) static tools available, which effectively fill the gap that
'lint' used to.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Exended ASCII and code pages [was Re: for / while else doesn't make sense]
On 25/05/16 11:19, Steven D'Aprano wrote: On Wednesday 25 May 2016 19:10, Christopher Reimer wrote: Back in the early 1980's, I grew up on 8-bit processors and latin-1 was all we had for ASCII. It really, truly wasn't. But you can be forgiven for not knowing that, since until the rise of the public Internet most people weren't exposed to more than one code page or encoding, and it was incredibly common for people to call *any* encoding "ASCII". Indeed - at that time, I was working with COBOL on an IBM S/370. On that system, we used EBCDIC ASCII. That was the wierdest ASCII of all ;) E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Exended ASCII and code pages [was Re: for / while else doesn't make sense]
On 26/05/16 02:28, Dennis Lee Bieber wrote: On Wed, 25 May 2016 22:03:34 +0100, Erik declaimed the following: Indeed - at that time, I was working with COBOL on an IBM S/370. On that system, we used EBCDIC ASCII. That was the wierdest ASCII of all ;) It would have to be... Extended Binary Coded Decimal Interchange Code, as I recall, predates American Standard Code for Information Interchange. EBCDIC's 8-bit code is actually more closely linked to Hollerith card encodings. I really didn't think it would be necessary to point this out (I thought the "" and emoji would be enough), but for the record, my previous message was clearly a joke. To break it down, Stephen was making the observation that people call all sorts of extended ASCII encodings (including proprietary things) "ASCII". So I took it to the extreme and called something that had nothing to do with ASCII a type of ASCII. As they say, if one has to explain one's jokes then they are probably not funny ... :( E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Exended ASCII and code pages [was Re: for / while else doesn't make sense]
On 26/05/16 10:20, Marko Rauhamaa wrote: ASCII has taken new meanings. For most coders, in relaxed style, it refers to any byte-oriented character encoding scheme. In C terms, ASCII == char * Is this really true? So by "taken new meanings" you are saying that it has actually lost all meaning. The 'S' stands for "Standard". It's an encoding (each byte value refers to a particular character value according to that standard). To say that any array of bytes, regardless of what each byte value should be interpreted as, is "ASCII" makes no sense. How "relaxed" are these 'coders' you're referring to, exactly? ;) Or, have I fallen for your trap, and you're joking with me too? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Exended ASCII and code pages [was Re: for / while else doesn't make sense]
On 26/05/16 08:21, Jussi Piitulainen wrote: UTF-8 ASCII is nice UTF-16 ASCII is weird. I am dumbstruck. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Operator Precedence/Boolean Logic
On 22/06/16 04:40, Elizabeth Weiss wrote:
I am a little confused as to how this is False:
False==(False or True)
Other people have explained why the expression evaluates as it does -
the sub-expression "False or True" evaluates to True (as one of the
operands is truthy). Your expression then becomes "False == True", which
is of course false.
To get the construct you were expecting (is the thing on the left hand
side equal to one of the things on the right hand side), you can use
Python's "in" keyword to "search" a collection (list, tuple, set,
dictionary etc) that contains the things you are trying to match:
>>> False in (False, True) # tuple
>>> False in [False, True] # list
>>> False in {False, True} # set
>>> False in {False: None, True: None} # dict
HTH,
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: I can't understand re.sub
On 29/11/15 21:36, Mr Zaug wrote:
I need to use re.sub to replace strings in a text file.
Do you? Is there any other way?
result = re.sub(pattern, repl, string, count=0, flags=0);
I think I understand that pattern is the regex I'm searching for and
repl is the thing I want to substitute for whatever pattern finds but
what is string?
Where do you think the function gets the string you want to transform from?
This should be simple, right?
It is. And it could be even simpler if you don't bother with regexes at
all (if your input is as fixed as you say it is):
>>> foo = "foo bar baz spam CONTENT_PATH bar spam"
>>> ' Substitute '.join(foo.split(' CONTENT_PATH ', 1))
'foo bar baz spam Substitute bar spam'
>>>
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: I can't understand re.sub
On 30/11/15 08:51, Jussi Piitulainen wrote:
Surely the straight thing to say is:
>>> foo.replace(' CONTENT_PATH ', ' Substitute ')
'foo bar baz spam Substitute bar spam'
Not quite the same thing (but yes, with a third argument of 1, it would be).
But there was no guarantee of spaces around the target.
I know. It was just an example to show that there might be an option
that's not a regex for the specific use indicated. It's up to the OP to
decide whether they think the spaces (or any other, or no, delimiter)
would actually be required or useful. Or whether they really prefer a
regex after all.
If you wish to,
say, replace "spam" in your foo with "REDACTED" but leave it intact in
"May the spammer be prosecuted", a regex might be attractive after all.
But that's not what the OP said they wanted to do. They said everything
was very fixed - they did not want a general purpose human language text
processing solution ... ;)
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: I can't understand re.sub
On 01/12/15 05:28, Jussi Piitulainen wrote: A real solution should be aware of the actual structure of those lines, assuming they follow some defined syntax. I think that we are in violent agreement on this ;) E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Could you explain this rebinding (or some other action) on "nums = nums"?
On 01/12/15 21:37, Denis McMahon wrote: The assignment succeeds. That's imo a bug. If it's a TypeError to try and assign a value to tup[1], then tup[1] should not allow the mutated list to be assigned. Nothing got assigned. That original list object remains in that slot. However, it has been mutated since it was originally assigned. But I can see what you're getting at - what you're asking for is that the *container* object whose element is being assigned to is first queried as to whether it will accept a mutated element being assigned to it before that element is mutated. This looks to be a fundamental issue with the augmented assignment mechanism. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Could you explain this rebinding (or some other action) on "nums = nums"?
Apologies for self-replying, On 01/12/15 22:34, Erik wrote: what you're asking for is that the *container* object whose element is being assigned to is first queried as to whether it will accept a mutated element being assigned to it before that element is mutated. What I said above is rubbish. The situation is approximately similar to: a = [4, 5, 6] t = ([1, 2, 4], a) a.append(7) a.append(8) a.append(9) The point is, you're mutating something that an immutable object contains. In the example you give, that's caught because of the subsequent explicit assignment. In the example above, it's not caught. But it's the same thing. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: "Downloading"
On 01/12/15 23:28, Ian Kelly wrote: What about transfers that are initiated by neither? scp remote_host1:path/to/file remote_host2:path/to/destination Regardless of how the transfer is invoked, in traditional parlance the source uploads, the target downloads. Why is this on the Python list? ;) E. -- https://mail.python.org/mailman/listinfo/python-list
Re: static variables
On 02/12/15 01:02, Steven D'Aprano wrote: On Tue, 1 Dec 2015 08:15 pm, Grobu wrote: # - >>> def test(arg=[0]): ... print arg[0] ... arg[0] += 1 Awesome! Hideous! using a mutable default as static storage. Exposing something a caller can override as a local, static, supposedly "private" value is IMHO a tad ... ugly? (*) E. (*) No I don't want to resurrect that thread. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question about split method
On 05/12/15 20:27, Mark Lawrence wrote:
On 05/12/2015 19:51, Robert wrote:
On Saturday, December 5, 2015 at 2:29:28 PM UTC-5, Peter Pearson wrote:
On Wed, 2 Dec 2015 14:44:30 -0600, Ian Kelly
wrote:
On Wed, Dec 2, 2015 at 2:37 PM, Robert wrote:
[snip]
ss0="1, 2, 4, 8, 16".split(", ")
[snip]
Try help(str.split)
Or if, like me, you can't remember the magic word "str", ask:
help("".split)
and you know you're asking about the right "split".
--
To email me, substitute nowhere->runbox, invalid->com.
Thanks for your smart method.
The even smarter method is:
help(''.split)
as this saves you reaching for the shift key :)
... except you're already pressing it for the open parenthesis ... ;)
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Accessing container's methods
Hi Tony,
On 07/12/15 18:10, Tony van der Hoff wrote:
A highly contrived example, where I'm setting up an outer class in a
Has-a relationship, containing a number of Actors. The inner class needs
to access a method of the outer class; here the method get_name.
Generally, an object should not need to know which container it's in
(let alone its "index" or "key" in that container). Amongst other
things, you can't put the object into multiple containers which might be
organised differently and you are asking for bugs where the container
and the object get out of sync WRT just where the object is in the
container (in your example, if you found you wanted to add a method
where the 'actors' list is modified (say, calling "self.actors.insert(3,
...)", or sorting the list) then things get nasty quickly.
However, you've said this is a highly contrived example, so I'll bear
with you and assume what you're trying to do is not quite as nasty as
the example implies ;)
Can anyone please advise me on how to achieve this magic?
As you can't sensibly put the object into more than one container at a
time anyway, then you can pass the container object to the Actor object
as its "parent". It can then call its parent object for things that the
parent will know (such as, the total number of contained objects):
class Actor:
def __init__ ( self, name, id, parent ):
self.name = name
self.id = id
self.parent = parent
def get_name( self ):
txt = "I'm Actor {} Number {} of {}".\
format( self.name, self.id, self.parent.count_actors() )
return txt
Then you can add a new actor with:
self.actors.append( Actor( n, i, self ) )
Note that you are creating circular references here, too (the container
references the Actor object and the Actor object references the
container). Just another possible issue to bear in mind ...
Also, while I'm looking at this, you have this loop and comment:
>def __init__( self, names ):
> self.actors = []
>
> i = 0
> for n in names:
>self.actors.append( Actor( n, i ) )
>i += 1# here is a case for python supporting post-increment!
However, if you refactor that loop to use iterators, you don't need to
manually manipulate 'i' at all (you need to import the itertools module
first, and this is the "new" version where the container is passed in as
the parent):
def __init__( self, names ):
self.actors = [ Actor ( n, i, self ) for n, i in
itertools.izip(names, itertools.count()) ]
Or, if you don't like list comprehensions:
def __init__( self, names ):
self.actors = []
for n, i in itertools.izip(names, itertools.count()):
self.actors.append( Actor( n, i, self ) )
(I assume you're using Python 3 because of your print statement - in
Python 3, 'itertools.izip' should just be 'zip'.)
HTH,
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Help on for loop understanding
Hi Robert,
On 08/12/15 01:39, Robert wrote:
I don't find a way to show __next__ yet.
Can we explicitly get the iterator for a list?
Thanks,
Excuse me. I find it as the following:
xx.__iter__().next
Out[16]:
xx.__iter__().next()
Out[17]: 1
Robin has told you how things work under the hood for the particular
version of Python that he is running (Python 3). As you've seen, it
works a bit different under the hood in your version (Python 2).
This is why you should not be calling the __ ("dunder") methods
directly. Until you understand more and want to write your own classes
that support being iterated using the 'for' keyword, you should probably
ignore them.
Instead, the way to do this which works on all versions is:
x = [1, 2, 3, 4]
xit = iter(x)
next(xit)
next(xit)
next(xit)
next(xit)
next(xit)
This is what the 'for' keyword is doing for you - it first gets an
iterator for the list (using iter()) and then processes each element
that the iterator returns (from next()) until it raises the exception.
It then suppresses the exception (so you don't have to catch it
yourself) and exits the for loop.
Of course, it might actually do this using the __ methods and other
things as a shortcut internally, but that's just an implementation detail.
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Help on for loop understanding
On 08/12/15 01:50, Robert wrote:
One example, see below please, is in the above mentioned link. I don't see
the purpose of the example.
OK, so there are two parts to this.
The first, is "how do I iterate over something". The answer to that is
using "for" or using "iter()" followed by zero or more calls to
"next()". In this case, by using the correct syntax/function calls your
script can work under various versions of Python without change.
The second is "how do I make my own classes iterable". This is what the
example you pasted is trying to show. In this case, you are implementing
things which are "internal" to the way the version of Python you are
using does things (which is why the code Robin posted wasn't quite right
for you).
I have the following two same results. What do they tell me?
They tell you that the implementation does the same thing as the default
implementation for a list. That perhaps doesn't help much - especially
with the comment in the example telling you not to do it!
Instead, try the following (Python 2):
class MyList(list):
def __iter__(self):
return MyListIter(self)
class MyListIter(object):
def __init__(self, lst):
self.lst = lst
self.i = -1
def __iter__(self):
return self
def next(self):
if self.i >= -len(self.lst):
item = self.lst[self.i]
self.i -= 1
return item
raise StopIteration
if __name__ == "__main__":
a = MyList([1, 2, 3, 4])
ia = iter(a)
print 'type(a): %r, type(ia): %r' %(type(a), type(ia))
for i in a:
print i,
print
while True:
print next(ia)
What we have here is the same class that subclasses 'list'. It's just a
list. However, it has a custom iterator. In this implementation the
iterator works BACKWARDS through the list - the final element is
returned first, the penultimate element second, and so on. After the
first element has been returned, the iterator raises StopIteration. This
tells you not to call next() again, or if in a for loop, the loop is exited.
So, you can write your class's iterator to do anything that makes sense
when someone says "for i in myclassinstance:".
If your class is a subclass of a class ("is-a") that already has a
defined iterator (such as a list or a dict) and the behaviour of that is
correct for you, then you need to do nothing (you inherit that class's
__iter__() method).
If your class should iterate over an embedded object ("has-a") that
already has a defined iterator, then your __iter__() method can just
delegate to that object's iterator using something like:
def __iter__(self):
return iter(self.embedded_thing)
Does that make more sense?
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Accessing container's methods
Annoyingly, there seemed to be no responses to the original question
when I wrote that and then shortly after, I saw all the others (and we
all pretty much said the same thing - so I'm not sure why I was singled
out for special attention ;)).
On 08/12/15 19:02, Thomas 'PointedEars' Lahn wrote:
Erik wrote:
^^^^
Please fix, Erik #75656.
Fixed(*)
Thomas 'PointerEars', you have chosen to selectively quote snippets of
code and comments out of context, so I think it's futile to respond to
those arguments individually. The original request (if you read it) was
to return a string that said, essentially, "I am element 2 of 3 in my
container".
You posted a "Quickhack" (which, to be fair, is an accurate description)
which is incomplete, has errors and makes no sense in the context of the
original question. We all know we can create a list in Python (of parent
objects or whatever), but I think that if you expanded on that class a
bit more (methods for the containers to update the contained objects on
just what their index/key is etc) that you'll soon realise it's not a
scalable option.
Also, WRT the original question, what is the method supposed to return
now? "I am element 0 of 3 in container , key 'bar' of ('bar',
'foo', 'spam') in container "? Just curious.
I'm interested in this response though:
>> Generally, an object should not need to know which container it's in
>
> NAK. All kinds of objects already "know" which container they are in.
Please elucidate. Examples from the standard library would be interesting.
E.
(*) In the sense that it's not going to change ;)
--
https://mail.python.org/mailman/listinfo/python-list
Re: Can anyone help me modify the code so the ball starts in random directions
Hi, On 11/12/15 23:19, [email protected] wrote: Can anyone direct me in the direction where to start the code for the randomized of the ball to start. Your questions over the last week or so appear to be homework assignments. However, I'll give you a hint: in the interactive interpreter shell, try: >>> import random >>> help(random) Read that and try to work out how you might apply one of the functions to your problem. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Can anyone help me modify the code so the ball starts in random directions
Hi, On 11/12/15 23:19, [email protected] wrote: Can anyone direct me in the direction where to start the code for the randomized of the ball to start. Your questions over the last week or so appear to be homework assignments. However, I'll give you a hint: in the interactive interpreter shell, try: >>> import random >>> help(random) Read that and try to work out how you might apply one of the functions to your problem. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: appending a line to a list based off of a string found in a previous list
Hi Pedro,
It would be _really useful_ if you included code that could be pasted
into an interpreter or file directly to show your problem. You are
referencing several data sources ("satellite_dataread" and "list2") that
we can only guess at.
On 12/12/15 21:48, Pedro Vincenty wrote:
Hello, I'm wondering how to append a line from a file onto a
list(easy part) provided that the line contains strings specific to a
previous list I've already made(hard part).
The following is a complete version of your example with some guessed-at
data:
"""
satellite_dataread = (
"spam ham eggs,ctry0\n",
"spam ham eggs foo,ctry1\n",
"spam ham,ctry2\n",
"spam bar ham eggs,ctry3\n",
)
list2 = ['foo', 'bar']
satellite_origin_list = []
for line in satellite_dataread:
if any(i in line for i in list2):
line = line.strip()
satellite, country= line.split(',')
satellite_origin_list.append(country)
print (satellite_origin_list)
"""
When I put that in a file and run it, I get:
$ python foo.py
['ctry1', 'ctry3']
$ python3 foo.py
['ctry1', 'ctry3']
So, it seems to work as you describe already - what is it that I am
missing? Please explain what you expect to see (or change the guessed-at
input data to an example of what you actually have).
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't response pydoc on my Python 2.7?
Hi Robert, On 12/12/15 23:01, Robert wrote: I want to use pydoc as some online tutorial shows, but it cannot run as below. What is wrong? "some online tutorial"? import pydoc pydoc Correct - in the interactive interpreter, typing the name of an object prints its value. You have imported a module and then typed its name. pydoc sys SyntaxError: invalid syntax import sys pydoc sys SyntaxError: invalid syntax In both of these, there is no operator after "pydoc", so what does it mean? help(pydoc) Help on module pydoc: .. Instead of omitting the result of that, read it! FWIW, The relevant part based on what I _think_ you're trying to do (as you didn't include the URL of your "some online tutorial") is probably this part: """ DESCRIPTION In the Python interpreter, do "from pydoc import help" to provide online help. Calling help(thing) on a Python object documents the object. Or, at the shell command line outside of Python: Run "pydoc " to show documentation on something. """ E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't response pydoc on my Python 2.7?
On 12/12/15 23:08, Robert wrote: In fact, I wanted to run the following code. When it failed, I moved to the original question above. How did it fail? Tell us what _did_ happen. It works fine for me: $ pydoc module1 Help on module module1: NAME module1 FILE /tmp/robert/module1.py DATA a = 'A' b = 'B' c = 'C' $ pydoc module2 Help on module module2: NAME module2 FILE /tmp/robert/module2.py DATA __all__ = ['a', 'b'] a = 'A' b = 'B' E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't response pydoc on my Python 2.7?
Hi Robert, On 13/12/15 00:04, Robert wrote: Excuse me for the incomplete information on previous posts. Here is the message when I run it on Canopy (module1.py and module2.py are in the current folder): Welcome to Canopy's interactive data-analysis environment! with pylab-backend set to: qt Type '?' for more information. I don't have any experience with "Canopy", but it looks to me like it is providing you with an interactive Python environment. In [1]: pydoc module1 File "", line 1 pydoc module1 ^ SyntaxError: invalid syntax As this is an interactive Python environment, then Python syntax is required. Remember what "help(pydoc)" told you: """ In the Python interpreter, do "from pydoc import help" to provide online help. Calling help(thing) on a Python object documents the object. """ So, instead of "pydoc module1" (which is not good Python syntax), do what the help document tells you to do within a Python interpreter: import module1 pydoc.help(module1) import module2 pydoc.help(module2) Does that work better? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't response pydoc on my Python 2.7?
On 13/12/15 00:19, Robert wrote: It turns out that Enthought does not allow pydoc as the link said: http://stackoverflow.com/questions/12063718/using-help-and-pydoc-to-list-python-modules-not-working I don't think that's what the article is telling you. Try what I said in my previous message. Other than that, I think I'm probably out of ideas on this one ... E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Weird list conversion
On 13/12/15 20:05, KP wrote:
On Sunday, 13 December 2015 11:57:57 UTC-8, Laura Creighton wrote:
In a message of Sun, 13 Dec 2015 11:45:19 -0800, KP writes:
Hi all,
f = open("stairs.bin", "rb") data = list(f.read(16)) print data
returns
['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00',
'\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00']
The first byte of the file is 0x3D according to my hex editor, so
why does Python return '=' and not '\x3D'?
As always, thanks for any help!
0x3d is the ascii code for '='
I am aware of that - so is the rule that non-printables are returned
in hex notation whereas printables come in their ASCII
representation?
No, what is _returned_ is a list of one-byte strings.
When you call "print", then the list class's __repr__() method is called
which in turn calls the contained objects' __repr__() methods in turn -
it is those methods (in this case, they are all the string class's)
which is deciding to render ASCII printable characters as just their
value and ASCII non-printable characters using their hex notation.
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Weird list conversion
On 13/12/15 20:28, Erik wrote: When you call "print", then the list class's __repr__() method is called which in turn calls the contained objects' __repr__() methods in turn I mean the __str__() method, not __repr__() in this case - however, the answer is otherwise the same. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Installing PyCharm on Windows
Hello Thomas, On 19/12/15 18:32, Thomas 'PointedEars' Lahn wrote: > (and you should seriously > consider upgrading Windows or even better, to switch to a real operating > system, like GNU/Linux On 20/12/15 08:28, Thomas 'PointedEars' Lahn wrote: > Anyhow, *I* was not intending to start an OS flame war, Really? Specifically telling someone that their OS of choice is "not a real operating system" (without any sort of justification) is not intending to start an OS flame war? Of course that's what you intended to do. The answer to "Python does not work in this way for me" should *never* be "change your operating system". FWIW, I can see that you do indeed have something to add to these discussions but unfortunately you seem to also feel the need to provoke a reaction from people. As a result, anything of value you impart - and there IS something there - gets lost in the noise. If you could just bring yourself to offer your expertise without making direct value judgements on other people's choices, preferences and ability compared to your own, I think your voice would be listened to a lot more and things would be a whole lot easier. This is just friendly advice - I am not _insisting_ that you do anything you do not wish to ;) E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Need help on a project To :"Create a class called BankAccount with the following parameters "
On 24/12/15 19:36, [email protected] wrote: you are right chris it is a homework, but we are to figure out the solution first , all we need is some guidance please and not to be spoon fed like many thought From your response, it seems that this is a homework question that a group of you are working on. That might explain some of the confusion (both from your side, posting similar questions and slightly confusing replies) and from the list side (asking why different email addresses were being used - it all seemed a bit suspicious) ... I would recommend that one of you acts as a spokesperson for the group. However, this latest response is much better. You included your code, and it looks like it would compile (I haven't run it myself, but you've included reasonable results too). Your problem looks like it's related to how the unit test harness reports its errors and I guess it's a bit unfair for you to completely have to understand how that works if you're just learning. However, the wording of the assignment _does_ give a clue as to the problem. The error seems to be coming from the test for the "withdraw" method with a value greater that what should be the current balance: > [{"message": "Failure in line 23, in test_invalid_operation\n self.assertEqual(self.my_account.withdraw(1000), \"invalid transaction\", msg='Invalid transaction')\nAssertionError: Invalid transaction\n"}]}], "specs": {"count": 5, "pendingCount": 0, "time": "0.80"}} Your assignment said: Create a method called `withdraw` that takes in cash withdrawal amount and updates the balance accordingly. if amount is greater than balance return `"invalid transaction"` Your method is: def withdraw(self, amount): if self.balance>= amount: self.balance -= amount else: print('invalid transaction') Can you spot the difference between what the assignment is asking for and what the method is doing? Look at both paths carefully (when called with a valid amount and when called with an amount that is too large). Pay careful attention to the words the assignment uses. a1 = BankAccount (90) a1.deposit(90) a1.withdraw(40) a1.withdraw(1000) class MinimumBalanceAccount(BankAccount): def __init__(self): BankAccount.__init__(self) [snip] i believe the last three lines of my code answered your question. When the assignment requested you create a subclass, it probably expected a subclass that would run. Have you tried creating an instance of your subclass? Try it - you might see another problem that needs fixing. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Need help on a project To :"Create a class called BankAccount with the following parameters "
Hi, I appreciate that you've made an effort this time to write some code, but have you attempted to try to _execute_ any of this? [I can see that the answer must be "no"] On 25/12/15 23:09, [email protected] wrote: > #my solution is: > def manipulate_data(dic,dict_data = {'name':'prince','age':21,'sex':'male'}): >return dict_data.keys() > > def manipulate_data( alist, list_data = [2,8,16,23,14]): >return list_data.reverse() > > def manipulate_data(aset, set_data = {"bee","cee","dee"}): >set_data = {"bee","cee","dee"} >set_data.update("ANDELA","TIA","AFRICA") >return dictionary_data > #please what is wrong with my code If you try to execute it (by writing a test that calls the functions), you will get errors. Those errors will help you to fix it. If you get to the point where there is an error you really can't work out for yourself then you can ask a specific question related to what it is you don't understand about the error. It looks like you're just typing in something and sending it to the list first rather than the Python interpreter. If you want to learn how to program well, then you need to learn how to interpret the compiler/parser error messages or exceptions you get and work out what is wrong for yourself. You can only do that by running your code. I'll give you a hint - read the words of your assignment very carefully. It says "a function" (not "several functions") that "Accepts as the first parameter a string". Look at what it then says about the second parameter, based on that first parameter. Work on it from there and when you get really stuck, post the code and the Python error you get and why you don't understand it (saying what you _think_ it means but why that doesn't help you would also be good). E. -- https://mail.python.org/mailman/listinfo/python-list
Re: Need help on a project To :"Create a class called BankAccount with the following parameters "
On 27/12/15 15:02, lee wrote:
the code i have tested base on Cameron's code
def manipulate_data(kind, data):
if kind == 'list':
return list(data)[::-1]
elif kind == 'set':
return set(data)
elif kind == 'dictionary':
return dict( data)
manipulate_data("list", range(1,6))
a = manipulate_data("set", {"a", "b", "c", "d", "e"})
a.add("ANDELA")
a.add("TIA")
a.add("AFRICA")
b = manipulate_data("dictionary", {"apples": 23, "oranges": 15, "mangoes": 3,
"grapes": 45})
list(b.keys())
[snip]
i guess i passed the first requirement to return the reversed order of the list
and believe i messed up when creating a set then add data to the set, also
something is wrong with returning the keys of the dictionary
can someone point out the error in my code and the meaning of the unittes error?
You're nearly there.
After you've called the function, anything you do to the result is not
done BY the function and will therefore not be done when called by other
code.
The unit test that calls the function will not do those things. It
expects them to already be done.
So ... what changes to your function do you think would fix that?
Regards,
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Need help on a project To :"Create a class called BankAccount with the following parameters "
On 27/12/15 20:32, Prince Udoka wrote:
thanks mr cameron simpson, finally at i got the solution, God bless you:
def manipulate_data(kind, data):
if kind == 'list':
for data in [1, 2, 3, 4, 5]:
return data.reverse()
elif kind == 'set':
for data in {"a", "b", "c", "d", "e"}:
data.add("ANDELA")
data.add("TIA")
data.add("AFRICA")
return data
elif kind == 'dictionary':
for data in {"apples": 23, "oranges": 15, "mangoes": 3, "grape": 45}:
return data.key()
Please stop posting code to the list which you have not even attempted
to run. This is getting a bit silly.
RUN your code. Three of the four paths through that code will fail when
it is run, so I am sure that you have not.
If you don't understand the error messages then ask what they mean,
along with your guess at what you think they mean and what you tried to
do about it (but did not work).
Please consider joining a list which is more appropriate for these
questions:
https://mail.python.org/mailman/listinfo/tutor/
E.
--
https://mail.python.org/mailman/listinfo/python-list
Re: I'm missing something here...
On 11/01/16 23:26, Skip Montanaro wrote: If I change the last line of find_problems to call prob_dates.update(), the message disappears. Why is pylint (1.4.2 BTW) complaining that the prob_dates argument of find_problems is unused when I use the |= operator? Is it complaining about that, or is it because the 'for' loop body might be executed zero times? E. -- https://mail.python.org/mailman/listinfo/python-list
Re: I'm missing something here...
On 12/01/16 07:13, Cameron Simpson wrote: On 11Jan2016 23:55, Erik wrote: Is it complaining about that, or is it because the 'for' loop body might be executed zero times? The former. Almost any loop _might_ be executed zero times. Compilers and linters etc should only complain if they can prove the loop is always executed zero times. Sure, but Skip was thinking he'd found a bug - I was just raising the possibility that the bug could have been that the loop was (incorrectly) determined to be executed zero times for some reason. E. -- https://mail.python.org/mailman/listinfo/python-list
Re: I'm missing something here...
Apologies for self-replying On 12/01/16 08:24, Erik wrote: On 12/01/16 07:13, Cameron Simpson wrote: The former. Almost any loop _might_ be executed zero times. Compilers and linters etc should only complain if they can prove the loop is always executed zero times. I was just raising the possibility that the bug could have been that the loop was (incorrectly) determined to be executed zero times for some reason. Having just read it again, I note that Skip said he'd changed the |= to something different (and I've since read the solution to the question). I had misread what Skip said to mean he had added a new line _after_ the 'for' loop which touched the variable. E. -- https://mail.python.org/mailman/listinfo/python-list
