Re: [FAQ] "Best" GUI toolkit for python

2016-10-20 Thread Terry Reedy

On 10/20/2016 2:02 AM, Paul Rubin wrote:

pozz  writes:

What can I do and what *can't* I do with Tkinter?



I look at the very carefully tuned and sometimes animated UI's in fancy
desktop applications like Gimp and don't see a way to do similar things
in Tkinter.


Since I have not seen Gimp, I don't know what 'similar things' consist of.

However, one does animation (timed changes in some configuration 
attribute of a widget or widget item) with chained .after(milliseconds, 
function, *args) callbacks.



Tkinter is ok for simple basic GUIs with text labels,
buttons, an event loop that lets you catch mouse clicks, etc.  Gimp uses
Gtk (I think) and does all kinds of fancy effects that seem difficult
with tkinter, though now that I think about it, they might be doable
with enough effort.


I have done simple animations (movement, color and size changes) for 
either my own learning or to answer StackOverflow questions.  Others 
have also posted demonstration code.  Search '[tkinter] animation', for 
example.


Tk and tkinter do not come with animation functions or classes per se. 
However, Python does have the turtle module, which animates canvas items.

> python -m turtle # runs a demo and test
> python -m turtledemo # front end for about 20 animation demos.
There may also be modules available in PyPI.

If I were doing many animations, I would write functions or classes such 
as (writing this for the first time)

animate_ramp(widget, option, milliseconds, steps, end_value)
animate_flip(widget, option, milliseconds, steps, alt_value)
If these were functions, they would be closures defining an inner 
function passed as the .after callback.


The first would linearly interpolate between start_value and end_value. 
The second would flip back and forth.  Possible enhancements: recognize 
option 'xy' to mean x,y position and interpolate both together.  Allow 
milliseconds to be a list of ints so that time steps do not have to be 
uniform.  For ramp, allow steps and end_values to both be lists (of 
equal length) so one call can interpolate multiple segments of a path. 
Allow alt_value to be a list that is cycled through.  Steps == None 
means run forever.


Terry Jan Reedy


--
https://mail.python.org/mailman/listinfo/python-list


Re: [FAQ] "Best" GUI toolkit for python

2016-10-20 Thread Mark Summerfield
On Wednesday, October 19, 2016 at 7:18:28 PM UTC+1, Demosthenes Koptsis wrote:
> I thought PyQt was supported by Qt company...
> 
> There is also an official book by Prentice Hall:
> 
> Rapid GUI Programming with Python and Qt (Prentice Hall Open Source 
> Software Development)
> 
> https://www.amazon.com/Programming-Python-Prentice-Software-Development/dp/0132354187/ref=sr_1_1?ie=UTF8&qid=1476901015&sr=8-1&keywords=rapid+qt+python
> 
> Inside the book the apps are been developed in PyQt
> 
> Regards,
> Dim
> 
> On 10/19/2016 03:49 PM, Mark Summerfield wrote:
> > On Tuesday, October 18, 2016 at 9:09:46 PM UTC+1, Demosthenes Koptsis wrote:
> >> My favorite GUIs are PyQt and wxPython.
> >>
> >> I prefer PyQt than PySide because PySide seem to me like an abandoned
> >> project.
> > [snip]
> >
> > It does seem that PySide 1 isn't making any visible progress.
> >
> > However, PySide 2 for Qt 5 is indeed progressing, and is being funded by 
> > The Qt Company: https://wiki.qt.io/PySide2

I wrote that book and it was 'official' in the sense that PyQt's creator & 
maintainer Phil Thompson did technical review & helped. However, PyQt has never 
been an official Qt product (not Trolltech, nor Nokia, nor The Qt Company); in 
fact Trolltech never even approved of PyQt.

The only official Qt bindings for Python will be PySide2. PySide1 was funded by 
Nokia and so that was also official, but that funding stopped and so I guess 
PySide1 is in limbo. (However, it works well and I use it for both personal and 
commercial projects.)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python-based monads essay part 2

2016-10-20 Thread Steven D'Aprano
On Thursday 20 October 2016 04:57, Chris Angelico wrote:

> Short-circuiting depends only on what's known *prior* to that
> evaluation. Dead code elimination removes the notion of time:

Surely not. I understand "dead code" to mean the same as *unreachable* code: 
code which cannot be reached by any path through the program:

if False:
spam()  # dead code

not merely code that doesn't affect the return result:

x = spam()
x = 999

Calling spam is not dead code, even if the result is immediately thrown away!

In any case, whichever definition you use, for spam() to be dead code in the 
later example, it has to be known to have no side-effects.


> int(input("Enter something:")) * 0 + 5
> 
> This can simply return 5, because (barring an exception being thrown)
> the value entered cannot affect the result. Python does not do this.
> And any system that has optimization flags (PostgreSQL, Pike, etc),
> this would be marked "has side effects", and therefore is not
> considered dead code. But if you (maybe mistakenly) mark input() as a
> pure function, then yes, this could indeed be optimized out.

*Assuming* that the compiler can distinguish between functions with side-
effects and those that aren't, and *assuming* that the compiler knows that 
input() returns something which can be cast to an int with no side-effects or 
errors, then in principle the compiler could optimize that to just 5.

But I don't think that's terribly likely, even for an aggressive optimizing 
compiler. Maybe C, because there's nothing so terrible I wouldn't believe about 
C compilers *wink*

This is not the best example, because its obvious that the call to int() might 
fail, and hence the effect of this code may be to raise ValueError. A better 
example would be:

len(input("Enter something:")) * 0 + 5


Assuming the compiler knows that len() and input() have their standard meaning, 
is it justified to optimized that expression to just 5? I don't think so, 
because the side effect of input() displaying text on the screen and waiting 
for the user to type something is the whole reason for the function to exist.

Regardless of whether your language is imperative, or functional with monads, I 
think that expression has to write text to the screen and wait for the user to 
type something, or the compiler is buggy. But it doesn't have to happen 
straight away! Consider:

L = [0, 1, 2, 3, 4, len(input("A")) * 0 + 5, 6]
print("B")
print(L[5])

Does this program print "A B 5", or "B A 5"? In Python, it prints "A" first, 
but that may not be the case for all languages. My guess is that, like 
declarative, asynchronous, concurrent and parallel programming (did I miss any 
buzzwords?), functional programming doesn't guarantee the order in which code 
is executed.

Actually, neither does imperative programming, if the language supports "call 
by name" or similar parameter passing mechanisms:


def call_by_name(x):
print("B")
print(x)

call_by_name(len(input("A")) * 0 + 5)


If x is a thunk, then this too will print "B" first.


>> However, if we think of the I/O interaction (aka *the process*) to be
>> the return value of a function, every bead in the I/O chain counts.
> 
> And that's what I mean about making function purity meaningless. Here,
> look - this is a pure function!
> 
> magic_numbers = [1, 2, 4, 8]
> def do_magic(x):
> magic_numbers[x % 4] += x / 4
> return magic_numbers[(x + 1) % 4]
> 
> Since the previous state of magic_numbers can be considered an input,
> and the new state can be considered an output, this is a pure
> function! Right?

No, but you know that :-)

Inputs are explicitly arguments to the function, not external state. Here's how 
we can turn that into real input:

def do_magic(state, x):
state = calculate_new_state(state)  # work it out for yourself *wink*
value = state[(x + 1) % 4]
return state, value

and then use a monad to make the state invisible, so that you actually only 
need to call do_magic(x).

I'm hand-waving here because I don't remember all the fine details from Greg's 
essay. Call it magic if you want, but the compiler can do it, because the 
details of how state is stored is invisible to the caller, the compiler is free 
to do the optimization:


change the functional but inefficient idiom 
state = calculate_new_state(state)
into the imperative but efficient idiom:
modify_in_place(state)


That's allowed, because (1) nobody and nothing except the do_magic() function 
can access the state; (2) the use of a monad makes this completely transparent 
and mathematically vigorous, which means the compiler can do it without human 
intervention; and (3) we want the program to run in less than a billion 
petabytes of memory. Practicality beats purity.

All joking aside, the whole point of functional programming is to avoid the 
human programmer having to track external state. It's not actually to avoid 
external state: given our existing hardware, such a thin

Re: Converting the keys of a dictionary from numeric to string

2016-10-20 Thread Peter Otten
pozz wrote:

> I have a dictionary where the keys are numbers:
> 
> mydict = { 1: 1000, 2: 1500, 3: 100 }
> 
> I would like to convert keys from number to string representation:
> 
> mydict = { "apples": 1000, "nuts": 1500, "tables": 100 }
> 
> Of course, somewhere I have the association between key-numbers and
> key-strings, maybe in another dictionary:
> 
> keydict = { 1: "apples", 2: "nuts", 3; "tables" }
> 
> How could I make the conversion? My solution:
> 
> keydict = { 1: "Joseph", 2: "Michael", 3: "John" }
> mydict = { 1: 1000, 2: 2000, 3: 3000 }
> newdict = {}
> for k in mydict.keys():
> newdict.update({keydict[k]: mydict[k]})
> print(newdict)

This is the correct approach. You can spell it more elegantly (see Paul's 
answer), but

> I tried changing just mydict (without creating newdict), without success.

changing such a dict in place is hardly ever done by experienced Python 
programmers.

assert len(keydict) == len(mydict)
for k, v in keydict.items():
mydict[v] = mydict.pop(k)

The code is less clear than

mydict = {keydict[k]: v for k, v in mydict.items()}

and you run the risk of ending up with corrupted data when you encounter a 
missing key halfway through the iteration.


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Converting the keys of a dictionary from numeric to string

2016-10-20 Thread Paul Rubin
Peter Otten <__pete...@web.de> writes:
> assert len(keydict) == len(mydict)

assert set(keydict) == set(mydict)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Converting the keys of a dictionary from numeric to string

2016-10-20 Thread Peter Otten
Paul Rubin wrote:

> Peter Otten <__pete...@web.de> writes:
>> assert len(keydict) == len(mydict)
> 
> assert set(keydict) == set(mydict)

The weaker check is O(1), and, combined with the succeeding for loop, 
implies the above.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Converting the keys of a dictionary from numeric to string

2016-10-20 Thread Peter Otten
Peter Otten wrote:

> Paul Rubin wrote:
> 
>> Peter Otten <__pete...@web.de> writes:
>>> assert len(keydict) == len(mydict)
>> 
>> assert set(keydict) == set(mydict)
> 
> The weaker check is O(1), and, combined with the succeeding for loop,
> implies the above.

Sorry, I have to take that back:

Python 3.6.0b1+ (3.6:5c92f9e0a8b1, Sep 13 2016, 14:44:51) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> keydict = { 1: "Joseph", "Joseph": "Michael", 3: "John" }
>>> mydict = { 1: 1000, 2: 2000, 3: 3000 }
>>> assert len(keydict) == len(mydict)
>>> assert set(keydict) == set(mydict)
Traceback (most recent call last):
  File "", line 1, in 
AssertionError
>>> for k, v in keydict.items():
... mydict[v] = mydict.pop(k)
... 
>>> print(mydict)
{2: 2000, 'Michael': 1000, 'John': 3000}


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Meta classes - real example

2016-10-20 Thread Mr. Wrobel

W dniu 18.10.2016 o 16:42, Ethan Furman pisze:

On 10/17/2016 11:44 PM, Mr. Wrobel wrote:


Ok,so in general, we could say that using Metclasses is ok for
manipulating __new__ but not that what is setting by __init__. Am I
right?


No and yes.

In this code (python 2 syntax):

#untested
class Wonderful(object):

__metaclass__ = SomeMetaClass
diamond = Sparkly(7)
club = 9

def display(self):
print "I'm an instance!"

The metaclass controls what happens when Wonderful is created:

- it can add the name 'diamond' to the Sparkly descriptor;
-  it can change/remove/add other attributes such as club, spade, or
whatever;
- it can wrap methods such as display to pre- or post-process calls to it
- etc.

Once the class (Wonderful, in this example) has been created:

- x = Wonderful()  # metaclass not called
- x.display()  # metaclass not called
- x.diamond# metaclass not called

- list(Wonderful)  # metaclass called (e.g. SomeMetaClass.__iter__(cls) )
   # where cls = Wonderful


Check out http://stackoverflow.com/a/35730545/208880 for a simple
demonstration of a metaclass.

--
~Ethan~

Thank you Ethan!
--
https://mail.python.org/mailman/listinfo/python-list


HTML templating tools

2016-10-20 Thread Tony van der Hoff
For a long time, under Python 2.7, I have been using htmltmpl to
generate htmjl pages programmatically from Python.

However, htmltmpl is not available for python3, and doesn't look as if
it ever will be. Can anyone recommend a suitable replacement (preferably
compatible with htmltmpl)?

Cheers, Tony

-- 
Tony van der Hoff  | mailto:t...@vanderhoff.org
Ariège, France |
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: HTML templating tools

2016-10-20 Thread Ben Finney
Tony van der Hoff  writes:

> However, htmltmpl is not available for python3, and doesn't look as if
> it ever will be. Can anyone recommend a suitable replacement (preferably
> compatible with htmltmpl)?

I don't know about compatibility with that tool (I've never heard of
it).

There are many good templating engines for Python 3, including two of
the most popular:

* Mako http://www.makotemplates.org/>
* Jinja http://jinja.pocoo.org/>

You can read about many more at the Python wiki
https://wiki.python.org/moin/Templating> though not, sadly, a
categorisation by Python 3 support.

-- 
 \   “Prayer must never be answered: if it is, it ceases to be |
  `\   prayer and becomes correspondence.” —Oscar Wilde, _The Epigrams |
_o__)of Oscar Wilde_, 1952 |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python-based monads essay part 2

2016-10-20 Thread Gregory Ewing

Chris Angelico wrote:

Okay. Now let's suppose that, instead of "73" in the first step, you
have "ask the user for an integer". Are you allowed to eliminate this
prompt, since the result of it cannot possibly affect anything?


That's an excellent question. The answer is no, you're
not allowed to eliminate it, and I'll try to explain why.

In Python, you're talking about something like this:

  def get_int():
  return int(input())

  print(0 * get_int())

But you can't write it that way in Haskell, because I/O
actions are not functions that return results. The Haskell
equivalent would be something like

  main =
  get_int >>= (\n ->
  print (0 * n))

Here's what happens. We've defined 'main' as a function that
returns an I/O instruction, "get an integer". That instruction
has a callback attached, namely the lambda expression
'\n -> print (0 * n)'.

The top level of the Haskell system sees this instruction,
carries it out, and then invokes the callback, passing the
number it got as an argument.

Inside the lambda, the number is bound to n. The lambda multiplies
it by 0 and then returns *another* I/O instruction, one that says
"print this number". The Haskell system carries out that instruction.
No further I/O instructions result, so the process is terminated.

Inside the lambda, the Haskell compiler is free to notice that
n is being multiplied by 0 and optimise it to just 'print 0'.
But the body of the lambda doesn't get evaluated until *after*
the "get integer" instruction has been carried out, and there is
no evaluation path that avoids that.

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python-based monads essay part 2

2016-10-20 Thread Gregory Ewing

Marko Rauhamaa wrote:


def main():
try:
guard_it()
except ValueError:
# I'm having none of it!
resume "CarryOn!"

The problem is, how can the file f unclose itself when work resumes?


The same thing could happen in Scheme, though. Re-entering a
context via a continuation doesn't magically reset everything
to the way it was at some earlier time. A data structure that
has been mutated will still be mutated, and a file that has
been closed will still be closed.

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


ANN: Python Meeting Düsseldorf - 26.10.2016

2016-10-20 Thread eGenix Team: M.-A. Lemburg
[This announcement is in German since it targets a local user group
 meeting in Düsseldorf, Germany]



ANKÜNDIGUNG

  Python Meeting Düsseldorf

   http://pyddf.de/

Ein Treffen von Python Enthusiasten und Interessierten
 in ungezwungener Atmosphäre.

   Mittwoch, 26.10.2016, 18:00 Uhr
   Raum 1, 2.OG im Bürgerhaus Stadtteilzentrum Bilk
 Düsseldorfer Arcaden, Bachstr. 145, 40217 Düsseldorf

Diese Nachricht ist auch online verfügbar:
http://www.egenix.com/company/news/Python-Meeting-Duesseldorf-2016-10-26


NEUIGKEITEN

 * Bereits angemeldete Vorträge:

   Charlie Clark
   "Testing mit Hypothesis"

   Tom Engemann
   "MicroPython auf dem ESP8266"

   Johannes Spielmann
   "PyCharm als Python IDE"

   Jochen Wersdörfer
   "CookieCutter"

   Matthias Endler
   "Visual Studio Code als Python IDE"

   Weitere Vorträge können gerne noch angemeldet werden: i...@pyddf.de

 * Startzeit und Ort:

   Wir treffen uns um 18:00 Uhr im Bürgerhaus in den Düsseldorfer
   Arcaden.

   Das Bürgerhaus teilt sich den Eingang mit dem Schwimmbad und
   befindet sich an der Seite der Tiefgarageneinfahrt der Düsseldorfer
   Arcaden.

   Über dem Eingang steht ein großes "Schwimm' in Bilk" Logo. Hinter
   der Tür direkt links zu den zwei Aufzügen, dann in den 2. Stock
   hochfahren. Der Eingang zum Raum 1 liegt direkt links, wenn man aus
   dem Aufzug kommt.

   Google Street View: http://bit.ly/11sCfiw



EINLEITUNG

Das Python Meeting Düsseldorf ist eine regelmäßige Veranstaltung in
Düsseldorf, die sich an Python Begeisterte aus der Region wendet:

 * http://pyddf.de/

Einen guten Überblick über die Vorträge bietet unser YouTube-Kanal,
auf dem wir die Vorträge nach den Meetings veröffentlichen:

 * http://www.youtube.com/pyddf/

Veranstaltet wird das Meeting von der eGenix.com GmbH, Langenfeld,
in Zusammenarbeit mit Clark Consulting & Research, Düsseldorf:

 * http://www.egenix.com/
 * http://www.clark-consulting.eu/



PROGRAMM

Das Python Meeting Düsseldorf nutzt eine Mischung aus Open Space
und Lightning Talks, wobei die Gewitter bei uns auch schon mal
20 Minuten dauern können ;-).

Lightning Talks können vorher angemeldet werden, oder auch spontan
während des Treffens eingebracht werden. Ein Beamer mit XGA Auflösung
steht zur Verfügung.

Lightning Talk Anmeldung bitte formlos per EMail an i...@pyddf.de



KOSTENBETEILIGUNG

Das Python Meeting Düsseldorf wird von Python Nutzern für Python
Nutzer veranstaltet. Um die Kosten zumindest teilweise zu
refinanzieren, bitten wir die Teilnehmer um einen Beitrag in Höhe von
EUR 10,00 inkl. 19% Mwst, Schüler und Studenten zahlen EUR 5,00
inkl. 19% Mwst.

Wir möchten alle Teilnehmer bitten, den Betrag in bar mitzubringen.



ANMELDUNG

Da wir nur für ca. 20 Personen Sitzplätze haben, möchten wir
bitten, sich per EMail anzumelden. Damit wird keine Verpflichtung
eingegangen. Es erleichtert uns allerdings die Planung.

Meeting Anmeldung bitte formlos per EMail an i...@pyddf.de



WEITERE INFORMATIONEN

Weitere Informationen finden Sie auf der Webseite des Meetings:

http://pyddf.de/

Mit freundlichen Grüßen,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Experts
>>> Python Projects, Coaching and Consulting ...  http://www.egenix.com/
>>> Python Database Interfaces ...   http://products.egenix.com/
>>> Plone/Zope Database Interfaces ...   http://zope.egenix.com/


: Try our mxODBC.Connect Python Database Interface for free ! ::

   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python-based monads essay part 2

2016-10-20 Thread Marko Rauhamaa
Gregory Ewing :

> Marko Rauhamaa wrote:
>
>> def main():
>> try:
>> guard_it()
>> except ValueError:
>> # I'm having none of it!
>> resume "CarryOn!"
>>
>> The problem is, how can the file f unclose itself when work resumes?
>
> The same thing could happen in Scheme, though. Re-entering a context
> via a continuation doesn't magically reset everything to the way it
> was at some earlier time. A data structure that has been mutated will
> still be mutated, and a file that has been closed will still be
> closed.

Obviously. However, Scheme continuations are (or can be) used to
implement all other single-threaded paradigms (coroutines, generators,
exceptions etc), so the execution context quite normally jumps around
"erratically". There is no automatic method to decide when final is
final.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: function call questions

2016-10-20 Thread chenyong20000
在 2016年10月20日星期四 UTC+8下午1:32:18,Frank Millman写道:
> wrote in message 
> news:5506e4d8-bd1d-4e56-8d1b-f71fa8293...@googlegroups.com...
> 
> 在 2016年10月19日星期三 UTC+8下午3:17:18,Peter Otten写道:
> > chenyong20...@gmail.com wrote:
> >
> > > 在 2016年10月19日星期三 UTC+8上午11:46:28,MRAB写道:
> > >> On 2016-10-19 03:15, chenyong20...@gmail.com wrote:
> > >> > Thanks Peter and Anssi for your kind help. Now I'm ok with the first
> > >> > question. But the second question still confused me. Why "it seems 
> > >> > that
> > >> > after root = root.setdefault(ch,{}) tree['a'] and root are the same
> > >> > object" and follows tree['a']['b']? Thanks.
> > >> >
> 
> > please forgive my stupid. I still can't follow this.
> 
> Let's see if I can explain. I am using 't' and 'r' instead of 'tree' and 
> 'root', but otherwise it is the same as your original example.
> 
> >>> t = {}
> >>> r = t
> >>> id(t)
> 2542235910088
> >>> id(r)
> 2542235910088
> 
> At this point, t and r are both references to the same empty dictionary.
> 
> >>> r = r.setdefault('a', {})
> 
> This has done two things.
> 
> It has inserted the key 'a' into the dictionary, and set its value to {}.
> 
> >>> t
> {'a': {}}
> >>> id(t)
> 2542235910088
> 
> It has also rebound 'r' so that it now references the new empty dictionary 
> that has been inserted.
> 
> >>> r
> {}
> >>> id(r)
> 2542234429896
> >>>t['a']
> {}
> >>> id(t['a'])
> 2542234429896
> 
> Now continue this process with r = r.setdefault('b', {}), and watch what 
> happens.
> 
> Hopefully this will help you to understand. Feel free to ask further if not 
> sure.
> 
> Frank Millman

Hi Frank,

thanks very much for your kind help. Your reply is clear. But I'm hindered by 
those you've not explained.

I'm always confused by "r = r.setdefault('a', {})". when the first loop 
finished, as what you have pointed out,
> >>> t
> {'a': {}}
> >>> r
> {}

Then next "r = r.setdefault('b', {})" will run again. Here what is "r" in 
"r.setdefault('b',{})"? According to final result, it should be "t['a']", which 
I can't understand. I thought the command is r.setdefault, so it should still 
be last "r", i.e., empty {}. Could you please let me know what I missed? 
thanks. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: function call questions

2016-10-20 Thread Frank Millman
wrote in message 
news:01cfd810-0561-40b1-a834-95a73dad6...@googlegroups.com...


在 2016年10月20日星期四 UTC+8下午1:32:18,Frank Millman写道:

wrote in message
news:5506e4d8-bd1d-4e56-8d1b-f71fa8293...@googlegroups.com...

> Let's see if I can explain. I am using 't' and 'r' instead of 'tree' and
> 'root', but otherwise it is the same as your original example.
>
> >>> t = {}
> >>> r = t
> >>> id(t)
> 2542235910088
> >>> id(r)
> 2542235910088
>
> At this point, t and r are both references to the same empty dictionary.
>
> >>> r = r.setdefault('a', {})
>
> This has done two things.
>
> It has inserted the key 'a' into the dictionary, and set its value to 
> {}.

>
> >>> t
> {'a': {}}
> >>> id(t)
> 2542235910088
>
> It has also rebound 'r' so that it now references the new empty 
> dictionary

> that has been inserted.
>
> >>> r
> {}
> >>> id(r)
> 2542234429896
> >>>t['a']
> {}
> >>> id(t['a'])
> 2542234429896
>
> Now continue this process with r = r.setdefault('b', {}), and watch what 
> happens.


thanks very much for your kind help. Your reply is clear. But I'm hindered 
by those you've not explained.


I'm always confused by "r = r.setdefault('a', {})". when the first loop 
finished, as what you have pointed out,

> >>> t
> {'a': {}}
> >>> r
> {}

Then next "r = r.setdefault('b', {})" will run again. Here what is "r" in 
"r.setdefault('b',{})"? According to final result, it should be "t['a']", 
which I can't understand. I thought the command is r.setdefault, so it 
should still be last "r", i.e., empty {}. Could you please let me know 
what I missed? thanks.


Firstly, I want to explain more clearly what I am doing here.

Instead of running your loop 3 times, I am running your command three times 
one step at a time (though I only showed the first one).



t = {}
r = t
r = r.setdefault('a', {})
r = r.setdefault('b', {})
r = r.setdefault('c', {})


This should give exactly the same result as your loop. The benefit of 
running it this way is that you can check the values after each step.


May I suggest that you do this, and try to understand the contents of 't' 
and 'r' at each point. If you are still unsure, let us know at which point 
the values are not what you expect, and I will try to explain further.


It is important that you understand that you are rebinding 'r' at each step, 
so after each command, 'r' is no  longer referencing the same object that it 
was referencing in the previous step.


To see the difference, try running it it this way -


t = {}
r = t
r.setdefault('a', {})
r.setdefault('b', {})
r.setdefault('c', {})


Hope this helps.

Frank


--
https://mail.python.org/mailman/listinfo/python-list


How to handle errors?

2016-10-20 Thread SS
The following script works fine:

#!/bin/python

import socket

str = raw_input("Enter a domain name: ");
print "Your domain is ", str
print socket.gethostbyname(str)

You provide it a hostname, it provides an IP.  That works fine.  But I need a 
way to handle errors.  For example:

[root@bart /]# ./dataman.py
Enter a domain name: aslfhafja
Your domain is  aslfhafja
Traceback (most recent call last):
  File "./dataman.py", line 7, in 
print socket.gethostbyname(str)
socket.gaierror: [Errno -2] Name or service not known
[root@bart /]#

I would like to be able to handle that error a bit better.  Any ideas?

TIA. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to handle errors?

2016-10-20 Thread John Gordon
In <8500044a-c8d1-43ad-91d9-e836d52bd...@googlegroups.com> SS 
 writes:

> I would like to be able to handle that error a bit better.  Any ideas?

Wrap the socket.gethostbyname() call in a try/except block.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Quick way to calculate lines of code/comments in a collection of Python scripts?

2016-10-20 Thread Brandon McCaig
(Sorry for the late reply)

On Wed, Oct 05, 2016 at 01:56:59PM -0400, Malcolm Greene wrote:
> Looking for a quick way to calculate lines of code/comments in a
> collection of Python scripts. This isn't a LOC per day per developer
> type analysis - I'm looking for a metric to quickly judge the complexity
> of a set of scripts I'm inheriting.

There is a CPAN module for a Perl application that calculates
SLOC. You or somebody else may find it useful for this task...

I believe it is packaged for some Linux distros. If applicable
you should be able to just install it:

sudo aptitude install cloc

Otherwise, if you have Perl installed already (e.g., *nix) and
already have a CPAN client [configured] it should be relatively
easy. cpanm is the most user-friendly client I've used.

cpanm App::cloc

Alternatively, you can do it with 'cpan' too, but that will
typically prompt you 3 million times... There are a few other
clients available. Use whatever suits you. You could also fetch
the module directly from CPAN and install it manually if so
inclined.

If you have none of these things (e.g., Windows) you could
install the free software Strawberry Perl distribution. It comes
with batteries included. If you're lucky cpanm will just work(tm)
to install it from there.

Hope that helps...

Regards,


-- 
Brandon McCaig  
Castopulence Software 
Blog 
perl -E '$_=q{V zrna gur orfg jvgu jung V fnl. }.
q{Vg qbrfa'\''g nyjnlf fbhaq gung jnl.};
tr/A-Ma-mN-Zn-z/N-Zn-zA-Ma-m/;say'



signature.asc
Description: Digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: HTML templating tools

2016-10-20 Thread Adrian Petrescu
On Thu, 20 Oct 2016 11:34:36 +0200, Tony van der Hoff wrote:

> Can anyone recommend a suitable replacement (preferably
> compatible with htmltmpl)?

I don't think anything is going to be compatible with htmltmpl, but Jinja2 
is a very widely-used, well-supported and easy-to-learn templating engine 
for Python: http://jinja.pocoo.org/docs/dev/

There's nothing specific to HTML about it, but that is its most common 
use case.
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: How to handle errors?

2016-10-20 Thread Joaquin Alzola
> [root@bart /]# ./dataman.py
>Enter a domain name: aslfhafja
>Your domain is  aslfhafja
>Traceback (most recent call last):
 > File "./dataman.py", line 7, in 
 >   print socket.gethostbyname(str)
>socket.gaierror: [Errno -2] Name or service not known
>[root@bart /]#

>I would like to be able to handle that error a bit better.  Any ideas?

Go with the "try  ... except ..."

https://docs.python.org/3/tutorial/errors.html
This email is confidential and may be subject to privilege. If you are not the 
intended recipient, please do not copy or disclose its content but contact the 
sender immediately upon receipt.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Quick way to calculate lines of code/comments in a collection of Python scripts?

2016-10-20 Thread John Strick
On Wednesday, October 5, 2016 at 12:57:14 PM UTC-5, Malcolm Greene wrote:
> Looking for a quick way to calculate lines of code/comments in a
> collection of Python scripts. This isn't a LOC per day per developer
> type analysis - I'm looking for a metric to quickly judge the complexity
> of a set of scripts I'm inheriting.
> 
> Thank you,
> Malcolm

pylint will report on lines of code, comments, blank lines, # of modules, 
functions, etc. It will also report long lines, non-standard object names, etc. 
I think it will answer some of your questions. 

https://www.pylint.org/

Just install and use:

 pylint *.py


Regards,
John
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to handle errors?

2016-10-20 Thread Steve D'Aprano
On Fri, 21 Oct 2016 06:48 am, SS wrote:

> The following script works fine:
> 
> #!/bin/python
> 
> import socket
> 
> str = raw_input("Enter a domain name: ");
> print "Your domain is ", str
> print socket.gethostbyname(str)
> 
> You provide it a hostname, it provides an IP.  That works fine.  But I
> need a way to handle errors.  For example:
[...]
> I would like to be able to handle that error a bit better.  Any ideas?

How do you want to handle the error? You can't just say "handle errors" --
you have to actually decide what do you want to do. If the user provides an
invalid hostname, what do you want to happen? If the network is down, what
do you want to happen?

Sometimes the best way to handle errors is not to handle them at all. If you
don't know what to do with a particular error condition, *don't* handle it.
Let it just go through to the user.




-- 
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: How to handle errors?

2016-10-20 Thread Wildman via Python-list
On Thu, 20 Oct 2016 12:48:28 -0700, SS wrote:

> The following script works fine:
> 
> #!/bin/python
> 
> import socket
> 
> str = raw_input("Enter a domain name: ");
> print "Your domain is ", str
> print socket.gethostbyname(str)
> 
> You provide it a hostname, it provides an IP.  That works fine.  But I need a 
> way to handle errors.  For example:
> 
> [root@bart /]# ./dataman.py
> Enter a domain name: aslfhafja
> Your domain is  aslfhafja
> Traceback (most recent call last):
>   File "./dataman.py", line 7, in 
> print socket.gethostbyname(str)
> socket.gaierror: [Errno -2] Name or service not known
> [root@bart /]#
> 
> I would like to be able to handle that error a bit better.  Any ideas?
> 
> TIA.

#!/usr/bin/env python

import socket

def get_ip(url):
try:
ip = socket.gethostbyname(url)
return ip
except socket.gaierror:
return "***ERROR***\nUnknown domain name!"

domain = raw_input("Enter a domain name: ");
print "Your domain is ", domain
print get_ip(domain)

-- 
 GNU/Linux user #557453
The cow died so I don't need your bull!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to handle errors?

2016-10-20 Thread Wildman via Python-list
On Thu, 20 Oct 2016 12:48:28 -0700, SS wrote:

> The following script works fine:
> 
> #!/bin/python

I meant to include this with my other post but I forgot it.

Using a direct path to the Python interpreter can cause problems
on some systems because it is not always installed to the same
directory.  On my Debian-based system Python is installed in
/usr/bin.  So your code as written will not run on my system.
A workaround for this is to use env in the shebang/hashbang.

For Python 2:  #!/usr/bin/env python

For Python 3:  #!/usr/bin/env python3

It will not matter where Python is installed.  'env' will always
know where it is.

-- 
 GNU/Linux user #557453
The cow died so I don't need your bull!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to handle errors?

2016-10-20 Thread D'Arcy Cain

On 2016-10-20 08:03 PM, Wildman via Python-list wrote:

Using a direct path to the Python interpreter can cause problems
on some systems because it is not always installed to the same
directory.  On my Debian-based system Python is installed in
/usr/bin.  So your code as written will not run on my system.
A workaround for this is to use env in the shebang/hashbang.

For Python 2:  #!/usr/bin/env python


Which would fail on my system because that's Python 3.5.


For Python 3:  #!/usr/bin/env python3

It will not matter where Python is installed.  'env' will always
know where it is.


Nothing is perfect.  I have just started linking /usr/bin/python* to 
wherever the actual one is on all my systems.  If I distribute something 
I expect the package manager on the target system to rewrite it as 
necessary.  I use NetBSD pkgsrc (which runs on many systems besides 
NetBSD) and it rewrites the HB line.


--
D'Arcy J.M. Cain
System Administrator, Vex.Net
http://www.Vex.Net/ IM:da...@vex.net
VoIP: sip:da...@vex.net
--
https://mail.python.org/mailman/listinfo/python-list


Re: List of modules available for import inside Python?

2016-10-20 Thread sorimdongja
On Thursday, August 28, 2008 at 1:12:04 AM UTC-5, Michele Simionato wrote:
> On Aug 28, 6:21 am, ssecorp  wrote:
> > Is there a way to view all the modules I have available for import
> > from within Python?
> > Like writing in the interpreter:
> 
> Try:
> 
> >>> help()
> help> modules
> Please wait a moment while I gather a list of all available modules...
> 

Finally, I have found it! Thanks a lot!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to handle errors?

2016-10-20 Thread Steve D'Aprano
On Fri, 21 Oct 2016 11:03 am, Wildman wrote:

> On Thu, 20 Oct 2016 12:48:28 -0700, SS wrote:
> 
>> The following script works fine:
>> 
>> #!/bin/python
> 
> I meant to include this with my other post but I forgot it.
> 
> Using a direct path to the Python interpreter can cause problems
> on some systems because it is not always installed to the same
> directory.

Then you change the path and fix it.


> On my Debian-based system Python is installed in 
> /usr/bin.  So your code as written will not run on my system.
> A workaround for this is to use env in the shebang/hashbang.

That's not a work-around. That's a bug waiting to happen.

One of the problems with of env is that it will use whatever python
executable appears first in the user's $PATH, regardless of whether it is
the right Python or not -- or even whether it is actually Python, or just
some random executable file called "python". For example, you might have
compiled your own experimental Python executable, and adjusted your PATH
environment variable to find it. Now your env scripts will use your
unstable, experimental Python interpreter instead of the system Python.

Another serious problem with using env in the hash-bang line is that you
cannot pass commandline options to the Python executable.

Using env in this way is a hack that happens to mostly work. Its arguably an
abuse of env, and its not as portable as people often think (not all older
Unix systems even have env).


> For Python 2:  #!/usr/bin/env python
> For Python 3:  #!/usr/bin/env python3
> 
> It will not matter where Python is installed.  'env' will always
> know where it is.

That's not correct: env only searches the PATH, so if your python is not in
the path, it won't be found. Here's env on my system with the default PATH:

[steve@ando ~]$ /usr/bin/env python -c "import sys; print(sys.version)"
2.4.3 (#1, Jan  9 2013, 06:49:54)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)]


But if I change the search path (or if I move the Python executable
somewhere off the path):

[steve@ando ~]$ PATH="/tmp" /usr/bin/env python -c "import sys;
print(sys.version)"
/usr/bin/env: python: No such file or directory


Even if env finds something called "python", you can't be sure that it is
the right version of Python, or even Python at all. All you know is that it
is something called "python" on the search path.




-- 
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