Re: Connection refused when tryign to run bottle/flask web framweworks

2018-08-19 Thread Miki Tebeka
If you're trying to access the machine from another machine, you need to change 
the host to '0.0.0.0'. 'localhost' is the internal interface.

On Sunday, August 19, 2018 at 10:36:25 PM UTC+3, Νίκος wrote:
> Hello,
> 
> i just installed bottle and flask web frameworks in my CentOS environment but 
> i canno get it working even with the simpleste xample. The coonection is 
> refused always.
> 
> from bottle import route, run, template
> 
> @route('/hello/')
> def index(name):
> return template('Hello {{name}}!', name=name)
> 
> run(host='localhost', port=8080)
> 
> 
> Any ideas as to why i cannot access it?
> I dont have sme firewall blocking the ports 8080 or 5000.
> 
> Thank you.

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


Re: Connection refused when tryign to run bottle/flask web framweworks

2018-08-19 Thread dieter
Νίκος  writes:
> i just installed bottle and flask web frameworks in my CentOS environment but 
> i canno get it working even with the simpleste xample. The coonection is 
> refused always.

"connection refused" is an indication that there is no (running)
server at the connection port.

Unlike simple web servers, more complex web frameworks are often not
started automatically at system startup (as they require complex
configuration to be meaningfully usable). Likely, this your
case: you likely need to explicitely start the server component.

> from bottle import route, run, template
>
> @route('/hello/')
> def index(name):
> return template('Hello {{name}}!', name=name)
>
> run(host='localhost', port=8080)

Likely, the code above is supposed to start the server component.
Ensure, that the start is successful (I typically use "lsof -i"
to find out whether a server is listening on the expected port).

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


Re: Python Information Form

2018-08-19 Thread dieter
Suman Mupparapu  writes:
> Working on a creating a small information form ..and encountering issues
> when trying to edit the details using Python Flask and MYSQL DB.
>
> Placed the code below for your reference. Please help to fix this issue.
> Let me know if you need any other details from my end.

You need to describe precisely which issues you have encountered.
And as this is a text only forum, images may not be available
for most of us (as already noted by someone else). This implies
that your description must be textual.

As a general note: to understand errors, the traceback information
is of great help. Python supports tracebacks for (uncaught) exceptions.
You might find such tracebacks potentially on the error page itself,
potentially in a log file (written by your Web application framework).
Not all errors are indicated by an exception -- thus, they may not
be a traceback in your specific case: ideally, the error recognizing
component should in this case provide an understandable error description.

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


Re: Writing bytes to stdout reverses the bytes

2018-08-19 Thread Chris Angelico
On Mon, Aug 20, 2018 at 12:01 PM, Grant Edwards
 wrote:
> On 2018-08-20, Ben Bacarisse  wrote:
>> Grant Edwards  writes:
>>
>>> On 2018-08-20, Steven D'Aprano  wrote:
 On Mon, 20 Aug 2018 00:31:35 +, Steven D'Aprano wrote:

> When I write bytes to stdout, why are they reversed?

 Answer: they aren't, use hexdump -C.
>>>
>>> One might think that dumping out bytes in the correct order ought to
>>> be the default format for hexdump.
>>
>> It is if you run it as hd.
>
> What do you mean "run it as hd"?
>
> I don't see any mention of it the hexdump manpage, and I don't have an
> "hd" in my path.  Some commands alter their behavior based on argv[0],
> so I created an alias named "hd" that points to hexdump, but that
> doesn't do anything any different than "hexdump":
>
> $ which hexdump
> /usr/bin/hexdump
>
> $ ls -l $(which hd)
> lrwxrwxrwx 1 grante users 16 Aug 19 21:00 /home/grante/bin/hd -> 
> /usr/bin/hexdump
>
> $ hd .bashrc | head -n2
> 000 2023 652f 6374 732f 656b 2f6c 622e 7361
> 010 7268 0a63 0a23 2023 6854 7369 6620 6c69
>
> $ hexdump .bashrc | head -n2
> 000 2023 652f 6374 732f 656b 2f6c 622e 7361
> 010 7268 0a63 0a23 2023 6854 7369 6620 6c69
>

Your system is different from mine, then.

rosuav@sikorsky:~$ ls -l $(which hd)
lrwxrwxrwx 1 root root 7 Apr 12  2017 /usr/bin/hd -> hexdump
rosuav@sikorsky:~$ ls -l $(which hexdump)
-rwxr-xr-x 1 root root 27248 Apr 12  2017 /usr/bin/hexdump

In 'man hexdump', the -C option says:
 -C  Canonical hex+ASCII display.  Display the input offset in hexa‐
 decimal, followed by sixteen space-separated, two column, hexa‐
 decimal bytes, followed by the same sixteen bytes in %_p format
 enclosed in ``|'' characters.

 Calling the command hd implies this option.

I'm on Debian GNU/Linux, and the 'hexdump' command comes from a
package called bsdmainutils. What are you on, and where is your
hexdump from?

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


Re: Writing bytes to stdout reverses the bytes

2018-08-19 Thread Grant Edwards
On 2018-08-20, Ben Bacarisse  wrote:
> Grant Edwards  writes:
>
>> On 2018-08-20, Steven D'Aprano  wrote:
>>> On Mon, 20 Aug 2018 00:31:35 +, Steven D'Aprano wrote:
>>>
 When I write bytes to stdout, why are they reversed?
>>>
>>> Answer: they aren't, use hexdump -C.
>>
>> One might think that dumping out bytes in the correct order ought to
>> be the default format for hexdump.
>
> It is if you run it as hd.

What do you mean "run it as hd"?

I don't see any mention of it the hexdump manpage, and I don't have an
"hd" in my path.  Some commands alter their behavior based on argv[0],
so I created an alias named "hd" that points to hexdump, but that
doesn't do anything any different than "hexdump":

$ which hexdump
/usr/bin/hexdump

$ ls -l $(which hd)
lrwxrwxrwx 1 grante users 16 Aug 19 21:00 /home/grante/bin/hd -> 
/usr/bin/hexdump

$ hd .bashrc | head -n2
000 2023 652f 6374 732f 656b 2f6c 622e 7361
010 7268 0a63 0a23 2023 6854 7369 6620 6c69

$ hexdump .bashrc | head -n2
000 2023 652f 6374 732f 656b 2f6c 622e 7361
010 7268 0a63 0a23 2023 6854 7369 6620 6c69



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


Re: Writing bytes to stdout reverses the bytes

2018-08-19 Thread Chris Angelico
On Mon, Aug 20, 2018 at 11:31 AM, Grant Edwards
 wrote:
> On 2018-08-20, Chris Angelico  wrote:
>> On Mon, Aug 20, 2018 at 11:12 AM, Grant Edwards
>> wrote:
>>> On 2018-08-20, Steven D'Aprano  wrote:
 On Mon, 20 Aug 2018 00:31:35 +, Steven D'Aprano wrote:

> When I write bytes to stdout, why are they reversed?

 Answer: they aren't, use hexdump -C.
>>>
>>> One might think that dumping out bytes in the correct order ought to
>>> be the default format for hexdump.  Dog only know why the actual
>>> default format was chosen.  If it was 16-bit values in _octal_ you
>>> could at least blame the PDP-11 heritage of Unix...
>>>
>>
>> It's dumping sixteen-bit units in correct order.
>
> I know.  What I don't understand is is why 16-bit units in hex is the
> default.  8-bits make sense.  32-bits makes sense.  16-bits in octal
> makes sense (at least to those of us who first used Unix on a PDP-11).
>

Ah, I see what you mean. TBH, I no longer am surprised at weird
command defaults; many of them carry long history and sometimes
arbitrariness, maintained forever for backward compatibility. In this
specific case, I just use 'hd' instead of 'hexdump' - the defaults are
more to my liking, and it's shorter to boot.

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


Re: Writing bytes to stdout reverses the bytes

2018-08-19 Thread Ben Bacarisse
Grant Edwards  writes:

> On 2018-08-20, Steven D'Aprano  wrote:
>> On Mon, 20 Aug 2018 00:31:35 +, Steven D'Aprano wrote:
>>
>>> When I write bytes to stdout, why are they reversed?
>>
>> Answer: they aren't, use hexdump -C.
>
> One might think that dumping out bytes in the correct order ought to
> be the default format for hexdump.

It is if you run it as hd.

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


Re: Writing bytes to stdout reverses the bytes

2018-08-19 Thread Grant Edwards
On 2018-08-20, Chris Angelico  wrote:
> On Mon, Aug 20, 2018 at 11:12 AM, Grant Edwards
> wrote:
>> On 2018-08-20, Steven D'Aprano  wrote:
>>> On Mon, 20 Aug 2018 00:31:35 +, Steven D'Aprano wrote:
>>>
 When I write bytes to stdout, why are they reversed?
>>>
>>> Answer: they aren't, use hexdump -C.
>>
>> One might think that dumping out bytes in the correct order ought to
>> be the default format for hexdump.  Dog only know why the actual
>> default format was chosen.  If it was 16-bit values in _octal_ you
>> could at least blame the PDP-11 heritage of Unix...
>>
>
> It's dumping sixteen-bit units in correct order.

I know.  What I don't understand is is why 16-bit units in hex is the
default.  8-bits make sense.  32-bits makes sense.  16-bits in octal
makes sense (at least to those of us who first used Unix on a PDP-11).

-- 
Grant



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


Re: Writing bytes to stdout reverses the bytes

2018-08-19 Thread Chris Angelico
On Mon, Aug 20, 2018 at 11:12 AM, Grant Edwards
 wrote:
> On 2018-08-20, Steven D'Aprano  wrote:
>> On Mon, 20 Aug 2018 00:31:35 +, Steven D'Aprano wrote:
>>
>>> When I write bytes to stdout, why are they reversed?
>>
>> Answer: they aren't, use hexdump -C.
>
> One might think that dumping out bytes in the correct order ought to
> be the default format for hexdump.  Dog only know why the actual
> default format was chosen.  If it was 16-bit values in _octal_ you
> could at least blame the PDP-11 heritage of Unix...
>

It's dumping sixteen-bit units in correct order.

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


Re: Writing bytes to stdout reverses the bytes

2018-08-19 Thread Grant Edwards
On 2018-08-20, Steven D'Aprano  wrote:
> On Mon, 20 Aug 2018 00:31:35 +, Steven D'Aprano wrote:
>
>> When I write bytes to stdout, why are they reversed?
>
> Answer: they aren't, use hexdump -C.

One might think that dumping out bytes in the correct order ought to
be the default format for hexdump.  Dog only know why the actual
default format was chosen.  If it was 16-bit values in _octal_ you
could at least blame the PDP-11 heritage of Unix...




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


Re: Writing bytes to stdout reverses the bytes

2018-08-19 Thread Steven D'Aprano
On Mon, 20 Aug 2018 00:31:35 +, Steven D'Aprano wrote:

> When I write bytes to stdout, why are they reversed?

Answer: they aren't, use hexdump -C.

Thanks to all replies!


-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson

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


Re: Writing bytes to stdout reverses the bytes

2018-08-19 Thread Cameron Simpson

On 20Aug2018 00:31, Steven D'Aprano  
wrote:

When I write bytes to stdout, why are they reversed?

[steve@ando ~]$ python2.7 -c "print('\xfd\x84\x04\x08')" | hexdump
000 84fd 0804 000a
005

[steve@ando ~]$ python3.5 -c "import sys; sys.stdout.buffer.write(b'\xfd
\x84\x04\x08\n')" | hexdump
000 84fd 0804 000a
005


They're not. Hexdump is presenting your bytes as little endian 2 byte words. So 
your leading 0xfd is the _low_ bytes of the 2 bytes word.


Try "od -c" instead.

Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: Writing bytes to stdout reverses the bytes

2018-08-19 Thread Chris Angelico
On Mon, Aug 20, 2018 at 10:31 AM, Steven D'Aprano
 wrote:
> When I write bytes to stdout, why are they reversed?
>
> [steve@ando ~]$ python2.7 -c "print('\xfd\x84\x04\x08')" | hexdump
> 000 84fd 0804 000a
> 005
>
> [steve@ando ~]$ python3.5 -c "import sys; sys.stdout.buffer.write(b'\xfd
> \x84\x04\x08\n')" | hexdump
> 000 84fd 0804 000a
> 005

They're not. They're being printed out as individual bytes, but then
the hexdump command is looking at little-endian sixteen-bit units. Try
the 'hd' command instead, or use 'hexdump -C'.

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


Re: Writing bytes to stdout reverses the bytes

2018-08-19 Thread Grant Edwards
On 2018-08-20, Steven D'Aprano  wrote:

> When I write bytes to stdout, why are they reversed?
>
> [steve@ando ~]$ python2.7 -c "print('\xfd\x84\x04\x08')" | hexdump
> 000 84fd 0804 000a
> 005

They aren't.  You're being fooled by the default output format of
hexdump.  By default, it displays data as 16-byte integers in
little-endian.  If you want to look at bytes, do this:

$ python2.7 -c "print('\xfd\x84\x04\x08')" | hexdump -C
  fd 84 04 08 0a|.|
0005


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


Re: How to multiply dictionary values with other values based on the dictionary's key?

2018-08-19 Thread Steven D'Aprano
On Sun, 19 Aug 2018 05:29:46 -0700, giannis.dafnomilis wrote:

> With your help I have arrived at this point: I have the dictionary
> varsdict (size 5) as below
>
> KeyTypeSize  Value
> FEq_(0,_0,_0,_0)   float11.0
> FEq_(0,_0,_1,_1)   float11.0 
> FEq_(0,_0,_2,_2)   float11.0 
> FEq_(0,_0,_3,_0)   float11.0 
> FEq_(0,_0,_4,_1)   float11.0

That's not a Python dict. It looks like some sort of table structure. How 
do you get this? (What menu command do you run, what buttons to you 
click, etc?) I'm guessing you are using an IDE ("Integrated Development 
Environment") like Anaconda or similar. Is that right?

Python dicts print something like this:

{'FEq_(0,_0,_4,_1)': , 'FEq_(0,_0,_3,_0)': }

If you run 

print(varsdict)

what does it show?






(I have limited time to respond at the moment, so apologies for the brief 
answers. Hopefully someone else will step in with some help too.)


-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson

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


Writing bytes to stdout reverses the bytes

2018-08-19 Thread Steven D'Aprano
When I write bytes to stdout, why are they reversed?

[steve@ando ~]$ python2.7 -c "print('\xfd\x84\x04\x08')" | hexdump
000 84fd 0804 000a
005

[steve@ando ~]$ python3.5 -c "import sys; sys.stdout.buffer.write(b'\xfd
\x84\x04\x08\n')" | hexdump
000 84fd 0804 000a
005




-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson

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


Re: Pylint false positives

2018-08-19 Thread Marko Rauhamaa
Chris Angelico :

> On Sun, Aug 19, 2018 at 11:54 PM, Marko Rauhamaa  wrote:
>>> 3) Every invocation of method() has to execute the class body, which
>>> takes time.
>>
>> That's what happens with every method invocation in Python regardless.
>
> No. You have to execute the *class body*. Every method invocation has
> to execute a function body. Yours includes a class definition.
> Remember: The 'class' statement is NOT a declaration. It is an
> executable statement.

Sorry, I was being imprecise.

Obviously, whenever you execute a def statement, you have to execute a
def statement. Similarly, whenever you execute a class statement, you
have to execute a class statement. And executing a class statement
involves certain chores. Intantiating an object involves a different set
of chores. And invoking a method involves yet another set of chores.

Some of these chores are heavier, some of them are lighter. But where I
have used Python, performance hasn't been a bottleneck. It it were, I'd
choose different approaches of implementation.

> Oh, even easier then. You don't need any of this locality. Which means
> the inner class is buying you a whole lot of nothing.

When I first ran into Java's anonymous inner classes, I wondered why
they hadn't simply introduced anonymous functions. In fact, the whole
debacle ended up in a schism where C# forked out of Java and introduced
delegates, which are a neat concept and should have been there in C++
from the get-go. In their arms race both C# and Java finally introduced
lambdas.

But now I'm thinking the original Java approach (anonymous inner
classes) is probably the most versatile of them all. A single function
rarely captures behavior. That's the job of an object with its multiple
methods. In in order to create an ad-hoc object in Python, you will need
an ad-hoc class.

> Hmm... so it's fine to create a class at run time, but it's not okay
> to define its methods at run time.

Yes.

> I'm seriously confused here as to what you gain by that. How is it of
> value to create a new class at run time, but to require that all its
> methods and attributes be hand-written in the source code, and thus
> completely fixed?

Not completely fixed because the methods of the inner class can refer to
the variables of the outer scope.


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


Re: Connection refused when tryign to run bottle/flask web framweworks

2018-08-19 Thread Ian Kelly
On Sun, Aug 19, 2018, 1:47 PM Νίκος  wrote:

> Hello,
>
> i just installed bottle and flask web frameworks in my CentOS environment
> but i canno get it working even with the simpleste xample. The coonection
> is refused always.
>
> from bottle import route, run, template
>
> @route('/hello/')
> def index(name):
> return template('Hello {{name}}!', name=name)
>
> run(host='localhost', port=8080)
>
>
> Any ideas as to why i cannot access it?
> I dont have sme firewall blocking the ports 8080 or 5000.
>

What would port 5000 have to do with it?

How are you trying to access the page?

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


Re: printing to stdout

2018-08-19 Thread Cameron Simpson

On 19Aug2018 15:09, richard lucassen  wrote:

On Sun, 19 Aug 2018 19:53:04 +1000
Cameron Simpson  wrote:
Although I do not understand what zip is doing exactly here (I presume
I switch to use pointers instead of the values),


Someone else has descibed zip tersely: it pairs it the elements of 2 lists. In 
fact it joins up matching elements of an arbitrary number of iterables. Here is 
a 3 iterable example:


   >>> zip( (1,2,3), (4,5,6), (7,8,9) )
   
   >>> list( zip( (1,2,3), (4,5,6), (7,8,9) ) )
   [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

See that is has collected the first element of each tuple, then the second and 
so forth?


In my sentence above, "iterable" means any object you can iterate over - any 
object you could use in a for-loop. So, obviously, a list as in your programme.  
And also a tuple like (1,2,3) as in the example above (a tuple is an 
unmodifiable list). ANd any number of other things that will yield a sequence 
of values.


In Python 3 (which you're using) zip returns a lazy object, which does the 
zipping as you request the values. That is why the example shows a base "zip()" 
returning a "zip object" - we hand it to list() to get an actual list of all 
the values. This is fast (instant return of the zip object without doing much 
work) and cheap in memory (no need to make a huge result if you're zipping big 
lists) and cheap in time (no need to make the whole result if you're only using 
the first part of it).


So, to the code using the zip:

 for device_nr, (pcf, pcf_value) in enumerate(zip(list_pcf, list_pcf_value)):

The inner zip yields (pcf, pcf_value) pairs from zipping list_pcf and 
list_pcf_value, an iterable of:


 (pcf[0], pcf-value[0]), (pcf[1], pcf_value[1]), ...

and you can write a for loop like this:

 for pcf, pcf_value in zip(list_pcf, list_pcf_value):

to deal with each of those pairs in turn.

However, since you also need the index (device_nr) in order to update 
list_pcf_value:


 list_pcf_value[device_nr] = output

we then hand the whole thing to enumerate:

 for device_nr, (pcf, pcf_value) in enumerate(zip(list_pcf, list_pcf_value)):

The enumerate does just what the previous one did, yields pairs of (index, 
value). Each value is a pair from the zip, so it yields:


 (0, (pcf[0], pcf-value[0])),
 (1, (pcf[1], pcf_value[1])),
 ...

and Python's tuple unpacking syntax is fairly generous, so you want write:

 device_nr, (pcf, pcf_value) = (0, (pcf[0], pcf-value[0]))

and you can stick that in the for loop, getting the syntax you're using in the 
programme:


 for device_nr, (pcf, pcf_value) in enumerate(zip(list_pcf, list_pcf_value)):


The code is now as follows:


Much nicer. A few tiny nit picks:


#!/usr/bin/env python3

import sys
from smbus import SMBus
from time import sleep
import RPi.GPIO as GPIO

list_pcf = [0x38, 0x39, 0x3a, 0x3b]
list_pcf_value = []


Just convention: you could call these pcfs and pcf_values and perhaps have more 
readable code. Using plural names kind of indicates that they're lists (or 
tuples or some other sequence of values) and reads more like prose.



# initialisation of the input devices:
print ("[INFO] initialisation input devices")


"print" is just a regular function. We tend not to put a space before the "(" 
with other functions, and print isn't special. You might have this trailing 
space left over from Python 2 (either your own or some example code), where 
print _wasn't_ a function. So:


 print("[INFO] initialisation input devices")


for pcf in list_pcf:
 try:
   bus.write_byte(pcf, 0xff) # set device to 0xff
 except IOError as e:
   print ("[ALERT] I/O problem device 0x%x (init): %s" % (pcf, e))
 output = bus.read_byte(pcf)


You presumably also want a try/except around the bus.read_byte. You could use a 
distinct try/except (rather wordy) or, since they're adjacent and your 
exception action is the same, just put them both inside the try/except.


The advice to keep things as small as possible within the try/except has to do 
with knowing exactly what kind of thing threw the exception. But they're both 
bus operations and handled the same - including both is reasonable.



 list_pcf_value.append(output) # append value to list
 print ("found pcf8574 at 0x%x, input value: 0x%x" % (pcf, output))
 sys.stdout.flush()
# GPIO 23 set up as input. It is pulled up to stop false signals
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
loopcntr = 0 # detects if INT is kept low

while True:
 if GPIO.input(23) == 1: # if still 0, another event has occurred
   GPIO.wait_for_edge(23, GPIO.FALLING)


Can the GPIO ops also raise IOErrors? Just wondering.

Cheers,
Cameron Simpson 

Stepwise Refinement n.  A sequence of kludges K, neither distinct or finite,
applied to a program P aimed at transforming it into the target program Q.
--
https://mail.python.org/mailman/listinfo/python-list


Re: printing to stdout

2018-08-19 Thread Chris Angelico
On Mon, Aug 20, 2018 at 7:55 AM, Cameron Simpson  wrote:
> Draw little boxes with arrows.  It helps.   - Michael J. Eager

Draw good boxes. - DeviCat

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


Re: printing to stdout

2018-08-19 Thread Cameron Simpson

On 19Aug2018 18:10, richard lucassen  wrote:

On Sun, 19 Aug 2018 10:11:08 -0400
Joel Goldstick  wrote:

Your allusion to pointers is misguided.  Python is not like C or
assembler.  You don't, and don't need to know where objects are
stored.  Names are assigned to reference data objects


I'll have another look at it, I was just searching for a clear
explanation, but the page I found was not clear enough for me. I'll
have to take some time for it...


If you think of references like C pointers you are 80% of the way there.

In CPython (the primary Python implementation, which you're using), a reference 
is effectively a pointer to the referenced Python object. _Internally_. And the 
result of the id() function (giving an object's identity) _happens_ to be a 
memory address.


But the language specification doesn't talk about pointers or memory addresses, 
and other implementations may use other abstractions to associate variables 
with the objects they reference.


So never talk about Python references as pointers. You'll cop noisy criticism!

Just think of them as arrows from a variable (or attributes, etc) to an object.

Every Python variable is a reference. So when you pass a variable to a function 
or use it in an expression, your putting a reference there. This:


 x = 3
 y = x

results in x and y referring to the same "3" int object. For ints this is 
pretty irrelevant, since they're immutable. Arithmetic works as you would 
expect.


But this:

 values = [1, 2, 3]
 values2 = values

Here, values and values 2 both refer to the same list - values2 does not have a 
copy. So:


 values2[1] = 4

means that values[1] and values2[1] are both 4 because it is the same list.

Cheers,
Cameron Simpson 

Draw little boxes with arrows.  It helps.   - Michael J. Eager
--
https://mail.python.org/mailman/listinfo/python-list


Connection refused when tryign to run bottle/flask web framweworks

2018-08-19 Thread Νίκος
Hello,

i just installed bottle and flask web frameworks in my CentOS environment but i 
canno get it working even with the simpleste xample. The coonection is refused 
always.

from bottle import route, run, template

@route('/hello/')
def index(name):
return template('Hello {{name}}!', name=name)

run(host='localhost', port=8080)


Any ideas as to why i cannot access it?
I dont have sme firewall blocking the ports 8080 or 5000.

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


Re: printing to stdout

2018-08-19 Thread Richard Lucassen
On Sun, 19 Aug 2018 12:37:18 -0400
Joel Goldstick  wrote:

> > I'll have another look at it, I was just searching for a clear
> > explanation, but the page I found was not clear enough for me. I'll
> > have to take some time for it...
> 
> try python.org tutorial, and search for terms like names, or name
> binding.  And also 'namespace'

I'll have to get used to the language and I think it's a nice language.
I just mucked about with the sqlite modules BTW. And it works :) 

-- 
Richard Lucassen
http://contact.xaq.nl/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: printing to stdout

2018-08-19 Thread Joel Goldstick
On Sun, Aug 19, 2018 at 12:16 PM Richard Lucassen
 wrote:
>
> On Sun, 19 Aug 2018 10:11:08 -0400
> Joel Goldstick  wrote:
>
> > > Well, apparently there were quite a lot of things that makes the
> > > code more readable I'd say. And even better. But it was indeed not
> > > very unPythony. OTOH, I'm not a programmer, otherwise I would have
> > > written this in C ;-)
> >
> > This strikes me as an odd conclusion.  Raspberry Pi places a strong
> > emphasis on python.  It certainly doesn't execute as fast as C can,
> > but it provides a conceptually higher level programming model.  There
> > is extremely good community support for python with Pi (a huge plus),
> > and the code is much more understandable.  It is faster to write code
> > with python, you can come back to it and understand it more readily at
> > some later time, as can others.  And it runs 'fast enough' .  So, no,
> > I don't think if you were a 'programmer' you would have used C to do
> > this project.  But others may be of a different persuation.
>
> You've got absolutely a point that Python seems to be largely supported
> for Rpi. But I'll tell you something else: I just started to use a
> Rpi ;-) I agree that python code is much more understandable than C.
>
> > You seemed to have snipped your question about zip function.  It takes
> > iterables (things like lists, tuples, dictionaries) as arguments and
> > pairs them together to form tuples.  Look it up.  Very useful.  As and
> > example, if you have list1 = (1,2,3), and list2 = (4,5,6,7) and zip
> > them you will get ((1,4), (2,5),(3,6)).  (It stops when the shortest
> > iterable is exhausted)
> >
> > Your allusion to pointers is misguided.  Python is not like C or
> > assembler.  You don't, and don't need to know where objects are
> > stored.  Names are assigned to reference data objects
>
> I'll have another look at it, I was just searching for a clear
> explanation, but the page I found was not clear enough for me. I'll
> have to take some time for it...

try python.org tutorial, and search for terms like names, or name
binding.  And also 'namespace'

> --
> Richard Lucassen
> http://contact.xaq.nl/
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python Information Form

2018-08-19 Thread MRAB

On 2018-08-19 15:41, Suman Mupparapu wrote:

Hi Team,

I am newbie to Python and glad to be part of the team. Sorry for starting
with a help.

Working on a creating a small information form ..and encountering issues
when trying to edit the details using Python Flask and MYSQL DB.

Placed the code below for your reference. Please help to fix this issue.
Let me know if you need any other details from my end.

1) HTML Page for the Form

Welcome






Name 
   

Email 
   
CRType 
 New
  Old
   



The Output of the page is as below




The Python Code to Save and Display results is as below

  From flask import Flask, render_template, request, redirect
from flask_mysqldb import MySQL
# from flask_table import Table, Col, LinkCol



app = Flask(__name__)

# Configure db
#db = yaml.load(open('db.yaml'))
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
#app.config['MYSQL_PASSWORD'] = 'P@$$w0rd'
app.config['MYSQL_DB'] = 'flaskapp'

mysql = MySQL(app)

@app.route('/', methods=['GET', 'POST'])
def index():
 if request.method == 'POST':
 # Fetch form data
 userDetails = request.form
 name = userDetails['name']
 email = userDetails['email']
 CRType = userDetails['CRType']
  #   CR_ID = userDetails['CR_ID']
 cur = mysql.connection.cursor()
   #  cur.execute("""INSERT INTO users(name, email, CRType)
VALUES(%s, %s, % )""",(name, email, CRType)
 cur.execute("""INSERT INTO users (name, email, CRType) VALUES
(%s, %s, %s)""", (name, email, CRType))
 mysql.connection.commit()
 cur.close()
 return redirect ('/results')
   #  return redirect('/results')
 return render_template('index.html')

@app.route('/results')
def results():
 cur = mysql.connection.cursor()
 resultValue = cur.execute("SELECT * from users")
 if resultValue > 0:
 userDetails = cur.fetchall()
 #edit = LinkCol('Edit', 'edit', url_kwargs=dict(id='CR_ID'))
 return render_template('results.html',userDetails=userDetails)

Results are displayed as below


If we click on the Edit for Example Row 1 .. the following data is displayed


When I click on Submit, the below error is displayed





Edit HTML Page and Python Code for Edit

h1>Welcome to Update Zone






CR_ID 
   
Name 
   

Email 
   
   
   



app.route('/Edit', methods=['GET', 'POST'])
def Edit():

 CR_ID = request.args.get('CR_ID')
 cur = mysql.connection.cursor()
 result = cur.execute("""SELECT CR_ID, name, email from users where
CR_ID = %s""",CR_ID)
 RV = cur.fetchall()
 cur.close()
 user = RV[0]
 return render_template('Edit.html',user=user)


Thanks in Advance.

I'm not seeing the results. Are you posting from Google Groups and 
including images?


Google Groups is merely a mirror to the actual python-list group. Images 
(and spam) are removed when they arrive at python-list, so only those 
who are on Google Groups will see them.

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


Re: printing to stdout

2018-08-19 Thread Richard Lucassen
On Sun, 19 Aug 2018 10:11:08 -0400
Joel Goldstick  wrote:

> > Well, apparently there were quite a lot of things that makes the
> > code more readable I'd say. And even better. But it was indeed not
> > very unPythony. OTOH, I'm not a programmer, otherwise I would have
> > written this in C ;-)
> 
> This strikes me as an odd conclusion.  Raspberry Pi places a strong
> emphasis on python.  It certainly doesn't execute as fast as C can,
> but it provides a conceptually higher level programming model.  There
> is extremely good community support for python with Pi (a huge plus),
> and the code is much more understandable.  It is faster to write code
> with python, you can come back to it and understand it more readily at
> some later time, as can others.  And it runs 'fast enough' .  So, no,
> I don't think if you were a 'programmer' you would have used C to do
> this project.  But others may be of a different persuation.

You've got absolutely a point that Python seems to be largely supported
for Rpi. But I'll tell you something else: I just started to use a
Rpi ;-) I agree that python code is much more understandable than C.
 
> You seemed to have snipped your question about zip function.  It takes
> iterables (things like lists, tuples, dictionaries) as arguments and
> pairs them together to form tuples.  Look it up.  Very useful.  As and
> example, if you have list1 = (1,2,3), and list2 = (4,5,6,7) and zip
> them you will get ((1,4), (2,5),(3,6)).  (It stops when the shortest
> iterable is exhausted)
> 
> Your allusion to pointers is misguided.  Python is not like C or
> assembler.  You don't, and don't need to know where objects are
> stored.  Names are assigned to reference data objects

I'll have another look at it, I was just searching for a clear
explanation, but the page I found was not clear enough for me. I'll
have to take some time for it...

-- 
Richard Lucassen
http://contact.xaq.nl/
-- 
https://mail.python.org/mailman/listinfo/python-list


Python Information Form

2018-08-19 Thread Suman Mupparapu
Hi Team,

I am newbie to Python and glad to be part of the team. Sorry for starting
with a help.

Working on a creating a small information form ..and encountering issues
when trying to edit the details using Python Flask and MYSQL DB.

Placed the code below for your reference. Please help to fix this issue.
Let me know if you need any other details from my end.

1) HTML Page for the Form

Welcome






Name 
  

Email 
  
CRType 
New
 Old
  



The Output of the page is as below




The Python Code to Save and Display results is as below

>From flask import Flask, render_template, request, redirect
from flask_mysqldb import MySQL
# from flask_table import Table, Col, LinkCol



app = Flask(__name__)

# Configure db
#db = yaml.load(open('db.yaml'))
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
#app.config['MYSQL_PASSWORD'] = 'P@$$w0rd'
app.config['MYSQL_DB'] = 'flaskapp'

mysql = MySQL(app)

@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# Fetch form data
userDetails = request.form
name = userDetails['name']
email = userDetails['email']
CRType = userDetails['CRType']
 #   CR_ID = userDetails['CR_ID']
cur = mysql.connection.cursor()
  #  cur.execute("""INSERT INTO users(name, email, CRType)
VALUES(%s, %s, % )""",(name, email, CRType)
cur.execute("""INSERT INTO users (name, email, CRType) VALUES
(%s, %s, %s)""", (name, email, CRType))
mysql.connection.commit()
cur.close()
return redirect ('/results')
  #  return redirect('/results')
return render_template('index.html')

@app.route('/results')
def results():
cur = mysql.connection.cursor()
resultValue = cur.execute("SELECT * from users")
if resultValue > 0:
userDetails = cur.fetchall()
#edit = LinkCol('Edit', 'edit', url_kwargs=dict(id='CR_ID'))
return render_template('results.html',userDetails=userDetails)

Results are displayed as below


If we click on the Edit for Example Row 1 .. the following data is displayed


When I click on Submit, the below error is displayed





Edit HTML Page and Python Code for Edit

h1>Welcome to Update Zone






CR_ID 
  
Name 
  

Email 
  
  
  



app.route('/Edit', methods=['GET', 'POST'])
def Edit():

CR_ID = request.args.get('CR_ID')
cur = mysql.connection.cursor()
result = cur.execute("""SELECT CR_ID, name, email from users where
CR_ID = %s""",CR_ID)
RV = cur.fetchall()
cur.close()
user = RV[0]
return render_template('Edit.html',user=user)


Thanks in Advance.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: printing to stdout

2018-08-19 Thread richard lucassen
On Sun, 19 Aug 2018 19:53:04 +1000
Cameron Simpson  wrote:

> There are always unPythonic bits. Even after you've cleaned them all
> up, since people will disagree about the finer points of Pythonicism
> there will be bits both over and under cleaned.

Although I do not understand what zip is doing exactly here (I presume
I switch to use pointers instead of the values), I like the
"enumerate" function, very handy :-) The code is now as
follows:

#!/usr/bin/env python3

import sys
from smbus import SMBus
from time import sleep
import RPi.GPIO as GPIO

list_pcf = [0x38, 0x39, 0x3a, 0x3b]
list_pcf_value = []
GPIO.setmode(GPIO.BCM)
bus = SMBus(1)

# initialisation of the input devices:
print ("[INFO] initialisation input devices")
for pcf in list_pcf:
  try:
bus.write_byte(pcf, 0xff) # set device to 0xff
  except IOError as e:
print ("[ALERT] I/O problem device 0x%x (init): %s" % (pcf, e))
  output = bus.read_byte(pcf)
  list_pcf_value.append(output) # append value to list
  print ("found pcf8574 at 0x%x, input value: 0x%x" % (pcf, output))
  sys.stdout.flush()

# GPIO 23 set up as input. It is pulled up to stop false signals
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
loopcntr = 0 # detects if INT is kept low

while True:
  if GPIO.input(23) == 1: # if still 0, another event has occurred
GPIO.wait_for_edge(23, GPIO.FALLING)

  while GPIO.input(23) == 0:
for device_nr, (pcf, pcf_value) in enumerate(zip(list_pcf, list_pcf_value)):
  try:
output = bus.read_byte(pcf)
  except IOError as e:
print ("[ALERT] I/O problem device 0x%x: %s" % (pcf, e))

  if output != pcf_value:
xor = pcf_value ^ output
for bit_pos in range(8):
  if xor & 0x1:
up_down = (output >> bit_pos) & 0x1
print ("pcf8574 0x%x bit %d: to %d" % (pcf,bit_pos,up_down))
# send decimal values to event script:
with open('/mnt/ramdisk/var/lib/ha/events.fifo', 'w') as fifo:
  print("%d %d %d" % (pcf,bit_pos,up_down), file=fifo)
  xor >>= 1
list_pcf_value[device_nr] = output

  if GPIO.input(23) == 1:
loopcntr = 0
break
  loopcntr += 1
  if loopcntr >=20:
print ('[ALERT] possible INT loop, disabling 10 seconds')
sys.stdout.flush()
sleep (10)

sys.stdout.flush()
GPIO.cleanup()

And it still works :-)

Thnx!

R.

-- 
richard lucassen
http://contact.xaq.nl/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New books by O’Reilly

2018-08-19 Thread Gene Heskett
On Saturday 18 August 2018 21:40:25 Larry Martell wrote:

> https://imgur.com/gallery/tW1lwEl

Larry;

Here, it loaded very slow and the central window is empty. Was there 
supposed to be content? Or is my firefox busted?

-- 
Cheers, Gene Heskett
--
"There are four boxes to be used in defense of liberty:
 soap, ballot, jury, and ammo. Please use in that order."
-Ed Howdershelt (Author)
Genes Web page 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pylint false positives

2018-08-19 Thread Chris Angelico
On Sun, Aug 19, 2018 at 11:54 PM, Marko Rauhamaa  wrote:
> Chris Angelico :
>> 2) You can't identify these objects as being of the same type (since
>> they're not).
>
> That's a feature, not a bug. Type membership checking goes against
> duck-typing.

Oh, so it would be better for Python if every integer object were an
instance of a unique type, all of them called "int"? Duck typing does
NOT mean "having lots of identical type objects". You can argue that
it's an insignificant flaw to have the duplicate types, but it's
certainly not a virtue.

>> 3) Every invocation of method() has to execute the class body, which
>> takes time.
>
> That's what happens with every method invocation in Python regardless.

No. You have to execute the *class body*. Every method invocation has
to execute a function body. Yours includes a class definition.
Remember: The 'class' statement is NOT a declaration. It is an
executable statement.

>> At the price of a very small amount of encapsulation, you can make it
>> actually an inner class:
>>
>> class Outer:
>> class Inner:
>> def __init__(self, outer):
>> self.spam = outer.quarantine
>>
>> def method(self):
>> return self.Inner(self)
>
> Sure, there are ways to avoid closures, but the expressive price is
> usually higher than the supposed performance gain.
>
>> Now all instances of Inner are actually instances of the same type.
>> It's still local to the class, just not local to that method.
>
> Locality to the class is usually not worth the trouble. It's good enough
> to have names local to the module.

Oh, even easier then. You don't need any of this locality. Which means
the inner class is buying you a whole lot of nothing.

>> None of this explains your aversion to creating functions in a loop at
>> class scope, while still being perfectly happy doing so at function
>> scope.
>
> It had to do with populating a namespace programmatically using strings
> as field/method names (which, generally, you shouldn't be doing).
> Defining functions and classes dynamically during runtime is perfectly
> ok.

Hmm... so it's fine to create a class at run time, but it's not okay
to define its methods at run time. I'm seriously confused here as to
what you gain by that. How is it of value to create a new class at run
time, but to require that all its methods and attributes be
hand-written in the source code, and thus completely fixed?

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


Re: printing to stdout

2018-08-19 Thread Joel Goldstick
On Sun, Aug 19, 2018 at 9:56 AM richard lucassen
 wrote:
>
> On Sun, 19 Aug 2018 12:02:51 +0300
> Marko Rauhamaa  wrote:
>
> > richard lucassen :
> > > As I'm new to Python, just this question: are there any unPythony
> > > things in this code?
> >
> > Your code looks neat.
>
> Well, apparently there were quite a lot of things that makes the code
> more readable I'd say. And even better. But it was indeed not very
> unPythony. OTOH, I'm not a programmer, otherwise I would have written
> this in C ;-)

This strikes me as an odd conclusion.  Raspberry Pi places a strong
emphasis on python.  It certainly doesn't execute as fast as C can,
but it provides a conceptually higher level programming model.  There
is extremely good community support for python with Pi (a huge plus),
and the code is much more understandable.  It is faster to write code
with python, you can come back to it and understand it more readily at
some later time, as can others.  And it runs 'fast enough' .  So, no,
I don't think if you were a 'programmer' you would have used C to do
this project.  But others may be of a different persuation.

>
> R.

You seemed to have snipped your question about zip function.  It takes
iterables (things like lists, tuples, dictionaries) as arguments and
pairs them together to form tuples.  Look it up.  Very useful.  As and
example, if you have list1 = (1,2,3), and list2 = (4,5,6,7) and zip
them you will get ((1,4), (2,5),(3,6)).  (It stops when the shortest
iterable is exhausted)

Your allusion to pointers is misguided.  Python is not like C or
assembler.  You don't, and don't need to know where objects are
stored.  Names are assigned to reference data objects
>
> --
> richard lucassen
> http://contact.xaq.nl/
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pylint false positives

2018-08-19 Thread Marko Rauhamaa
Chris Angelico :

> On Sun, Aug 19, 2018 at 10:28 PM, Marko Rauhamaa  wrote:
>> The most useful use of inner classes is something like this:
>>
>> class Outer:
>> def method(self):
>> outer = self
>>
>> class Inner:
>> def spam(self, a, b):
>> outer.quarantine(a, b)
>>
>> return Inner()
>
> That's pretty inefficient.

Hasn't become an issue for me.

> I'm not sure what you gain by having Inner be local to that method,

It's a practical way of implementing the state pattern (https://en.wikipedia.org/wiki/State_pattern>). Your outer object behaves
differently in different states, and the inner object encapsulates the
behavior differences.

Java listeners have for ever used the pattern to implement event
listeners: http://www.fredosaurus.com/notes-java/GUI/events/anonym
ous_listener.html>.

> but here's what you lose:
>
> 1) Each instance of Inner carries with it a large class object.

Again, that hasn't been an issue for me in practice.

> 2) You can't identify these objects as being of the same type (since
> they're not).

That's a feature, not a bug. Type membership checking goes against
duck-typing.

> 3) Every invocation of method() has to execute the class body, which
> takes time.

That's what happens with every method invocation in Python regardless.

> At the price of a very small amount of encapsulation, you can make it
> actually an inner class:
>
> class Outer:
> class Inner:
> def __init__(self, outer):
> self.spam = outer.quarantine
>
> def method(self):
> return self.Inner(self)

Sure, there are ways to avoid closures, but the expressive price is
usually higher than the supposed performance gain.

> Now all instances of Inner are actually instances of the same type.
> It's still local to the class, just not local to that method.

Locality to the class is usually not worth the trouble. It's good enough
to have names local to the module.

> None of this explains your aversion to creating functions in a loop at
> class scope, while still being perfectly happy doing so at function
> scope.

It had to do with populating a namespace programmatically using strings
as field/method names (which, generally, you shouldn't be doing).
Defining functions and classes dynamically during runtime is perfectly
ok.


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


Re: printing to stdout

2018-08-19 Thread richard lucassen
On Sun, 19 Aug 2018 12:02:51 +0300
Marko Rauhamaa  wrote:

> richard lucassen :
> > As I'm new to Python, just this question: are there any unPythony
> > things in this code?
> 
> Your code looks neat.

Well, apparently there were quite a lot of things that makes the code
more readable I'd say. And even better. But it was indeed not very
unPythony. OTOH, I'm not a programmer, otherwise I would have written
this in C ;-)

R.

-- 
richard lucassen
http://contact.xaq.nl/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: printing to stdout

2018-08-19 Thread richard lucassen
On Sun, 19 Aug 2018 19:53:04 +1000
Cameron Simpson  wrote:

[Oops, apparently you set the Reply-To to python-list@python.org,
normally that's no problem, but I did something wrong somewhere]

> There are always unPythonic bits. Even after you've cleaned them all
> up, since people will disagree about the finer points of Pythonicism
> there will be bits both over and under cleaned.

Although I do not understand exactly what zip is doing here (I presume
I switch to use pointers instead of the values), I like the
"enumerate" function, very handy :-) The code is now as
follows:

#!/usr/bin/env python3

import sys
from smbus import SMBus
from time import sleep
import RPi.GPIO as GPIO

list_pcf = [0x38, 0x39, 0x3a, 0x3b]
list_pcf_value = []
GPIO.setmode(GPIO.BCM)
bus = SMBus(1)

# initialisation of the input devices:
print ("[INFO] initialisation input devices")
for pcf in list_pcf:
  try:
bus.write_byte(pcf, 0xff) # set device to 0xff
  except IOError as e:
print ("[ALERT] I/O problem device 0x%x (init): %s" % (pcf, e))
  output = bus.read_byte(pcf)
  list_pcf_value.append(output) # append value to list
  print ("found pcf8574 at 0x%x, input value: 0x%x" % (pcf, output))
  sys.stdout.flush()

# GPIO 23 set up as input. It is pulled up to stop false signals
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
loopcntr = 0 # detects if INT is kept low

while True:
  if GPIO.input(23) == 1: # if still 0, another event has occurred
GPIO.wait_for_edge(23, GPIO.FALLING)

  while GPIO.input(23) == 0:
for device_nr, (pcf, pcf_value) in enumerate(zip(list_pcf, list_pcf_value)):
  try:
output = bus.read_byte(pcf)
  except IOError as e:
print ("[ALERT] I/O problem device 0x%x: %s" % (pcf, e))

  if output != pcf_value:
xor = pcf_value ^ output
for bit_pos in range(8):
  if xor & 0x1:
up_down = (output >> bit_pos) & 0x1
print ("pcf8574 0x%x bit %d: to %d" % (pcf,bit_pos,up_down))
# send decimal values to event script:
with open('/mnt/ramdisk/var/lib/ha/events.fifo', 'w') as fifo:
  print("%d %d %d" % (pcf,bit_pos,up_down), file=fifo)
  xor >>= 1
list_pcf_value[device_nr] = output

  if GPIO.input(23) == 1:
loopcntr = 0
break
  loopcntr += 1
  if loopcntr >=20:
print ('[ALERT] possible INT loop, disabling 10 seconds')
sys.stdout.flush()
sleep (10)

sys.stdout.flush()
GPIO.cleanup()

And it still works :-)

Thnx!

R.


-- 
richard lucassen
http://contact.xaq.nl/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pylint false positives

2018-08-19 Thread Chris Angelico
On Sun, Aug 19, 2018 at 10:28 PM, Marko Rauhamaa  wrote:
> Steven D'Aprano :
>
>> On Sun, 19 Aug 2018 11:43:44 +0300, Marko Rauhamaa wrote:
>>> At least some of the methods of inner classes are closures (or there
>>> would be no point to an inner class).
>>
>> [...]
>>
>> (2) Whether or not the methods of an inner class are closures depends on
>> the methods, not the fact that it is an inner class. There are no
>> closures here:
>>
>> class Outer:
>> class Inner:
>>...
>>
>> no matter what methods Inner has. Nor is this a closure:
>>
>> class Outer:
>> def method(self):
>> class Inner:
>> def spam(self):
>> return self.eggs
>> return Inner
>
> The most useful use of inner classes is something like this:
>
> class Outer:
> def method(self):
> outer = self
>
> class Inner:
> def spam(self, a, b):
> outer.quarantine(a, b)
>
> return Inner()

That's pretty inefficient. I'm not sure what you gain by having Inner
be local to that method, but here's what you lose:

1) Each instance of Inner carries with it a large class object.
2) You can't identify these objects as being of the same type (since
they're not).
3) Every invocation of method() has to execute the class body, which takes time.

At the price of a very small amount of encapsulation, you can make it
actually an inner class:

class Outer:
class Inner:
def __init__(self, outer):
self.spam = outer.quarantine

def method(self):
return self.Inner(self)

Now all instances of Inner are actually instances of the same type.
It's still local to the class, just not local to that method.

None of this explains your aversion to creating functions in a loop at
class scope, while still being perfectly happy doing so at function
scope.

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


Re: Pylint false positives

2018-08-19 Thread Marko Rauhamaa
Steven D'Aprano :

> On Sun, 19 Aug 2018 11:43:44 +0300, Marko Rauhamaa wrote:
>> At least some of the methods of inner classes are closures (or there
>> would be no point to an inner class).
>
> [...]
>
> (2) Whether or not the methods of an inner class are closures depends on 
> the methods, not the fact that it is an inner class. There are no 
> closures here:
>
> class Outer:
> class Inner:
>...
>
> no matter what methods Inner has. Nor is this a closure:
>
> class Outer:
> def method(self):
> class Inner:
> def spam(self):
> return self.eggs
> return Inner

The most useful use of inner classes is something like this:

class Outer:
def method(self):
outer = self

class Inner:
def spam(self, a, b):
outer.quarantine(a, b)

return Inner()

> You made a vague comment about inner classes being equivalent to
> closures in some unknown fashion, but inner classes are not themselves
> closures, and the methods of inner classes are not necessarily
> closures.

I hope the above outline removes the vagueness.

 populating an object with fields (methods) in a loop is very rarely
 a good idea.
>>>
>>> Of course it is *rarely* a good idea
>> 
>> So no dispute then.
>
> Isn't there? Then why are you disagreeing with me about the
> exceptional cases where it *is* a good idea?

I don't know which statement of mine you are referring to exactly now.


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


Re: How to multiply dictionary values with other values based on the dictionary's key?

2018-08-19 Thread giannis . dafnomilis
On Sunday, August 19, 2018 at 1:42:29 PM UTC+2, Steven D'Aprano wrote:
> On Sun, 19 Aug 2018 03:15:32 -0700, giannis.dafnomilis wrote:
> 
> > Thank you MRAB!
> > 
> > Now I can get the corresponding dictionary value A[i,j,k,l] for each key
> > in the varsdict dictionary.
> > 
> > However how would I go about multiplying the value of each
> > FEq_(i,_j,_k,_l) key with the A[i,j,k,l] one? Do you have any insight in
> > that?
> 
> Do you want to modify the varsdict values in place?
> 
> varsdict['Feq_(i,_j,_k,_l)'] *= A[i,j,k,l]
> 
> which is a short-cut for this slightly longer version:
> 
> temp = varsdict['Feq_(i,_j,_k,_l)'] * A[i,j,k,l]
> varsdict['Feq_(i,_j,_k,_l)'] = temp
> 
> 
> 
> If you want to leave the original in place and do something else with the 
> result:
> 
> result = varsdict['Feq_(i,_j,_k,_l)'] * A[i,j,k,l]
> print(result)
> 



> Do you want to modify the varsdict values in place? 
> 
> varsdict['Feq_(i,_j,_k,_l)'] *= A[i,j,k,l] 
> 
> which is a short-cut for this slightly longer version: 
> 
> temp = varsdict['Feq_(i,_j,_k,_l)'] * A[i,j,k,l] 
> varsdict['Feq_(i,_j,_k,_l)'] = temp 
> 
> 
> 
> If you want to leave the original in place and do something else with the 
> result: 
> 
> result = varsdict['Feq_(i,_j,_k,_l)'] * A[i,j,k,l] 
> print(result) 
> 

Thanks again for your answers Steven. I will try to explain it simpler because 
I think I tend to complicate things. 

With your help I have arrived at this point: 
I have the dictionary varsdict (size 5) as below 
KeyTypeSize Value 
FEq_(0,_0,_0,_0)   float11.0 
FEq_(0,_0,_1,_1)   float11.0 
FEq_(0,_0,_2,_2)   float11.0 
FEq_(0,_0,_3,_0)   float11.0 
FEq_(0,_0,_4,_1)   float11.0 

and the dictionary B (size 150) as below 
KeyTypeSize Value 
FEq_(0,_0,_0,_0)   float11500.0 
FEq_(0,_0,_0,_1)   int  10 
... 
FEq_(0,_0,_1,_1)   float13300.0
... 
FEq_(0,_0,_2,_2)   float12200.0
...
FEq_(0,_0,_4,_1)   float14000.0

for dictionary B the i,j,k,l ranges run as far as my input ranges when I 
started the model. So now I only want to multiply the values with the same keys 
with each other and get the sum of it.

result = Sum(varsdict['FEq_(i,_j,_k,_l)']*B['FEq_(i,_j,_k,_l)']

As I mentioned above I have been trying this with 
{k : v * B[k] for k, v in varsdict.items() if k in B} 

or 

for key in varsdict: 
if key in B: 
print(int(varsdict[key]) * int(B[key])) 

but all I get is an empty dictionary. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to multiply dictionary values with other values based on the dictionary's key?

2018-08-19 Thread giannis . dafnomilis


> Do you want to modify the varsdict values in place?
> 
> varsdict['Feq_(i,_j,_k,_l)'] *= A[i,j,k,l]
> 
> which is a short-cut for this slightly longer version:
> 
> temp = varsdict['Feq_(i,_j,_k,_l)'] * A[i,j,k,l]
> varsdict['Feq_(i,_j,_k,_l)'] = temp
> 
> 
> 
> If you want to leave the original in place and do something else with the 
> result:
> 
> result = varsdict['Feq_(i,_j,_k,_l)'] * A[i,j,k,l]
> print(result)
> 

Thanks again for your answers Steven. I will try to explain it simpler because 
I think I tend to complicate things.

With your help I have arrived at this point:
I have the dictionary varsdict as below
KeyTypeSize Value 
FEq_(0,_0,_0,_0)   float11.0 
FEq_(0,_0,_1,_1)   float11.0 
FEq_(0,_0,_2,_2)   float11.0 
FEq_(0,_0,_3,_0)   float11.0 
FEq_(0,_0,_4,_1)   float11.0 

and the dictionary A as below
KeyTypeSize Value 
FEq_(0,_0,_0,_0)   float11500
FEq_(0,_0,_0,_1)   int10
... 
FEq_(0,_0,_1,_1)   float13300
... 
FEq_(0,_0,_2,_2)   float11.0 
FEq_(0,_0,_3,_0)   float11.0 
FEq_(0,_0,_4,_1)   float11.0 

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


Re: New books by O’Reilly

2018-08-19 Thread D'Arcy Cain
On 2018-08-18 09:40 PM, Larry Martell wrote:
> https://imgur.com/gallery/tW1lwEl

I think I have met the people who studied those books.

-- 
D'Arcy J.M. Cain
Vybe Networks Inc.
http://www.VybeNetworks.com/
IM:da...@vex.net VoIP: sip:da...@vybenetworks.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to multiply dictionary values with other values based on the dictionary's key?

2018-08-19 Thread Steven D'Aprano
On Sun, 19 Aug 2018 03:35:24 -0700, giannis.dafnomilis wrote:

> On Sunday, August 19, 2018 at 3:53:39 AM UTC+2, Steven D'Aprano wrote:
[...]

>> If you know absolutely for sure that the key format is ALWAYS going to
>> be 'FEq_()' then you can extract the fields using slicing, like
>> this:
>> 
>>   key = 'FEq_(0,_0,_2,_2)'
>>   fields = key[5, -1]  # cut from char 5 to 1 back from the end
[...]
>> - delete any underscores
>> - split it on commas
>> - convert each field to int
>> - convert the list of fields to a tuple
>> 
>>   fields = fields.replace('_', '')
>>   fields = string.split(',)
>>   fields = tuple([int(x) for x in fields])
>> 
>> 
>> and then you can use that tuple as the key for A.
> 
> When I try to this, I get the message 'fields = key[5, -1]. TypeError:
> string indices must be integers'.

Ouch! That was my fault, sorry, it was a typo. You need a colon, not a 
comma. Sorry about that!

Try this instead:

key = 'FEq_(0,_0,_2,_2)'
fields = key[5:-1]
fields = fields.replace('_', '')
fields = fields.split(',')
fields = tuple([int(x) for x in fields])
print(fields)


which this time I have tested.


(More comments later, time permitting.)


-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson

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


Re: How to multiply dictionary values with other values based on the dictionary's key?

2018-08-19 Thread Steven D'Aprano
On Sun, 19 Aug 2018 03:15:32 -0700, giannis.dafnomilis wrote:

> Thank you MRAB!
> 
> Now I can get the corresponding dictionary value A[i,j,k,l] for each key
> in the varsdict dictionary.
> 
> However how would I go about multiplying the value of each
> FEq_(i,_j,_k,_l) key with the A[i,j,k,l] one? Do you have any insight in
> that?

Do you want to modify the varsdict values in place?

varsdict['Feq_(i,_j,_k,_l)'] *= A[i,j,k,l]

which is a short-cut for this slightly longer version:

temp = varsdict['Feq_(i,_j,_k,_l)'] * A[i,j,k,l]
varsdict['Feq_(i,_j,_k,_l)'] = temp



If you want to leave the original in place and do something else with the 
result:

result = varsdict['Feq_(i,_j,_k,_l)'] * A[i,j,k,l]
print(result)




-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson

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


Re: Pylint false positives

2018-08-19 Thread Steven D'Aprano
On Sun, 19 Aug 2018 11:43:44 +0300, Marko Rauhamaa wrote:

> Steven D'Aprano :
> 
>> On Sun, 19 Aug 2018 00:11:30 +0300, Marko Rauhamaa wrote:
>>
>>> In Python programming, I mostly run into closures through inner
>>> classes (as in Java).
>>
>> Inner classes aren't closures.
> 
> At least some of the methods of inner classes are closures (or there
> would be no point to an inner class).

(1) Ironically, the only times I've used an inner class, its methods were 
not closures. So yes, there are sometimes uses for inner classes that 
don't include closures. There's an example in the argparse module in the 
standard library, and it too has no closures.

(2) Whether or not the methods of an inner class are closures depends on 
the methods, not the fact that it is an inner class. There are no 
closures here:

class Outer:
class Inner:
   ...

no matter what methods Inner has. Nor is this a closure:

class Outer:
def method(self):
class Inner:
def spam(self):
return self.eggs
return Inner


since the spam method doesn't close over any of the variables in method.

You made a vague comment about inner classes being equivalent to closures 
in some unknown fashion, but inner classes are not themselves closures, 
and the methods of inner classes are not necessarily closures.


>> Its also quite expensive to be populating your application with lots of
>> classes used only once each, which is a common pitfall when using inner
>> classes. Memory is cheap, but it's not so cheap that we ought to just
>> profligately waste it needlessly.
> 
> That is a completely separate question.

It wasn't a question, it was an observation.


> There's is no a-priori reason for inner classes to be wasteful;

Not in languages where classes are declared statically and built at 
compile-time, no.

But in a language like Python where classes are executable statements 
that are built at run time, like constructing any other mutable object, 
it is very easy to use them badly and waste memory.

This doesn't look harmful:

def func(x):
class Record:
def __init__(self, a):
self.a = a
return Record(x)

but it is.

You might not like that design, but it is part of Python's execution 
model and whether you like it or not you have to deal with the 
consequences :-)



> they
> have been part and parcel of Java programming from its early days, and
> Java is widely used for high-performance applications.

https://dirtsimple.org/2004/12/python-is-not-java.html



> CPython does use memory quite liberally. I don't mind that as
> expressivity beats performance in 99% of programming tasks.

Fair enough, but in the example I showed above, the practical effect is 
to increase the de facto size of the objects returned by func() twenty 
times. And fragment memory as well. In a long-lived application where you 
are calling func() a lot, and saving the objects, it all adds up.


>>> populating an object with fields (methods) in a loop is very rarely a
>>> good idea.
>>
>> Of course it is *rarely* a good idea
> 
> So no dispute then.

Isn't there? Then why are you disagreeing with me about the exceptional 
cases where it *is* a good idea?




-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson

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


Re: How to multiply dictionary values with other values based on the dictionary's key?

2018-08-19 Thread giannis . dafnomilis
On Sunday, August 19, 2018 at 3:53:39 AM UTC+2, Steven D'Aprano wrote:

> 
> Unless you edit your code with Photoshop, why do you think a JPEG is a 
> good idea?
> 
> That discriminates against the blind and visually impaired, who can use 
> screen-readers with text but can't easily read text inside images, and 
> those who have access to email but not imgur.

Thank you very much for the answer Steven! To be honest I did not think of 
that, I just assumed that it was easier for everyone to just look at the jpeg 
and see my dictionary. I will keep it in mind for the future.


> Sounds like you have to parse the key for the number fields:
> 
> - extract out the part between the parentheses '0,_0,_2,_2'
> 
> If you know absolutely for sure that the key format is ALWAYS going to be 
> 'FEq_()' then you can extract the fields using slicing, like this:
> 
>   key = 'FEq_(0,_0,_2,_2)'
>   fields = key[5, -1]  # cut from char 5 to 1 back from the end
> 
> If you're concerned about that "char 5" part, it isn't an error. Python 
> starts counting from 0, not 1, so char 1 is "E" not "F".
> 
> 
> 
> - delete any underscores
> - split it on commas
> - convert each field to int
> - convert the list of fields to a tuple
> 
>   fields = fields.replace('_', '')
>   fields = string.split(',)
>   fields = tuple([int(x) for x in fields])
> 
> 
> and then you can use that tuple as the key for A.

When I try to this, I get the message 'fields = key[5, -1]. TypeError: string 
indices must be integers'.

> It might be easier and/or faster to convert A to use string keys 
> "FEq_(0,_0,_2,_2)" instead. Or, depending on the size of A, simply make a 
> copy:
> 
> B = {}
> for (key, value) in A.items():
> B['FEq(%d,_%d,_%d,_%d)' % key] = value
> 
> 
> and then do your look ups in B rather than A.

This helped me a lot! Now I have 2 dictionaries that contain the same keys and 
the different values I want to multiply, varsdict and B. However if I try to 
multiply them using:

{k : v * varsdict[k] for k, v in B.items() if k in varsdict}

or

for key in varsdict:
if key in B:
print(int(varsdict[key]) * int(B[key]))

all I get is an empty dictionary. Do you know how to make this work?


> I don't see why the dictionary lookup won't work just because the indexes 
> aren't consistent. When you look up 
> 
> varsdict['FEq_(0,_0,_2,_2)']
> 
> it has no way of knowing whether or not 'FEq_(0,_0,_1,_2)' previously 
> existed. I think you need to explain more of what you are doing rather 
> than just dropping hints.
> 
> *Ah, the penny drops* ...
> 
> 
> Are you trying to generate the keys by using nested loops?
> 
> for i in range(1000):  # up to some maximum value
> for j in range(1000):
> for k in range(1000):
> for l in range(1000):
> key = "FEq_({0},_{1},_{2},_{3})".format(i,j,k,l)
> value = varsdict[key]  # this fails
> 
> 
> That's going to be spectacularly wasteful if the majority of keys don't 
> exist. Rather, you should just iterate over the ones that *do* exist:
> 
> for key in varsdict:
> ...

The varsdict dictionary was the result of the optimization run in PulP and 
contains the 'prob.variables()' keys and values. so while my initial problem 
variables were created for all i,j,k,l that I wanted, only the 5 appear in the 
optimization results. 

Now, however I want to multiply the result variables with external dictionary 
values that were also created for all the  i,j,k,l that I wanted. My B 
dictionary has a length of 150 but I only want the 5 values with the same keys 
as the varsdict dictionary to be multiplied with the values in the varsdict 
dictionary correspondigly.

For 5 key/value pairs I can do it manually but for a more complex problem with 
hundreds of key/value pairs it will be impossible so I am looking to automate 
that.

Sorry if that reads confusingly, I just started with python and I am trying to 
explain as clear as I can.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to multiply dictionary values with other values based on the dictionary's key?

2018-08-19 Thread giannis . dafnomilis
Thank you MRAB!

Now I can get the corresponding dictionary value A[i,j,k,l] for each key in the 
varsdict dictionary.

However how would I go about multiplying the value of each FEq_(i,_j,_k,_l) key 
with the A[i,j,k,l] one? Do you have any insight in that?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: printing to stdout

2018-08-19 Thread Cameron Simpson

On 19Aug2018 09:32, richard lucassen  wrote:

This is a working script I made. It initializes the I/O expanders, then
it waits for an INT from these I/O expanders on GPIO23, reads the
contents and sends which bit on which chip went up or down to a fifo
(and stdout for logging)

As I'm new to Python, just this question: are there any unPythony
things in this code?


There are always unPythonic bits. Even after you've cleaned them all up, since 
people will disagree about the finer points of Pythonicism there will be bits 
both over and under cleaned.



##

#!/usr/bin/env python3

list_pcf = [0x38, 0x39, 0x3a, 0x3b]
list_pcf_value = []

import sys
from smbus import SMBus
from time import sleep
import RPi.GPIO as GPIO


Imports should come before any other code.


GPIO.setmode(GPIO.BCM)
bus = SMBus(1)

# initialisation of the input devices:
print ("[INFO] initialisation input devices")
for i in range(len(list_pcf)):


This is better written as:

 for i, pcf in enumerate(list_pcf):

then you can replace every mention of "list_pcf[i] with "pcf" within the loop.

And in fact, since you're not using "i" for anything else you can just go:

 for pcf in list_pcf:


 try:
   bus.write_byte(list_pcf[i], 0xff) # set device to 0xff
   output = bus.read_byte(list_pcf[i])
   list_pcf_value.append(output) # append value to list
   print ("found: %d, input value: 0x%x" % (list_pcf[i], output))
 except IOError:


It is best to put try/except around the smallest possible piece of code. If 
there is an I/O error in the above you have no idea what caused it. Even the 
print() could emit one, and in that case your except clause's action will be 
misguided. Example:


 try:
   bus.write_byte(list_pcf[i], 0xff) # set device to 0xff
   output = bus.read_byte(list_pcf[i])
 except IOError as e:
   ...
 else:
   list_pcf_value.append(output) # append value to list
   print ("found: %d, input value: 0x%x" % (list_pcf[i], output))


   print ("[ALERT] I/O problem device 0x%x (init)" % pcf)


You should always include the exception itself in this kind of message, 
example:


  print ("[ALERT] I/O problem device 0x%x (init): %s" % (pcf, e))
 

 sys.stdout.flush()

# GPIO 23 set up as input. It is pulled up to stop false signals
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
loopcntr = 0 # detects if INT is kept low

while True:
 if GPIO.input(23) == 1: # if still 0, another event has occurred
   GPIO.wait_for_edge(23, GPIO.FALLING)
 print ('---')
 while GPIO.input(23) == 0:
   for i in range(len(list_pcf)):


You can write thos as:

 for i, (pcf, pcf_value) in enumerate(zip(list_pcf, list_pcf_value)):

and then just talk about "pcf" and "pcf_value" where you have "list_pcf[i]" and 
"list_pcf_value[i]". Then you just want the "i" when you update 
"list_pcf_value[i]". (Assigning to pcf_value won't affect that, so you need the 
index.)



 try:
   output = bus.read_byte(list_pcf[i])


Again, this try/except covers too much code. It should only cover bus I/O 
actions.



   if output != list_pcf_value[i]:
 xor = list_pcf_value[i] ^ output
 for l in range(8):


You might want a more meaningful name than "l", such as "bit_pos".


   if xor & 0x1:
 updown = (output >> l) & 0x1
 print ("%d bit %d: to %d" % (list_pcf[i],l,updown))
 print("%d %d %d" % (list_pcf[i],l,updown),
   file=open('/mnt/ramdisk/var/lib/ha/events.fifo', 'w'))


This print is better written:

 with open('/mnt/ramdisk/var/lib/ha/events.fifo', 'w') as fifo:
   print("%d %d %d" % (list_pcf[i],l,updown), file=fifo)

This ensures timely closing of the fifo when you exit the with suite.

Your "print(, file=open(...))" _will_ close the fifo in a timely fashion in 
CPython because the reference counting will trigger the file's delete action, 
but in other Python implementations the deletion may happen an arbitrarily 
large amount of time later (because they may garbage collect unreferenced 
objects differently).


Importantly, your print() won't get flushed to the fifo until the file closes, 
so timely closing is important. The with is reliable. And also the common 
idiom.



   xor = xor >> 1


You can write this:

 xor >>= 1


 list_pcf_value[i] = output
 except IOError:
   print ("[ALERT] I/O problem device 0x%x" % list_pcf[i])


And again, you should include the exception value in the message.


 if GPIO.input(23) == 1:
   loopcntr = 0
   break
 else:


You don't need this else, because the break will exit the loop.


   loopcntr += 1
   if loopcntr >=20:
 print ('[ALERT] possible INT loop, disable 10 seconds')
 sleep (10)
   sys.stdout.flush()


You need a flush before the sleep, otherwise the flush won't occur for 10 
seconds. Untimely.



GPIO.cleanup()


Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: printing to stdout

2018-08-19 Thread Marko Rauhamaa
richard lucassen :
> As I'm new to Python, just this question: are there any unPythony
> things in this code?

Your code looks neat.

>   except IOError:
> print ("[ALERT] I/O problem device 0x%x" % list_pcf[i])

Just double check that simply printing the alert is the correct recovery
from the exception. Should there be additional logic instead of the
fallthrough?


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


Re: Pylint false positives

2018-08-19 Thread Marko Rauhamaa
Chris Angelico :
> On Sun, Aug 19, 2018 at 9:03 AM, Marko Rauhamaa  wrote:
>> Chris Angelico :
>>
>>> *headscratch*
>>>
>>> So this is okay:
>>>
>>> def f():
>>> for i in range(5):
>>> def g(): ...
>>>
>>> But this isn't:
>>>
>>> class C:
>>> for i in range(5):
>>> def m(self): ...
>>>
>>> I've missed something here.
>>
>> No, you got it right.
>
> Then I've completely missed the problem. Why is one of them acceptable
> and the other not?

In the def-def case, you will do something mundane with g. For example,
you will register it as a callback.

In the class-def case, you are defining the method m five times in the
same namespace and overwriting all but one of the definitions, which
probably isn't what you are after.

In order to populate the class with methods of different names, you will
need to manipulate the namespace programmatically. If you find yourself
needing to do something like that, you need to take a couple of steps
back and ask yourself if there might be a more conventional way to solve
the problem at hand.


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


Re: Pylint false positives

2018-08-19 Thread Marko Rauhamaa
Steven D'Aprano :

> On Sun, 19 Aug 2018 00:11:30 +0300, Marko Rauhamaa wrote:
>
>> In Python programming, I mostly run into closures through inner classes
>> (as in Java).
>
> Inner classes aren't closures.

At least some of the methods of inner classes are closures (or there
would be no point to an inner class).

> Its also quite expensive to be populating your application with lots
> of classes used only once each, which is a common pitfall when using
> inner classes. Memory is cheap, but it's not so cheap that we ought to
> just profligately waste it needlessly.

That is a completely separate question.

There's is no a-priori reason for inner classes to be wasteful; they
have been part and parcel of Java programming from its early days, and
Java is widely used for high-performance applications.

CPython does use memory quite liberally. I don't mind that as
expressivity beats performance in 99% of programming tasks.

>> populating an object with fields (methods) in a loop is very rarely a
>> good idea.
>
> Of course it is *rarely* a good idea

So no dispute then.


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


Re: printing to stdout

2018-08-19 Thread richard lucassen
On Fri, 17 Aug 2018 08:31:22 +1000
Cameron Simpson  wrote:

> Just looking at your loop I would be inclined to just call flush once
> at the bottom, _before_ the sleep() call:
> 
>   sys.stdout.flush()
> 
> Your call; the performance difference will be small, so it tends to
> come down to keeping your code readable and maintainable.

This is a working script I made. It initializes the I/O expanders, then
it waits for an INT from these I/O expanders on GPIO23, reads the
contents and sends which bit on which chip went up or down to a fifo
(and stdout for logging)

As I'm new to Python, just this question: are there any unPythony
things in this code?

##

#!/usr/bin/env python3

list_pcf = [0x38, 0x39, 0x3a, 0x3b]
list_pcf_value = []

import sys
from smbus import SMBus
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
bus = SMBus(1)

# initialisation of the input devices:
print ("[INFO] initialisation input devices")
for i in range(len(list_pcf)):
  try:
bus.write_byte(list_pcf[i], 0xff) # set device to 0xff
output = bus.read_byte(list_pcf[i])
list_pcf_value.append(output) # append value to list
print ("found: %d, input value: 0x%x" % (list_pcf[i], output))
  except IOError:
print ("[ALERT] I/O problem device 0x%x (init)" % pcf)
  sys.stdout.flush()

# GPIO 23 set up as input. It is pulled up to stop false signals
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
loopcntr = 0 # detects if INT is kept low

while True:
  if GPIO.input(23) == 1: # if still 0, another event has occurred
GPIO.wait_for_edge(23, GPIO.FALLING)
  print ('---')
  while GPIO.input(23) == 0:
for i in range(len(list_pcf)):
  try:
output = bus.read_byte(list_pcf[i])
if output != list_pcf_value[i]:
  xor = list_pcf_value[i] ^ output
  for l in range(8):
if xor & 0x1:
  updown = (output >> l) & 0x1
  print ("%d bit %d: to %d" % (list_pcf[i],l,updown))
  print("%d %d %d" % (list_pcf[i],l,updown), 
file=open('/mnt/ramdisk/var/lib/ha/events.fifo', 'w'))
xor = xor >> 1
  list_pcf_value[i] = output
  except IOError:
print ("[ALERT] I/O problem device 0x%x" % list_pcf[i])

  if GPIO.input(23) == 1:
loopcntr = 0
break
  else:
loopcntr += 1
if loopcntr >=20:
  print ('[ALERT] possible INT loop, disable 10 seconds')
  sleep (10)
sys.stdout.flush()
GPIO.cleanup()

-- 
richard lucassen
http://contact.xaq.nl/
-- 
https://mail.python.org/mailman/listinfo/python-list