Re: replacing `else` with `then` in `for` and `try`
On 2017-11-04, Michael Torrie wrote: > On 11/03/2017 09:06 PM, Chris Angelico wrote: >> On Sat, Nov 4, 2017 at 1:57 PM, Michael Torrie wrote: >>> On 11/03/2017 07:09 PM, Steve D'Aprano wrote: That's incorrect. There are multiple ways to exit a loop that will prevent the `else` block from executing, `break` is only one. >>> >>> Such as? >> >> There are many. But other than break, I don't know of any that WOULD >> execute the next line of code immediately _after_ the loop. > > Can you be more specific? What are some of these "many" ways of aborting > a loop? Help a guy out here. > > I know, for example, that we have exceptions. But those hardly matter in > this discussion because they wouldn't execute the else clause either. > They'd either be caught elsewhere, or end the program. sys.exit() can > also terminate a for loop, but it terminates the whole program without > running the else statement. Yes, those are the sort of thing that Steve was referring to. He was being unhelpfully pedantic. A giant meteor destroying the computer the program was running on would prevent the 'else' block from executing too. -- https://mail.python.org/mailman/listinfo/python-list
Re: Ideas about how software should behave (was: replacing `else` with `then` in `for` and `try`)
On 2017-11-04, Ben Finney wrote: > To respond to the criticism of an idea – criticism containing no mention > of the person – as though it “clearly refers to the [person]”, is of > significant concern on a software dicussion forum such as this. No, the thing that is "of significant conern on a software discussion forum such as this" is people such as yourself defending the abuse of other contributors. -- https://mail.python.org/mailman/listinfo/python-list
Re: Ideas about how software should behave (was: replacing `else` with `then` in `for` and `try`)
On Sat, Nov 4, 2017 at 11:25 PM, Jon Ribbens wrote: > On 2017-11-04, Ben Finney wrote: >> To respond to the criticism of an idea – criticism containing no mention >> of the person – as though it “clearly refers to the [person]”, is of >> significant concern on a software dicussion forum such as this. > > No, the thing that is "of significant conern on a software discussion > forum such as this" is people such as yourself defending the abuse of > other contributors. Maybe we're not defending the abuse of other contributors. Maybe we're defending a legitimate, if somewhat caustic, response to a ridiculous suggestion. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: matplot plot hangs
Tim,
it won't even advance to that line.
On Thu, Nov 2, 2017 at 8:28 AM, Tim Williams wrote:
> On Wednesday, November 1, 2017 at 6:30:27 PM UTC-4, Andrew Z wrote:
> > nope. it doesnt:
> >
> > I added print-s after each line and that produced:
> > [az@hp src]$ cat ./main1.py
> > import matplotlib.pyplot as plt
> > print("imported")
> > plt.plot([1,2,4,1])
> > print("plot is done")
> > plt.show()
> > print("show is done")
> >
> > [az@hp src]$ python3.5 ./main1.py
> > imported
> > ^C^Z
> > [1]+ Stopped python3.5 ./main1.py
> >
> >
> > On Wed, Nov 1, 2017 at 9:31 AM, Vlastimil Brom >
> > wrote:
> >
> > > 2017-11-01 13:49 GMT+01:00 Andrew Z :
> > > > Wolfgang,
> > > > I tried to ran from ide with no rwsults, so now im trying from a
> > > terminal
> > > > in xwindow.
> > > > The .plot is the last line in the script and it does hang trying to
> > > execute
> > > > it.
> > > >
> > > >
> > > > On Nov 1, 2017 05:44, "Wolfgang Maier" <
> > > > [email protected]> wrote:
> > > >
> > > > On 01.11.2017 00:40, Andrew Z wrote:
> > > >
> > > >> hello,
> > > >> learning python's plotting by using matplotlib with python35 on
> > > fedora 24
> > > >> x86.
> > > >>
> > > >> Installed matplotlib into user's directory.
> > > >> tk, seemed to work -
> > > >> http://www.tkdocs.com/tutorial/install.html#installlinux - the
> window
> > > >> shows
> > > >> up just fine.
> > > >> but when trying to run the simple plot (
> > > >> https://matplotlib.org/examples/pylab_examples/simple_plot.html)
> the
> > > >> script
> > > >> is hanging on;
> > > >>
> > > >> plt.plot(t, s)
> > > >>
> > > >> attempts to
> > > >> matplotlib.interactive(True) didn't bring anything,
> > > >>
> > > >>
> > > > Hi Andrew,
> > > >
> > > > From which environment are you trying to run the example? In the
> > > terminal,
> > > > from within some IDE, inside a jupyter notebook?
> > > >
> > > > Are you sure the script "is hanging on plt.plot(t, s)" and not after
> > > that?
> > > >
> > > > Best,
> > > > Wolfgang
> > > >
> > > > --
> > > Hi,
> > > sorry if it is too trivial, just to make sure, do you have a call to
> > > "show()" the resulting plot in the code?
> > >
> > > An elementary plotting code might be e.g.:
> > >
> > > import matplotlib.pyplot as plt
> > > plt.plot([1,2,4,1])
> > > plt.show()
> > >
> > > Does this work in your environment?
> > >
> > > It was not quite clear, what do you plan with interactive drawing, or
> > > whether you are using e.g. plt.interactive(True) already - this might
> > > be a problem as there could be collisions or the plot window is closed
> > > after the standalone script finishes.
> > >
> > > hth,
> > > vbr
> > > --
> > > https://mail.python.org/mailman/listinfo/python-list
> > >
>
> Have you tried
>
> plt.show(block=False)
> ?
> --
> https://mail.python.org/mailman/listinfo/python-list
>
--
https://mail.python.org/mailman/listinfo/python-list
Re: replacing `else` with `then` in `for` and `try`
On Sat, Nov 4, 2017 at 11:22 PM, Jon Ribbens wrote:
> On 2017-11-04, Michael Torrie wrote:
>> On 11/03/2017 09:06 PM, Chris Angelico wrote:
>>> On Sat, Nov 4, 2017 at 1:57 PM, Michael Torrie wrote:
On 11/03/2017 07:09 PM, Steve D'Aprano wrote:
> That's incorrect. There are multiple ways to exit a loop that
> will prevent the `else` block from executing, `break` is only one.
Such as?
>>>
>>> There are many. But other than break, I don't know of any that WOULD
>>> execute the next line of code immediately _after_ the loop.
>>
>> Can you be more specific? What are some of these "many" ways of aborting
>> a loop? Help a guy out here.
>>
>> I know, for example, that we have exceptions. But those hardly matter in
>> this discussion because they wouldn't execute the else clause either.
>> They'd either be caught elsewhere, or end the program. sys.exit() can
>> also terminate a for loop, but it terminates the whole program without
>> running the else statement.
>
> Yes, those are the sort of thing that Steve was referring to.
> He was being unhelpfully pedantic. A giant meteor destroying
> the computer the program was running on would prevent the 'else'
> block from executing too.
My definition of "preventing else from executing" is that it would (a)
not execute code inside the else block, and (b) execute unindented
code immediately *after* that else block. Consider a try/finally
block:
try:
print("Setup")
...
finally:
print("Cleanup")
print("Carrying on")
Before we reach "carrying on", we are guaranteed to pass through
"cleanup". Steve's pedantry is 100% accurate for situations where the
setup and cleanup involve the network; you can't actually guarantee
that the cleanup will be performed (a hard exit will abort the whole
process, a 'kill -9' will shut you down, powering down the computer
means nothing happens), so you have to assume that the cleanup might
not happen (eg with PostgreSQL, the database server will roll back
your transaction and clean up the trash). But AFAIK there is no way to
reach "carrying on" without first executing "cleanup".
With the for-else clause, we have the same valid pedantry, but with a
few differences. A 'return' inside the loop will skip the 'else'
clause (but wouldn't skip a 'finally'), as will any exception. But
neither of those would hit "carrying on" either. AFAIK the only way to
skip the else *and hit the "carrying on" call* is to use 'break'.
That's a non-pedantic interpretation of "skip the else clause".
ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: Try: Except: evaluates to True every time
On Sun, Nov 5, 2017 at 2:31 AM, brandon wallace wrote: > > I have this code that tests a server to see if it is listening on port 123 > runs and evaluates to True every time. Even if the server does not exist but > it is not supposed to do that. I am getting no error message at all. What is > going on with this code? > > > > #!/usr/bin/env python > > import socket > > hostname = ["192.168.1.22", "192.168.1.23", "200.168.1.24", "19.0.0.0"] > port = 123 > > def check_udp(hosts, port_num): > '''Test the UDP port on a remove server.''' > s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > for host in hosts: > try: > s.connect((host, port_num)) > return "Port 53 is reachable on: %s" % host > except socket.error as e: > return "Error on connect: %s" % e > > check_udp(hostname, port) Do you understand what it actually means to connect a UDP socket? If not, I suggest reading up on the nature of UDP. You can't probe a remote server this way; it simply doesn't work like that. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Try: Except: evaluates to True every time
I have this code that tests a server to see if it is listening on port 123 runs and evaluates to True every time. Even if the server does not exist but it is not supposed to do that. I am getting no error message at all. What is going on with this code? #!/usr/bin/env python import socket hostname = ["192.168.1.22", "192.168.1.23", "200.168.1.24", "19.0.0.0"] port = 123 def check_udp(hosts, port_num): '''Test the UDP port on a remove server.''' s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for host in hosts: try: s.connect((host, port_num)) return "Port 53 is reachable on: %s" % host except socket.error as e: return "Error on connect: %s" % e check_udp(hostname, port) -- https://mail.python.org/mailman/listinfo/python-list
Re: Try: Except: evaluates to True every time
On Sun, 5 Nov 2017 02:31 am, brandon wallace wrote:
>
> I have this code that tests a server to see if it is listening on port 123
> runs and evaluates to True every time. Even if the server does not exist but
> it is not supposed to do that. I am getting no error message at all. What is
> going on with this code?
You're returning a string in both cases. Both strings evaluate as true when
treated as bools.
Success:
> return "Port 53 is reachable on: %s" % host
Failure:
> except socket.error as e:
> return "Error on connect: %s" % e
>
> check_udp(hostname, port)
That's the first bug. The second bug is that I don't think the code does what
you think it does. You seem to be calling it with a single hostname,
presumably a string. But then you split the hostname into individual letters,
and try to connect to each of them. The *first* attempt either succeeds or
fails, and then returns.
So if you call check_udp("mailserver", 143), your function calls
for host in "mailserver":
try:
s.connect((host, port_num))
which attempts to connect to ("m", 143). That will either succeed (probably
not), or fail (probably this), and then the function returns a string, which
you apparently never look at.
I suggest you re-write your check_udp function to something more like this:
def check_udp(host, port_num):
'''Test the UDP port on a remove server.'''
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect((host, port_num))
return True
except socket.error as e:
return False
But even this is suspicious, since it is vulnerable to a "Time Of Check To
Time Of Use" bug. Just because you can connect to the host *now*, when you
call check_udp, doesn't mean it will still respond two seconds later (or even
two milliseconds later) when you attempt to connect again.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
--
https://mail.python.org/mailman/listinfo/python-list
Read Firefox sqlite files with Python
I'm trying to dump a Firefox IndexDB sqlite file to text using Python 3.5.
import sqlite3
con = sqlite3.connect('foo.sqlite')
with open('dump.sql', 'w') as f:
for line in con.iterdump():
f.write(line + '\n')
The error I get is:
Traceback (most recent call last):
File "", line 2, in
File "/usr/local/lib/python3.5/sqlite3/dump.py", line 30, in _iterdump
schema_res = cu.execute(q)
sqlite3.DatabaseError: file is encrypted or is not a database
If I open the file in a hex editor, it starts with:
SQLite format 3
and although I can see a few human readable words, the bulk of the file looks
like noise.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
--
https://mail.python.org/mailman/listinfo/python-list
Aw: Try: Except: evaluates to True every time
Try in an interactive interpreter: python> "a string" is True Karsten > Gesendet: Samstag, 04. November 2017 um 16:31 Uhr > Von: "brandon wallace" > An: [email protected] > Betreff: Try: Except: evaluates to True every time > > > I have this code that tests a server to see if it is listening on port 123 > runs and evaluates to True every time. Even if the server does not exist but > it is not supposed to do that. I am getting no error message at all. What is > going on with this code? > > > > #!/usr/bin/env python > > import socket > > hostname = ["192.168.1.22", "192.168.1.23", "200.168.1.24", "19.0.0.0"] > port = 123 > > def check_udp(hosts, port_num): > '''Test the UDP port on a remove server.''' > s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > for host in hosts: > try: > s.connect((host, port_num)) > return "Port 53 is reachable on: %s" % host > except socket.error as e: > return "Error on connect: %s" % e > > check_udp(hostname, port) > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Read Firefox sqlite files with Python
Steve D'Aprano wrote:
> I'm trying to dump a Firefox IndexDB sqlite file to text using Python 3.5.
>
>
> import sqlite3
> con = sqlite3.connect('foo.sqlite')
> with open('dump.sql', 'w') as f:
> for line in con.iterdump():
> f.write(line + '\n')
>
>
> The error I get is:
>
> Traceback (most recent call last):
> File "", line 2, in
> File "/usr/local/lib/python3.5/sqlite3/dump.py", line 30, in _iterdump
> schema_res = cu.execute(q)
> sqlite3.DatabaseError: file is encrypted or is not a database
>
>
> If I open the file in a hex editor, it starts with:
>
> SQLite format 3
>
> and although I can see a few human readable words, the bulk of the file
> looks like noise.
I've seen that error message before:
https://mail.python.org/pipermail/tutor/2013-July/097022.html
--
https://mail.python.org/mailman/listinfo/python-list
Re: Try: Except: evaluates to True every time
On Sat, Nov 04, 2017 at 05:07:26PM +0100, Karsten Hilbert wrote: > Try in an interactive interpreter: > >python> "a string" is True Or, rather, python> if 'a string': print 'success' Sorry, Karsten -- GPG key ID E4071346 @ eu.pool.sks-keyservers.net E167 67FD A291 2BEA 73BD 4537 78B9 A9F9 E407 1346 -- https://mail.python.org/mailman/listinfo/python-list
Re: right list for SIGABRT python binary question ?
On Fri, Nov 03, 2017 at 07:31:56AM +0100, dieter wrote: > > I have posted backtraces taken from the address being > > watched. Does that help any at all ? > > Only in the case that the error is "local", i.e. detected > (quite) immediately. > > You might be in this case as you have observed that the address > is stable after library preload. Thus, it might not be a heap > address but one associated with one of the libraries. Such > a memory block should never be "freed". The backtrace would allow > you to determine the library affected. Obtain its source. Recompile > with symbols and try to find out where this memory block comes from. Dieter, thanks for taking the time to explain the general procedure. However, recompiling a library and trying to find out where given block of memory comes from is way beyond skills. I fear I have reached the end of what I can do. Karsten -- GPG key ID E4071346 @ eu.pool.sks-keyservers.net E167 67FD A291 2BEA 73BD 4537 78B9 A9F9 E407 1346 -- https://mail.python.org/mailman/listinfo/python-list
Re: [TSBOAPOOOWTDI]using names from modules
On 2017-11-04 19:42, Stefan Ram wrote: > What is better: > > ... > import math > ... > ... math.cos ... > ... > > or > > ... > from math import cos > ... > ... cos ... > ... > > ? > > (To me, the first is more readable, because at the site > where »math.cos« is used, it is made clear that »cos« > comes from math. If I'm doing trigonometric computations I think the *second* is *much* more readable. I'm using the well-known cosine function - that this was imported from the math module is pure noise. For other functions this may be less clear. I tend to use the first style more often, although that gets a bit verbose sometimes (os.path.join(os.path.dirname(...), ...)), And I do notice that the second style seems to be preferred in Django. > But I assume that the second might use > one less name lookup and therefore is faster. What is the > one way to do it?) I'm not worried about performance unless there is clear performance advantage (for real programs, not benchmarks). hp -- _ | Peter J. Holzer| Fluch der elektronischen Textverarbeitung: |_|_) || Man feilt solange an seinen Text um, bis | | | [email protected] | die Satzbestandteile des Satzes nicht mehr __/ | http://www.hjp.at/ | zusammenpaßt. -- Ralph Babel -- https://mail.python.org/mailman/listinfo/python-list
Looping on a list in json
Hi
I want to get a result from a largish json api. One section of the json
structure returns lists of data. I am wanting to get each resulting list
returned.
This is my code.
import json
from pprint import pprint
with open(r'/home/sayth/Projects/results/Canterbury_2017-01-20.json', 'rb') as
f, open('socks3.json','w') as outfile:
to_read = json.load(f)
print(to_read.keys())
# pprint(to_read)
meet = to_read["RaceDay"]["Meetings"]
meeting_id = to_read["RaceDay"]["Meetings"][0]
pprint(meeting_id.keys())
# result = meeting_id["Races"][1]["RacingFormGuide"]["Event"]["Runners"]
result = meeting_id["Races"]
#failing
for item in result:
pprint(["RacingFormGuide"]["Event"]["Runners"])
The key to the issue is that
result = meeting_id["Races"][0]["RacingFormGuide"]["Event"]["Runners"]
result = meeting_id["Races"][1]["RacingFormGuide"]["Event"]["Runners"]
result = meeting_id["Races"][2]["RacingFormGuide"]["Event"]["Runners"]
the numbers though in the above results could go from 0 to 10.
What is the best way to and return the data?
would just save meeting_id["Races"] to my result however there are a lot of
other junk dictionaries and lists I am filtering.
Cheers
Sayth
--
https://mail.python.org/mailman/listinfo/python-list
Re: Looping on a list in json
On 04Nov2017 14:01, Sayth Renshaw wrote:
I want to get a result from a largish json api. One section of the json
structure returns lists of data. I am wanting to get each resulting list
returned.
This is my code.
import json
from pprint import pprint
with open(r'/home/sayth/Projects/results/Canterbury_2017-01-20.json', 'rb') as
f, open('socks3.json','w') as outfile:
to_read = json.load(f)
[...]
meeting_id = to_read["RaceDay"]["Meetings"][0]
result = meeting_id["Races"]
#failing
for item in result:
pprint(["RacingFormGuide"]["Event"]["Runners"])
I'd just keep the interesting runners, along with their race numbers, in a
dict. The enumerate function is handy here. Something like (untested):
runner_lists = {}
for n, item in enumerate(result):
if this one is interested/not-filtered:
runner_lists[n] = result["RacingFormGuide"]["Event"]["Runners"]
and just return runner_lists. That way you know what the race numbers were for
each list of runners.
What is the best way to and return the data?
The basic idea is to make a small data structure of your own (just the
dictionary runner_lists in the example above) and fill it in with the
infomation you care about in a convenient and useful shape. Then just return
the data structure.
The actual data structure will depend on what you need to do with this later.
Cheers,
Cameron Simpson (formerly [email protected])
--
https://mail.python.org/mailman/listinfo/python-list
Re: [TSBOAPOOOWTDI]using names from modules
On 04Nov2017 20:59, Peter J. Holzer wrote:
On 2017-11-04 19:42, Stefan Ram wrote:
What is better:
...
import math
...
... math.cos ...
or
...
from math import cos
...
... cos ...
?
(To me, the first is more readable, because at the site
where »math.cos« is used, it is made clear that »cos«
comes from math.
If I'm doing trigonometric computations I think the *second* is *much*
more readable. I'm using the well-known cosine function - that this was
imported from the math module is pure noise.
For other functions this may be less clear. I tend to use the first
style more often, although that gets a bit verbose sometimes
(os.path.join(os.path.dirname(...), ...)), [...]
I think the same. If the function is well known and idstinctively named, just
use the short form ("cos(value)").
I also use the first style, but not often.
Regarding the less clear function names, particularly things like
"os.path.join", my os.path imports often look like this these days:
from os.path import dirname, exists as pathexists, isdir as pathisdir, join as
joinpath
This lets me use distinct but short names in the code. To take Peter's example:
joinpath(dirname(...), ...)
You can see I've given a distinctive name to "join", which would otherwise be
pretty vague.
Cheers,
Cameron Simpson (formerly [email protected])"
--
https://mail.python.org/mailman/listinfo/python-list
Re: Looping on a list in json
On Sunday, 5 November 2017 09:53:37 UTC+11, Cameron Simpson wrote:
> >I want to get a result from a largish json api. One section of the json
> >structure returns lists of data. I am wanting to get each resulting list
> >returned.
> >
> >This is my code.
> >import json
> >from pprint import pprint
> >
> >with open(r'/home/sayth/Projects/results/Canterbury_2017-01-20.json', 'rb')
> >as f, open('socks3.json','w') as outfile:
> >to_read = json.load(f)
> [...]
> >meeting_id = to_read["RaceDay"]["Meetings"][0]
> >result = meeting_id["Races"]
> >#failing
> >for item in result:
> >pprint(["RacingFormGuide"]["Event"]["Runners"])
>
> I'd just keep the interesting runners, along with their race numbers, in a
> dict. The enumerate function is handy here. Something like (untested):
>
> runner_lists = {}
> for n, item in enumerate(result):
> if this one is interested/not-filtered:
> runner_lists[n] = result["RacingFormGuide"]["Event"]["Runners"]
>
> and just return runner_lists. That way you know what the race numbers were
> for
> each list of runners.
>
> >What is the best way to and return the data?
>
> The basic idea is to make a small data structure of your own (just the
> dictionary runner_lists in the example above) and fill it in with the
> infomation you care about in a convenient and useful shape. Then just return
> the data structure.
>
> The actual data structure will depend on what you need to do with this later.
>
> Cheers,
Thank you. That does seem a good approach.
I was intending to merge other dictionary data from other dicts within the json
structure and that's where the trouble starts i guess trying to get too much
from json.
Thanks
Sayth
--
https://mail.python.org/mailman/listinfo/python-list
Re: Read Firefox sqlite files with Python
On Sunday, 5 November 2017 04:32:26 UTC+11, Steve D'Aprano wrote:
> I'm trying to dump a Firefox IndexDB sqlite file to text using Python 3.5.
>
>
> import sqlite3
> con = sqlite3.connect('foo.sqlite')
> with open('dump.sql', 'w') as f:
> for line in con.iterdump():
> f.write(line + '\n')
>
>
> The error I get is:
>
> Traceback (most recent call last):
> File "", line 2, in
> File "/usr/local/lib/python3.5/sqlite3/dump.py", line 30, in _iterdump
> schema_res = cu.execute(q)
> sqlite3.DatabaseError: file is encrypted or is not a database
>
>
> If I open the file in a hex editor, it starts with:
>
> SQLite format 3
>
> and although I can see a few human readable words, the bulk of the file looks
> like noise.
>
>
>
>
> --
> Steve
> “Cheer up,” they said, “things could be worse.” So I cheered up, and sure
> enough, things got worse.
https://stackoverflow.com/a/18601429
Version mismatch between sqlite CLI and python sqlite API? I created again my
db from the script instead of the CLI. Now insert and select work from the
script, but not from the CLI. $sqlite -version returns 2.8.17, while the python
version is 2.7.3.
Sayth
--
https://mail.python.org/mailman/listinfo/python-list
Re: Ideas about how software should behave
Jon Ribbens writes: > On 2017-11-04, Ben Finney wrote: > > To respond to the criticism of an idea – criticism containing no > > mention of the person – as though it “clearly refers to the > > [person]”, is of significant concern on a software dicussion forum > > such as this. > > No, the thing that is "of significant conern on a software discussion > forum such as this" is people such as yourself defending the abuse of > other contributors. I have defended no such thing, because there was no such abuse of any person in what you quoted. Ideas are not people, and ideas do not automatically deserve respect merely because some people hold those ideas. -- \ “Compulsory unification of opinion achieves only the unanimity | `\of the graveyard.” —Justice Roberts in 319 U.S. 624 (1943) | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Aw: Try: Except: evaluates to True every time
On Sun, 5 Nov 2017 03:07 am, Karsten Hilbert wrote: > Try in an interactive interpreter: > >python> "a string" is True Did you try that yourself? -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: Looping on a list in json
> I'd just keep the interesting runners, along with their race numbers, in a
> dict. The enumerate function is handy here. Something like (untested):
>
> runner_lists = {}
> for n, item in enumerate(result):
> if this one is interested/not-filtered:
> runner_lists[n] = result["RacingFormGuide"]["Event"]["Runners"]
>
> and just return runner_lists. That way you know what the race numbers were
> for
> each list of runners.
>
>
> Cheers,
> Cameron Simpson
The main issue is that enumerate doesn't enumerate on the lists when trying to
filter.
result = meeting_id["Races"]
so yes enumerating this works, showing just printing n and item.
runner_lists = {}
for n, item in enumerate(result):
# if this one is interested / not -filtered:
print(n, item)
0 {'FeatureRaceBonusActive': 'Disabled', 'FixedPriceSummary': {'FixedPrices':
[{'SportId': 8, 'LeagueId': 102, 'MeetingId': 1218, 'MainEventId': 650350,
'SubEventId': 3601361, 'Status': 'F', 'StatusDescription': 'FINALISED',
'BetTypeName': 'Win', 'EnablePlaceBetting': True}]}, 'RacingFormGuide':
{'Copyright': .
and so on it goes through the 7 items in this file.
but including
runner_lists = {}
for n, item in enumerate(result):
# if this one is interested / not -filtered:
print(n, item)
runner_lists[n] = result["RacingFormGuide"]["Event"]["Runners"]
## Produces
Traceback (most recent call last):
dict_keys(['RaceDay', 'ErrorInfo', 'Success'])
File "/home/sayth/PycharmProjects/ubet_api_mongo/parse_json.py", line 31, in
runner_lists[n] = result["RacingFormGuide"]["Event"]["Runners"]
TypeError: list indices must be integers or slices, not str
Cheers
Sayth
--
https://mail.python.org/mailman/listinfo/python-list
Re: Looping on a list in json
Sorry
figured it. Needed to use n to iterate when creating.
runner_lists = {}
for n, item in enumerate(result):
# if this one is interested / not -filtered:
print(n, item)
runner_lists[n] = result[n]["RacingFormGuide"]["Event"]["Runners"]
Sayth
--
https://mail.python.org/mailman/listinfo/python-list
Re: Looping on a list in json
On 04Nov2017 17:43, Sayth Renshaw wrote:
figured it. Needed to use n to iterate when creating.
Yeah, my mistake.
runner_lists = {}
for n, item in enumerate(result):
# if this one is interested / not -filtered:
print(n, item)
runner_lists[n] = result[n]["RacingFormGuide"]["Event"]["Runners"]
That's the beauty of offering untested code: I don't have to find and fix my
errors:-)
Cheers,
Cameron Simpson (formerly [email protected])
--
https://mail.python.org/mailman/listinfo/python-list
Re: [TSBOAPOOOWTDI]using names from modules
On 11/4/2017 3:42 PM, Stefan Ram wrote: What is better: ... import math ... ... math.cos ... ... or ... from math import cos ... ... cos ... ... ? (To me, the first is more readable, because at the site where »math.cos« is used, it is made clear that »cos« comes from math. But I assume that the second might use one less name lookup and therefore is faster. What is the one way to do it?) There is no 'one way', which is why there is more than one way. The first lets the reader know the source at each use site. The second lets the reader know what use is made of the source at the top. The advantage depends on how familiar the *reader* is with the source module and the functions therein. Is your question generic to any module and object, or specific to the math module? If generic, and mode is part of the package you are writing, then 'import mod' is less likely to create a circular import error. On the other hand, 'from mod import obj' is better for testing because it lets one mock obj in the importing module without touching the imported module (where the original may be internally needed in the same test). With idlelib, there are both circular import and testing issues. If importing a module is expensive in some way, then knowing that B only needs one or two 'cheap' items from A is needed may suggest a workaround or refactoring. For instance, move items from A to B and reverse the import between them. Replacing an existing 'from tkinter import *' with 'import tkinter' or 'import tkinter as tk' requires prefixing every existing reference to a tkinter object. Replacing the same with 'from tkinter import Tk, ...' requires list each object. The latter localizes the patch. Plus see the preceding paragraphs. In either case, complete enough test coverage is needed to make the change. I initially started with the 'as tk' replacement, but switched to the list version. A tkinter-specific reason was planning to switch from tk to ttk versions of widgets. Moving, for instance, 'Button' from the tkinter list to the tkinter.ttk list, instead of changing prefixes, would be both easy and make it obvious, at the top, that the change had been made, and for all Buttons. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: python3 byte decode
On 04Nov2017 01:47, Chris Angelico wrote: On Fri, Nov 3, 2017 at 8:24 PM, Ali Rıza KELEŞ wrote: Yesterday, while working with redis, i encountered a strange case. I want to ask why is the following `True` ``` "s" is b"s".decode() ``` while the followings are `False`? ``` "so" is b"so".decode() "som" is b"som".decode() "some" is b"some".decode() ``` Or vice versa? I read that `is` compares same objects, not values. So my question is why "s" and b"s".decode() are same objects, while the others aren't? My python version is 3.6.3. You shouldn't be comparing string objects with 'is'. Sometimes two equal strings will be identical, and sometimes they won't. All you're seeing is that the interpreter happened to notice and/or cache this particular lookup. To be more clear here, usually when humans say "identical" they mean having exactly the same value or attributes. Here, Chris means that the two strings are actually the same object rather than two equivalent objects. "is" tests the former (the same object). "==" is for testing the latter (the objects have the same value). For speed and memory reasons, Python notices small values of strings and ints, and allocates them only once. So When your write: a = "s" b = "s" Python will reuse the same str object for both. Because of this, not only is "a == b" (i.e. they have the same value) but also "a is b" (a and b refer to the same object). But this is not guarrenteed, and certainly for larger values Python doesn't bother. Eg: a = "ghghghghghg" b = "ghghghghghg" Here they will have the same value but be different objects. So "==" will still return True, but "is" would return False. You should usually be using "==" to compare things. "is" has its place, but it is usually not what you're after. In your example code, b"s".decode() returns the string value "s", and Python is internally deciding to reuse the existing "s" from the left half of your comparison. It can do this because strings are immutable. (For example, "+=" on a string makes a new string). Hoping this is now more clear, Cameron Simpson (formerly [email protected]) -- https://mail.python.org/mailman/listinfo/python-list
Re: [TSBOAPOOOWTDI]using names from modules
On Sun, 5 Nov 2017 06:42 am, Stefan Ram wrote: > What is the one way to do it? There is no philosophy of "one way to do it" in Python, that is a misunderstanding (possibly deliberate...) spread about by Perl users, to contrast Python from Perl's "more than one way to do it". The Zen of Python says: There should be one-- and preferably only one --obvious way to do it. The emphasis is on "obvious", not "one". There should be *at least* one, but preferably only one, OBVIOUS way to solve any problem. As for the question of importing names, the obvious way is to use a regular import: import math y = math.cos(x) which has the advantage of making it obvious where the name comes from, but the disadvantage that it is more to type and involves an extra name lookup at runtime, which is not free. But: - when performance matters - or the name is very well known - or you're only using a single name from the module (or at most a few) - especially if it repeats the module name (e.g. fractions.Fraction) it is acceptable to use the "from module import name" version: from math import cos y = cos(x) Which you use depends on the situation and personal taste. -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: Read Firefox sqlite files with Python
On Sun, 5 Nov 2017 04:32 am, Steve D'Aprano wrote:
> I'm trying to dump a Firefox IndexDB sqlite file to text using Python 3.5.
>
>
> import sqlite3
> con = sqlite3.connect('foo.sqlite')
> with open('dump.sql', 'w') as f:
> for line in con.iterdump():
> f.write(line + '\n')
Never mind. I dumped the file using the sqlite3 command line tool. Thank you
to all those who answered.
The file contains three INSERT statements, the first two don't have anything
of interest, and the third (which presumably contains all the data I'm trying
to recover) is an opaque 600+ KB blob.
Naturally. Why would you use a database as a database, when instead you could
just dump a big ball of mud into it?
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
--
https://mail.python.org/mailman/listinfo/python-list
Zen of Python “obvious way to do it” (was: [TSBOAPOOOWTDI]using names from modules)
Steve D'Aprano writes: > On Sun, 5 Nov 2017 06:42 am, Stefan Ram wrote: > > > What is the one way to do it? > > There is no philosophy of "one way to do it" in Python, that is a > misunderstanding (possibly deliberate...) spread about by Perl users, > to contrast Python from Perl's "more than one way to do it". > > The Zen of Python says: > > There should be one-- and preferably only one --obvious way to do it. > > > The emphasis is on "obvious", not "one". There should be *at least* > one, but preferably only one, OBVIOUS way to solve any problem. I think the confusion is quite understandable, and that the Zen was written quite consciously referencing the (at the time quite well-known) Perl princple “There's more than one way to do it”. Of course, “consciously referencing and contrasting with some well-known meme” is very close to “deliberately inviting confusion from those who don't examine the contrast closely enough”. So, I have given up trying to assign *blame* for that confusion. But from what I can tell it's a canard to say that the confusion is “spread about by Perl users”. On the contrary, in my experience, the confusion is also spread quite well by non-Perl-using, Python advocates. Heck, as someoone who works to *dispel* that confusion, I still find it difficult to place the emphasis correctly when rattling off that admonishment from the Zen. -- \“Perchance you who pronounce my sentence are in greater fear | `\ than I who receive it.” —Giordano Bruno, burned at the stake by | _o__) the Catholic church for the heresy of heliocentrism, 1600-02-16 | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: replacing `else` with `then` in `for` and `try`
On Sat, 4 Nov 2017 04:44 am, Jon Ribbens wrote:
> On 2017-11-03, Steve D'Aprano wrote:
>> The for loop does not necessarily perform a search:
>>
>> count = 1
>> for obj in sequence:
>> if count > MAX_OBJECTS:
>> print("too many objects, halting")
>> break
>> process(obj)
>> else:
>> print("finished")
>>
>> According to your mental model, this code is... what? Illegal? Silly?
>> Impossible? A syntax error?
>
> That conforms to my model. It's searching for the condition
> 'count > MAX_OBJECTS'.
That's sounds to me that you are willing to call just about any test of a
condition inside a loop a "search". I don't think that's helpful. I think it
is mangling the word to the point it is meaningless.
How about a loop that exits at some random time? Is that a search?
for i in range(100, 0, -1):
if flip_coin() == 'Heads':
print("surprise!")
break
print("still running")
else:
print("countdown completed")
[...]
>> Your response to code that doesn't match your mental model is to say
>> that it is obviously wrong and probably buggy and should be made
>> into a syntax error if possible.
>
> No, it isn't. Try reading again what I actually wrote.
What you actually wrote, in various posts:
You have a 'for...else' with no 'break'. Like I said, that should
probably be a syntax error.
if what the 'for' clause is doing doesn't match the concept
of 'searching for a match' then it's obvious that you shouldn't
be using 'for...else' in the first place.
the language doesn't currently strictly enforce the requirement
for a 'break', but nevertheless if you don't have one you almost
certainly have a bug.
I stand by my comment as an accurate description of your response.
>> Ah yes, because it is inconceivable that anyone might have thought of a use
>> for for...else without a break.
>
> It's not inconceivable, but nobody has thought of a sensible use so far
> (by which I mean one that shows it's a useful feature).
I find the code useful. I shouldn't have to justify why it is useful to me,
but for the record it especially comes in handy when I've already typed out a
multi-line loop in the REPL, and only then realised that I'll need some way
to add an extra line at the end. Since I spend a lot of time in the REPL
doing exploratory coding, this happens more often than I'd like.
Of course I could cancel the edit, then add in some sort of scaffolding code
to allow me to print an extra line at the end, then hit the up arrow
repeatedly to re-enter the lines I've already typed, editing them to fit the
scaffolding, then add the final print.
But that's tedious and painful and a waste of time and effort when it is
trivially easy to just add "else: print()". That is *simple* and it *works*
and it solves the problem.
And yes, a better REPL would also solve that problem. But I have to use the
REPL that exists, not the imaginary one that I'd like. If you want to call
this a hackish work around for a limitation of the REPL, I'll say... okay.
What's your point? It is still useful.
Try thinking outside the box. There's nothing wrong with finding unusual and
hackish uses for flow control statements.
[...]
>>> It's an incredibly obscure work-around for a different problem,
>>
>> You mean a different problem to "searching"? Yes indeed it is.
>
> No, I mean a problem that has nothing to do with 'for...else' clauses.
I would say that it has nothing to do with the original motivation for
introducing for...else clauses into the language. Since it uses for...else,
it is pretty obtuse to deny that it has anything to do with for...else.
The for...else control statement is a tool. We can use tools for any purpose
we want, not just the ones that they were originally designed for. You are
declaring that a perfectly useful, albeit hackish, trick for the REPL is
illegitimate because it doesn't match your mental model.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
--
https://mail.python.org/mailman/listinfo/python-list
Specialization for learning python from university of Michigan school of information
https://youtu.be/eblAxa5iO24. The video is just an introduction for a course on https://studyscienceblog.wordpress.com/2017/10/28/university-of-mitchigan-s-courses -- https://mail.python.org/mailman/listinfo/python-list
Re: Looping on a list in json
no doubt tho after playing with this is that enumerate value ends up in the
output which is a dictionary. The enumerate has no key which makes it invalid
json if dumped.
Not massive issue but getting the effect of enumerate without polluting output
would be the winner.
>runner_lists = {}
>for n, item in enumerate(result):
># if this one is interested / not -filtered:
>print(n, item)
>runner_lists[n] = result[n]["RacingFormGuide"]["Event"]["Runners"]
Sayth
--
https://mail.python.org/mailman/listinfo/python-list
