Re: Block Ctrl+S while running Python script at Windows console?

2019-03-19 Thread eryk sun
On 3/18/19, Dennis Lee Bieber  wrote:
> On Mon, 18 Mar 2019 14:38:40 -0400, "Malcolm Greene" 
> declaimed the following:
>
>>
>>Wondering if there's a way to have my Python scripts ignore these Ctrl+S
>> signals or if this behavior is outside of my Python script's control. If
>> there's a way to disable this behavior under Windows 10/Windows Server
>> 2016, I'm open to that as well.
>>
>
>   / (XOFF/XON) are traditional terminal control codes to
> stop/start transmission. The behavior is baked into the console being used.

The Windows console does not really implement XOFF (DC3, Ctrl+S) and
XON (DC1, Ctrl+Q) terminal behavior. In line-input mode, it implements
Ctrl+S as equivalent to pressing the pause key (i.e. VK_PAUSE, which
has the same numeric value as DC3), so it's meant to be familiar to
people who are used to working in terminals. But, in contrast to a
terminal emulator, there is no requirement to press Ctrl+Q (i.e. DC1)
to resume. Almost any key suffices to resume the console, except for
the pause key and modifiers (Ctrl, Alt, Shift). In particular,
pressing Ctrl+S again, as the original poster did, will resume the
Windows console, but it would not resume a terminal emulator.

If enabled, the console's extended editing keys feature overrides the
default pause behavior of Ctrl+S. It can be enabled via the console's
ExtendedEditKey registry value, or in the defaults and properties
dialogs by enabling "extended text selection keys". Disabling it also
disables immediate access to the console's new text selection keys
such as Shift+Arrows, in which case we have to first enter mark mode
via Ctrl+M.

The default extended-editing keymap doesn't define anything for
Ctrl+S, so it's just a DC3 (0x13) character. In principle the extended
editing keys can be customized to map Ctrl+S to a virtual key such as
VK_PAUSE (i.e. retain the default behavior), but, as far as I know,
the binary format of the console's ExtendedEditKeyCustom registry
value is not documented.

Regardless of the extended editing keys setting, we can always read
Ctrl+S via msvcrt.getwch(), since it disables line-input mode.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: tkinter

2019-03-19 Thread Peter Otten
Terry Reedy wrote:

> On 3/18/2019 12:00 PM, Informatico de Neurodesarrollo wrote:
>> Hello friends:
>> 
>> I am a beginner on programming in python.
>> 
>> I want make a simple program that test continuously (every 5 seg) the
>> connection  to internet and change the background color when are not
>> available. I try this , but not work properly:
>> 
>>  #!/usr/bin/env python3
>> # -*- coding: utf-8 -*-
> 
> Not needed for py 3 where utf-8 is default
> 
>> from tkinter import *
>> import socket, time
>> 
>> def DetectarConexion():
>>  testConn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>  try:
>>  testConn.connect(('8.8.8.8', 80))
>>  testConn.close()
>>  return True
>>  except:
>>  testConn.close()
>>  return False
>> 
>> root = Tk()
>> root.title("Conexión")
>> root.geometry("80x50")
>> 
>> while True:
>>  if DetectarConexion():
>>  # Background:Green
>>  root.config(background="#38EB5C")
>>  else:
>>  # Background:Red
>>  root.config(background="#F50743")
>>  time.sleep(5)
> 
> This is your problem.  Loop with event loop in order to not block gui.
> See working code below.
> 
>> root.mainloop()
> 
> #!/usr/bin/env python3
> 
> from tkinter import *
> 
> connected = False
> def DetectarConexion():
>  global connected
>  connected = not connected
>  return connected
> 
> root = Tk()
> root.title("Conexión")
> root.geometry("80x50")
> 
> def colorupdate():
>  if DetectarConexion():
>  # Background:Green
>  root.config(background="#38EB5C")
>  else:
>  # Background:Red
>  root.config(background="#F50743")
>  root.after(1000, colorupdate)  # 1000 milliseconds = 1 second
> 
> colorupdate()
> root.mainloop()

If the DetectarConexion() function takes long to execute it will still block 
the GUI because it is called indirectly by the callback. 

In that case you may execute it in a separate thread:

#!/usr/bin/env python3

from tkinter import *

import random
import threading
import time

# global flag used to communicate between the checker thread
# and the GUI in the main thread. If the interaction gets more
# complex you may use a queue.Queue() instead.
connected = False


def DetectarConexion():
# simulate that the function takes
# 3 seconds to execute
time.sleep(3)
return random.random() < .7  # good with 70% probability


def update_connection_state():
global connected
while True:
connected = DetectarConexion()
time.sleep(1)  # wait 1 second until the next check


def colorupdate():
if connected:
# Background:Green
root.config(background="#38EB5C")
else:
# Background:Red
root.config(background="#F50743")
root.after(1000, colorupdate)  # 1000 milliseconds = 1 second


checker_thread = threading.Thread(
target=update_connection_state, daemon=True
)
checker_thread.start()

root = Tk()
root.title("Conexión")
root.geometry("80x50")

colorupdate()
root.mainloop()


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


Re: running "python -i" in subprocess shows no prompt

2019-03-19 Thread finnkochinski
Thanks for letting me know that the list takes no attachments.

Please find my modified code at the end of this email. I found one problem. I 
was reading streams with "proc.stderr.readline()", which never returned, 
because only ">>> " was sent to stderr repeatedly, "\n" only going to stdout.
Now I am using proc.stderr.read(1) instead, and I do receive the prompts. 
Unfortunately both streams are mixed up:

Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> >1
>> 4
>>> 9
>>> 1>>> 6
>

I found that the pty module might be a solution, also from the helpful comments 
in this thread, but I can't find a simple example how to make it work.

regards
Finn

This is my last attempt, which produced the above output:

import subprocess, threading, time, os, sys

cont=True

def pyout(proc):
  while cont:
    c=proc.stdout.read(1)
    # was: c=proc.stdout.readline()
    sys.stdout.write(c)
    sys.stdout.flush()

def pyerr(proc):
  while cont:
    c=proc.stderr.read(1)
    # was: c=proc.stderr.readline()
    sys.stderr.write(c)
    sys.stderr.flush()

proc=subprocess.Popen(['python','-i'],
  stdin=subprocess.PIPE,
  stdout=subprocess.PIPE,
  stderr=subprocess.PIPE
)

threading.Thread(target=pyout,args=(proc,)).start()
threading.Thread(target=pyerr,args=(proc,)).start()

for i in range(1,5):
  time.sleep(1.)
  proc.stdin.write("print %d*%d\n" % (i,i))
  proc.stdin.flush()

time.sleep(0.1)
cont=False
proc.stdin.write("print\n") #make last read(1) finish



Mar 18, 2019, 6:26 PM by [email protected]:

> On Mon, 18 Mar 2019 14:10:51 +0100 (CET), <> [email protected] 
> > >
> declaimed the following:
>
> >Hello,
> >I try to start a separate python subprocess using the attached code. This 
> >example should catch all stdout and stderr output from the launched 
> >subprocess and send commands to its stdin.
>
>  No attachments here... either inline the code or provide a link to some
> file server.
>
> >The problem is that the prompt ">>>" asking for then next input is neither 
> >sent to stdout nor to stderr. The commands sent to stdin aren't echoed to 
> >stdout either.
>
>  The odds are very good that you are encountering the problems with
> buffered I/O streams. Such streams tend to only transfer when a) closed by
> the sending side, b) an end-of-line character sequence is sent.
>
>  The prompt string does not have an end-of-line (it expects input to be
> on the same terminal line)... so it is being held up in a buffer waiting
> for the end-of-line.
>
>  If you aren't encountering buffering problems, then it could be that
> the (nonvisible) code is doing read line operations, and THAT is blocking
> for an end-of-line.
>
>
> -- 
>  Wulfraed Dennis Lee Bieber AF6VN
>  > [email protected] >  
> HTTP://wlfraed.home.netcom.com/ 
>
> -- 
> https://mail.python.org/mailman/listinfo/python-list 
> 
>

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


Re: Reasoning of calling a method on class object instead of class instance object

2019-03-19 Thread Peter Otten
Arup Rakshit wrote:

> In this piece of code:
> 
> class RefrigeratedShippingContainer(ShippingContainer):

> @staticmethod
> def _c_to_f(celsius):
> return celsius * 9/5 + 32

> @property
> def fahrenheit(self):
> return RefrigeratedShippingContainer._c_to_f(self.celsius)

> If I call `_c_to_f`, `_f_to_c` methods on `self` instead of
> `RefrigeratedShippingContainer` class object, still it works. So what is
> the reason behind of this calling on the class object, instead class
> instance object?

I don't know, but I would prefer self over the class name.

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


Re: Block Ctrl+S while running Python script at Windows console?

2019-03-19 Thread Grant Edwards
On 2019-03-18, Malcolm Greene  wrote:

> Wondering if there's a way to have my Python scripts ignore these
> Ctrl+S signals or if this behavior is outside of my Python script's
> control.

This has nothing to do with Python does it?

Isn't Python is just writing to stdout and those write calls are
blocking due because the terminal emulator has stopped reading the
other end of the pipe/pty/queue/buffer/whatever-it's-called-in-windows?

-- 
Grant Edwards   grant.b.edwardsYow! It's some people
  at   inside the wall!  This is
  gmail.combetter than mopping!

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


Re: Block Ctrl+S while running Python script at Windows console?

2019-03-19 Thread Malcolm Greene
> This has nothing to do with Python does it? Isn't Python is just writing to 
> stdout and those write calls are blocking due because the terminal emulator 
> has stopped reading the other end of the 
> pipe/pty/queue/buffer/whatever-it's-called-in-windows?

You're right. But I wasn't sure. I know Python can trap Ctrl+C break signals, 
so I wondered if there was a similar tie-in for Ctrl+S.

Eryk did a great job explaining the tech details of what's happening behind the 
scenes in the Windows world. In my case it turned out that my clicking between 
windows was inadvertently selecting text pausing the running process. 
Unchecking the Windows console's Quick Edit mode stops this behavior.

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


Why can't access the property setter using the super?

2019-03-19 Thread Arup Rakshit
I have 3 classes which are connected to them through inheritance as you see in 
the below code:

import iso6346

class ShippingContainer:
"""docstring for ShippingContainer"""

HEIGHT_FT = 8.5
WIDTH_FT = 8.0
next_serial = 1337

@classmethod
def _get_next_serial(cls):
result = cls.next_serial
cls.next_serial += 1
return result

@staticmethod
def _make_bic_code(owner_code, serial):
return iso6346.create(owner_code=owner_code,
  serial=str(serial).zfill(6))

@classmethod
def create_empty(cls, owner_code, length_ft, *args, **keyword_args):
return cls(owner_code, length_ft, contents=None, *args, **keyword_args)

# ... skipped

def __init__(self, owner_code, length_ft, contents):
self.contents  = contents
self.length_ft = length_ft
self.bic = self._make_bic_code(owner_code=owner_code,
  
serial=ShippingContainer._get_next_serial())
# ... skipped


class RefrigeratedShippingContainer(ShippingContainer):
MAX_CELSIUS = 4.0
FRIDGE_VOLUME_FT3 = 100

def __init__(self, owner_code, length_ft, contents, celsius):
super().__init__(owner_code, length_ft, contents)
self.celsius = celsius

# ... skipped

@staticmethod
def _make_bic_code(owner_code, serial):
return iso6346.create(owner_code=owner_code,
  serial=str(serial).zfill(6),
  category='R')
@property
def celsius(self):
return self._celsius

@celsius.setter
def celsius(self, value):
if value > RefrigeratedShippingContainer.MAX_CELSIUS:
raise ValueError("Temperature too hot!")
self._celsius = value

# ... skipped


class HeatedRefrigeratedShippingContainer(RefrigeratedShippingContainer):
MIN_CELSIUS = -20.0

@RefrigeratedShippingContainer.celsius.setter
def celsius(self, value):
if value < HeatedRefrigeratedShippingContainer.MIN_CELSIUS:
raise ValueError("Temperature too cold!")
super().celsius = value




Now when I run the code :

Python 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from shipping import *>>> h1 = 
>>> HeatedRefrigeratedShippingContainer.create_empty('YML', length_ft=40, 
>>> celsius=-18)
Traceback (most recent call last):
  File "", line 1, in 
  File "/Users/aruprakshit/python_playground/shipping.py", line 23, in 
create_empty
return cls(owner_code, length_ft, contents=None, *args, **keyword_args)
  File "/Users/aruprakshit/python_playground/shipping.py", line 47, in __init__
self.celsius = celsius
  File "/Users/aruprakshit/python_playground/shipping.py", line 92, in celsius
super().celsius = value
AttributeError: 'super' object has no attribute 'celsius'
>>> 


Why here super is denying the fact that it has no celsius setter, although it 
has. While this code doesn’t work how can I solve this. The thing I am trying 
here not to duplicate the validation of temperature which is already in the  
setter property of the RefrigeratedShippingContainer class.




Thanks,

Arup Rakshit
[email protected]



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


Re: Why can't access the property setter using the super?

2019-03-19 Thread Ian Kelly
Here's the thing: the result of calling super() is not an instance of the
base class. It's just a proxy object with a __getattribute__ implementation
that looks up class attributes in the base class, and knows how to pass
self to methods to simulate calling base class methods on an instance. This
works fine for looking up methods and property getters. It doesn't work so
well for simulating other behaviors, like setters, or comparisons, or
iteration, etc.

A property is one example of what in Python is known as a descriptor, which
is described here:
https://docs.python.org/3/reference/datamodel.html#implementing-descriptors

A settable property has a __set__ method per the descriptor protocol. When
you try to set an attribute with the name of the property, Python looks up
the name in the class dict, finds the property object, and then calls its
__set__ method. The class of the super proxy object, however, does not
contain this property, and because you're not doing an attribute lookup,
the super proxy's __getattribute__ does not get called. So all Python sees
is that you tried to set an attribute that doesn't exist on the proxy
object.

The way I would suggest to get around this would be change your super()
call so that it looks up the property from the base class instead of trying
to set an attribute directly. For example, this should work:

super(HeatedRefrigeratedShippingContainer,
self.__class__).celsius.fset(self, value)

On Tue, Mar 19, 2019 at 9:12 AM Arup Rakshit  wrote:

> I have 3 classes which are connected to them through inheritance as you
> see in the below code:
>
> import iso6346
>
> class ShippingContainer:
> """docstring for ShippingContainer"""
>
> HEIGHT_FT = 8.5
> WIDTH_FT = 8.0
> next_serial = 1337
>
> @classmethod
> def _get_next_serial(cls):
> result = cls.next_serial
> cls.next_serial += 1
> return result
>
> @staticmethod
> def _make_bic_code(owner_code, serial):
> return iso6346.create(owner_code=owner_code,
>   serial=str(serial).zfill(6))
>
> @classmethod
> def create_empty(cls, owner_code, length_ft, *args, **keyword_args):
> return cls(owner_code, length_ft, contents=None, *args,
> **keyword_args)
>
> # ... skipped
>
> def __init__(self, owner_code, length_ft, contents):
> self.contents  = contents
> self.length_ft = length_ft
> self.bic = self._make_bic_code(owner_code=owner_code,
>
> serial=ShippingContainer._get_next_serial())
> # ... skipped
>
>
> class RefrigeratedShippingContainer(ShippingContainer):
> MAX_CELSIUS = 4.0
> FRIDGE_VOLUME_FT3 = 100
>
> def __init__(self, owner_code, length_ft, contents, celsius):
> super().__init__(owner_code, length_ft, contents)
> self.celsius = celsius
>
> # ... skipped
>
> @staticmethod
> def _make_bic_code(owner_code, serial):
> return iso6346.create(owner_code=owner_code,
>   serial=str(serial).zfill(6),
>   category='R')
> @property
> def celsius(self):
> return self._celsius
>
> @celsius.setter
> def celsius(self, value):
> if value > RefrigeratedShippingContainer.MAX_CELSIUS:
> raise ValueError("Temperature too hot!")
> self._celsius = value
>
> # ... skipped
>
>
> class HeatedRefrigeratedShippingContainer(RefrigeratedShippingContainer):
> MIN_CELSIUS = -20.0
>
> @RefrigeratedShippingContainer.celsius.setter
> def celsius(self, value):
> if value < HeatedRefrigeratedShippingContainer.MIN_CELSIUS:
> raise ValueError("Temperature too cold!")
> super().celsius = value
>
>
>
>
> Now when I run the code :
>
> Python 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43)
> [Clang 6.0 (clang-600.0.57)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> from shipping import *>>> h1 =
> HeatedRefrigeratedShippingContainer.create_empty('YML', length_ft=40,
> celsius=-18)
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/Users/aruprakshit/python_playground/shipping.py", line 23, in
> create_empty
> return cls(owner_code, length_ft, contents=None, *args, **keyword_args)
>   File "/Users/aruprakshit/python_playground/shipping.py", line 47, in
> __init__
> self.celsius = celsius
>   File "/Users/aruprakshit/python_playground/shipping.py", line 92, in
> celsius
> super().celsius = value
> AttributeError: 'super' object has no attribute 'celsius'
> >>>
>
>
> Why here super is denying the fact that it has no celsius setter, although
> it has. While this code doesn’t work how can I solve this. The thing I am
> trying here not to duplicate the validation of temperature which is already
> in the  setter property of the RefrigeratedShippingContainer class.
>
>
>
>
> Thanks,
>
> Arup Rakshit
> a...@zeit

Re: Block Ctrl+S while running Python script at Windows console?

2019-03-19 Thread eryk sun
On 3/19/19, Grant Edwards  wrote:
>
> This has nothing to do with Python does it?
>
> Isn't Python is just writing to stdout and those write calls are
> blocking due because the terminal emulator has stopped reading

It turns out the original poster had quick-edit mode enabled and the
pause was due to accidentally selecting text. A Python script can
disable this mode via GetConsoleMode / SetConsoleMode [1], called via
PyWin32 or ctypes. The original mode should be restored using an
atexit function. With quick-edit mode disabled, selecting text
requires enabling mark mode via the edit menu or Ctrl+M.

If it had been a Ctrl+S pause, the only way to programmatically
disable it for the current console is to disable line-input mode,
which is what msvcrt.getwch() does temporarily. However, disabling
line-input mode in general would break the REPL and input().

[1]: https://docs.microsoft.com/en-us/windows/console/getconsolemode

> the other end of the pipe/pty/queue/buffer/whatever-it's-called-
> in-windows?

In Windows 8+, a console client has handles for files on the ConDrv
device, which by default includes "Reference" (inherited reference to
a console), "Connect" (generic functions, such as setting the title),
"Input" (stdin), and "Output" (stdout, stderr). The host process
(conhost.exe) has a handle for ConDrv as well, from which it receives
IOCTL requests from its registered clients.

Windows 10 (release 1809) also supports pseudoconsoles [2], which are
roughly equivalent to Unix PTYs. The pseudoconsole interface is
restricted to virtual-terminal streams over a pair of pipes, so the
console's function-based API still has to be implemented for clients
by an instance of conhost.exe. It basically looks like the following:
Pseudoconsole Host <-- Pipe I/O --> conhost.exe <-- ConDrv I/O -->
Clients.

[2]: https://docs.microsoft.com/en-us/windows/console/pseudoconsoles
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I wrote a free book about TDD and clean architecture in Python

2019-03-19 Thread DL Neil

On 17/03/19 12:29 AM, [email protected] wrote:

I published on Leanpub a free book, "Clean Architectures in Python". It's a 
humble attempt to organise and expand some posts I published on my blog in the last years.
You can find it here: https://leanpub.com/clean-architectures-in-python

The main content is divided in two parts, this is a brief overview of the table 
of contents
* Part 1 - Tools
- Chapter 1 - Introduction to TDD
- Chapter 2 - On unit testing
- Chapter 3 - Mocks
* Part 2 - The clean architecture
- Chapter 1 - Components of a clean architecture
- Chapter 2 - A basic example
- Chapter 3 - Error management
- Chapter 4 - Database repositories



Unfortunately, the Kindle edition does not have a Table of Contents.

One might make a joke about (the book's) "architecture", but such humor 
often fails to carry-across language-translations.


A great effort, G!

--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: I wrote a free book about TDD and clean architecture in Python

2019-03-19 Thread Philippe Dixon
I actually came across this book last week looking for resources on best
practices for structuring a python app.  I plan on leaning on the material
heavily as I've been tasked with converting some Jupyter Notebooks to a
stand-alone application at work.  Thanks for sharing this Leonardo.

On Mon, Mar 18, 2019 at 12:30 PM Arup Rakshit  wrote:

> Hello,
>
> Thanks for writing this great book. I joined python community just couple
> of weeks.
>
>
> Thanks,
>
> Arup Rakshit
> [email protected]
>
>
>
> > On 16-Mar-2019, at 4:59 PM, [email protected] wrote:
> >
> > Hi all,
> >
> > I published on Leanpub a free book, "Clean Architectures in Python".
> It's a humble attempt to organise and expand some posts I published on my
> blog in the last years.
> >
> > You can find it here: https://leanpub.com/clean-architectures-in-python
> >
> > The main content is divided in two parts, this is a brief overview of
> the table of contents
> >
> > * Part 1 - Tools
> > - Chapter 1 - Introduction to TDD
> > - Chapter 2 - On unit testing
> > - Chapter 3 - Mocks
> >
> > * Part 2 - The clean architecture
> > - Chapter 1 - Components of a clean architecture
> > - Chapter 2 - A basic example
> > - Chapter 3 - Error management
> > - Chapter 4 - Database repositories
> >
> > Some highlights:
> >
> > - The book is written with beginners in mind
> >
> > - It contains 3 full projects, two small ones to introduce TDD and
> mocks, a bigger one to describe the clean architecture approach
> >
> > - Each project is explained step-by-step, and each step is linked to a
> tag in a companion repository on GitHub
> >
> > The book is free, but if you want to contribute I will definitely
> appreciate the help. My target is to encourage the discussion about
> software architectures, both in the Python community and outside it.
> >
> > As of today the book has been downloaded by 7,500 readers. I hope you
> will enjoy the book! if you do, please spread the news on your favourite
> social network
> > --
> > https://mail.python.org/mailman/listinfo/python-list
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


CheetahTemplate 3.2.1

2019-03-19 Thread Oleg Broytman
Hello!

I'm pleased to announce version 3.2.1, the first bugfix release of branch
3.2 of CheetahTemplate3.


What's new in CheetahTemplate3
==

Contributor for this release is Nicola Soranzo.

Minor features:

  - Changed LoadTemplate.loadTemplate{Module,Class}:
the loaded module's __name__ set to just the file name.
  - Use imp for Python 2, importlib for Python 3.

Bug fixes:

  - Fix a bug in LoadTemplate.loadTemplate{Module,Class}:
raise ImportError if the template was not found.

CI:

  - At Travis deploy wheels for macOS.
  - At AppVeyor deploy wheels directly to PyPI.


What is CheetahTemplate3


Cheetah3 is a free and open source template engine.
It's a fork of the original CheetahTemplate library.

Python 2.7 or 3.4+ is required.


Where is CheetahTemplate3
=

Site:
http://cheetahtemplate.org/

Development:
https://github.com/CheetahTemplate3

Download:
https://pypi.org/project/Cheetah3/3.2.1/

News and changes:
http://cheetahtemplate.org/news.html

StackOverflow:
https://stackoverflow.com/questions/tagged/cheetah


Example
===

Below is a simple example of some Cheetah code, as you can see it's practically
Python. You can import, inherit and define methods just like in a regular Python
module, since that's what your Cheetah templates are compiled to :) ::

#from Cheetah.Template import Template
#extends Template

#set $people = [{'name' : 'Tom', 'mood' : 'Happy'}, {'name' : 'Dick',
'mood' : 'Sad'}, {'name' : 'Harry', 'mood' : 
'Hairy'}]

How are you feeling?

#for $person in $people

$person['name'] is $person['mood']

#end for


Oleg.
-- 
Oleg Broytmanhttps://phdru.name/[email protected]
   Programmers don't die, they just GOSUB without RETURN.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why can't access the property setter using the super?

2019-03-19 Thread Arup Rakshit
Hello Ian,

That seems like too much code involved. Is this how we do write inheritance in 
Python. Coming from Ruby and JS world I find Python inheritance mechanism 
confusing so far. :/


Thanks,

Arup Rakshit
[email protected]



> On 19-Mar-2019, at 9:32 PM, Ian Kelly  wrote:
> 
> Here's the thing: the result of calling super() is not an instance of the
> base class. It's just a proxy object with a __getattribute__ implementation
> that looks up class attributes in the base class, and knows how to pass
> self to methods to simulate calling base class methods on an instance. This
> works fine for looking up methods and property getters. It doesn't work so
> well for simulating other behaviors, like setters, or comparisons, or
> iteration, etc.
> 
> A property is one example of what in Python is known as a descriptor, which
> is described here:
> https://docs.python.org/3/reference/datamodel.html#implementing-descriptors
> 
> A settable property has a __set__ method per the descriptor protocol. When
> you try to set an attribute with the name of the property, Python looks up
> the name in the class dict, finds the property object, and then calls its
> __set__ method. The class of the super proxy object, however, does not
> contain this property, and because you're not doing an attribute lookup,
> the super proxy's __getattribute__ does not get called. So all Python sees
> is that you tried to set an attribute that doesn't exist on the proxy
> object.
> 
> The way I would suggest to get around this would be change your super()
> call so that it looks up the property from the base class instead of trying
> to set an attribute directly. For example, this should work:
> 
>super(HeatedRefrigeratedShippingContainer,
> self.__class__).celsius.fset(self, value)
> 
> On Tue, Mar 19, 2019 at 9:12 AM Arup Rakshit  wrote:
> 
>> I have 3 classes which are connected to them through inheritance as you
>> see in the below code:
>> 
>> import iso6346
>> 
>> class ShippingContainer:
>>"""docstring for ShippingContainer"""
>> 
>>HEIGHT_FT = 8.5
>>WIDTH_FT = 8.0
>>next_serial = 1337
>> 
>>@classmethod
>>def _get_next_serial(cls):
>>result = cls.next_serial
>>cls.next_serial += 1
>>return result
>> 
>>@staticmethod
>>def _make_bic_code(owner_code, serial):
>>return iso6346.create(owner_code=owner_code,
>>  serial=str(serial).zfill(6))
>> 
>>@classmethod
>>def create_empty(cls, owner_code, length_ft, *args, **keyword_args):
>>return cls(owner_code, length_ft, contents=None, *args,
>> **keyword_args)
>> 
>># ... skipped
>> 
>>def __init__(self, owner_code, length_ft, contents):
>>self.contents  = contents
>>self.length_ft = length_ft
>>self.bic = self._make_bic_code(owner_code=owner_code,
>> 
>> serial=ShippingContainer._get_next_serial())
>># ... skipped
>> 
>> 
>> class RefrigeratedShippingContainer(ShippingContainer):
>>MAX_CELSIUS = 4.0
>>FRIDGE_VOLUME_FT3 = 100
>> 
>>def __init__(self, owner_code, length_ft, contents, celsius):
>>super().__init__(owner_code, length_ft, contents)
>>self.celsius = celsius
>> 
>># ... skipped
>> 
>>@staticmethod
>>def _make_bic_code(owner_code, serial):
>>return iso6346.create(owner_code=owner_code,
>>  serial=str(serial).zfill(6),
>>  category='R')
>>@property
>>def celsius(self):
>>return self._celsius
>> 
>>@celsius.setter
>>def celsius(self, value):
>>if value > RefrigeratedShippingContainer.MAX_CELSIUS:
>>raise ValueError("Temperature too hot!")
>>self._celsius = value
>> 
>># ... skipped
>> 
>> 
>> class HeatedRefrigeratedShippingContainer(RefrigeratedShippingContainer):
>>MIN_CELSIUS = -20.0
>> 
>>@RefrigeratedShippingContainer.celsius.setter
>>def celsius(self, value):
>>if value < HeatedRefrigeratedShippingContainer.MIN_CELSIUS:
>>raise ValueError("Temperature too cold!")
>>super().celsius = value
>> 
>> 
>> 
>> 
>> Now when I run the code :
>> 
>> Python 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43)
>> [Clang 6.0 (clang-600.0.57)] on darwin
>> Type "help", "copyright", "credits" or "license" for more information.
> from shipping import *>>> h1 =
>> HeatedRefrigeratedShippingContainer.create_empty('YML', length_ft=40,
>> celsius=-18)
>> Traceback (most recent call last):
>>  File "", line 1, in 
>>  File "/Users/aruprakshit/python_playground/shipping.py", line 23, in
>> create_empty
>>return cls(owner_code, length_ft, contents=None, *args, **keyword_args)
>>  File "/Users/aruprakshit/python_playground/shipping.py", line 47, in
>> __init__
>>self.celsius = celsius
>>  File "/Users/aruprakshit/python_playground/shipping.py", line 92, in
>> celsius
>>super().celsius = value
>> AttributeE

Re: Why can't access the property setter using the super?

2019-03-19 Thread Chris Angelico
On Wed, Mar 20, 2019 at 6:17 AM Arup Rakshit  wrote:
>
> Hello Ian,
>
> That seems like too much code involved. Is this how we do write inheritance 
> in Python. Coming from Ruby and JS world I find Python inheritance mechanism 
> confusing so far. :/
>
>

Ian gave the longhand form, but you can omit the arguments to super()
if you're using it inside the class definition.

Something you may want to consider, though, is NOT overriding the
parent's setter. Instead, have a validation step prior to the actual
setting, which you could then override in a subclass. Something like
this:

class RefrigeratedShippingContainer(ShippingContainer):
def _validate_temp(self, value):
"""Ensure that the given temperature is valid for this container

Invariant: At all times, self.validate_temp(self.celsius) will
not raise.
"""
if value > RefrigeratedShippingContainer.MAX_CELSIUS:
raise ValueError("Temperature too hot!")

@property
def celsius(self):
return self._celsius

@celsius.setter
def celsius(self, value):
self.validate_temp(value)
self._celsius = value


class HeatedRefrigeratedShippingContainer(RefrigeratedShippingContainer):
MIN_CELSIUS = -20.0

def _validate_temp(self, value):
if value < HeatedRefrigeratedShippingContainer.MIN_CELSIUS:
raise ValueError("Temperature too cold!")
super()._validate_temp(value)

Now, your property function doesn't need to care WHAT the validation
is, it just requests validation. You can redefine the validation logic
without changing anything else.

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


Can my python program send me a text message?

2019-03-19 Thread Steve
I have a program that triggers a reminder timer.  When that timer is done, I 
would like to receive a text message on my phone to tell me that it is time to 
reset the experiment.

Can this be done using Python?

Steve

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


Re: Can my python program send me a text message?

2019-03-19 Thread Abdur-Rahmaan Janhangeer
- 1) use pi with gsm module.
or
- 2) find some free sms api for python then use

Abdur-Rahmaan Janhangeer
http://www.pythonmembers.club | https://github.com/Abdur-rahmaanJ
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can my python program send me a text message?

2019-03-19 Thread Chris Angelico
On Wed, Mar 20, 2019 at 6:31 AM Steve  wrote:
>
> I have a program that triggers a reminder timer.  When that timer is done, I 
> would like to receive a text message on my phone to tell me that it is time 
> to reset the experiment.
>
> Can this be done using Python?
>

Yes! There are APIs that will help you with that. Search the web for
"text message api" and see what you can find. (Be aware that some of
them will ask you to pay money.) Then pick one of them and see if you
can access it from Python.

Most of them will be HTTP-based APIs, so you will do well to use the
"requests" module.

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


Re: Can my python program send me a text message?

2019-03-19 Thread Larry Martell
On Tue, Mar 19, 2019 at 3:30 PM Steve  wrote:
>
> I have a program that triggers a reminder timer.  When that timer is done, I 
> would like to receive a text message on my phone to tell me that it is time 
> to reset the experiment.
>
> Can this be done using Python?

You can send a text with email if you know the carrier:

Alltel [insert 10-digit number]@message.alltel.com
AT&T [insert 10-digit number]@txt.att.net
Boost Mobile [insert 10-digit number]@myboostmobile.com
Cricket Wireless [insert 10-digit number]@mms.cricketwireless.net
Sprint [insert 10-digit number]@messaging.sprintpcs.com
T-Mobile [insert 10-digit number]@tmomail.net
U.S. Cellular [insert 10-digit number]@email.uscc.net
Verizon [insert 10-digit number]@vtext.com
Virgin Mobile [insert 10-digit number]@vmobl.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can my python program send me a text message?

2019-03-19 Thread Dan Sommers

On 3/19/19 2:35 PM, Chris Angelico wrote:

On Wed, Mar 20, 2019 at 6:31 AM Steve  wrote:


I have a program that triggers a reminder timer.  When that timer is done, I 
would like to receive a text message on my phone to tell me that it is time to 
reset the experiment.

Can this be done using Python?



Yes! There are APIs that will help you with that. Search the web for
"text message api" and see what you can find. (Be aware that some of
them will ask you to pay money.) Then pick one of them and see if you
can access it from Python.


Some telephone carriers provide cost-free email-to-SMS
gateways.


Most of them will be HTTP-based APIs, so you will do well to use the
"requests" module.


Send email over SMTP; use Python's standard smtplib module.

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


Re: Block Ctrl+S while running Python script at Windows console?

2019-03-19 Thread Peter J. Holzer
On 2019-03-19 14:22:10 -, Grant Edwards wrote:
> On 2019-03-18, Malcolm Greene  wrote:
> > Wondering if there's a way to have my Python scripts ignore these
> > Ctrl+S signals or if this behavior is outside of my Python script's
> > control.
> 
> This has nothing to do with Python does it?
> 
> Isn't Python is just writing to stdout and those write calls are
> blocking due because the terminal emulator has stopped reading the
> other end of the pipe/pty/queue/buffer/whatever-it's-called-in-windows?

Yes, but there might be a way to control this behaviour from Python. On
Unix systems you can use the termios functions to turn flow control on
and off. This doesn't help you on Windows, but curses also has raw() and
noraw() functions which do that (among other things) and might work on
Windows, too. However, curses does a lot more than just control flow
control, so it may not be appropriate for the OP's problem.

hp

-- 
   _  | Peter J. Holzer| we build much bigger, better disasters now
|_|_) || because we have much more sophisticated
| |   | [email protected] | management tools.
__/   | http://www.hjp.at/ | -- Ross Anderson 


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


REPL, global, and local scoping

2019-03-19 Thread adam . preble
I got hit on the head and decided to try to write something of a Python 
interpreter for embedding. I'm starting to get into the ugly stuff like 
scoping. This has been a good way to learn the real deep details of the 
language. Here's a situation:

>>> meow = 10
>>> def vartest():
... x = 1
... y = 2
... def first():
...x = 3
...meow = 11
...return x
... def second():
...y = 4
...meow = 12
...return y
... return first() + second() + x + y + meow
...
>>> vartest()
20

first() and second() are messing with their own versions of x and y. Side note: 
the peephole optimizer doesn't just slap a 3 and 4 on the stack, respectively, 
and just return that. It'll actually do a STORE_NAME to 0 for each. The meow 
variable is more peculiar. The first() and second() inner functions are working 
on their own copy. However, vartest() is using the one from the calling scope, 
which is the REPL.

I can see in vartest() that it's using a LOAD_GLOBAL for that, yet first() and 
second() don't go searching upstairs for a meow variable. What is the basis 
behind this?

I tripped on this in my unit tests when I was trying to note that a class' 
constructor had run successfully without getting into poking the class' 
variables. I was trying to have it set a variable in the parent scope that I'd 
just query after the test.

It looks like in practice, that should totally not work at all:
>>> meow = 10
>>> class Foo:
...def __init__(self):
...   meow = 11
...
>>> f = Foo()
>>> meow
10

...and it's on me to carve out a throwaway inner meow variable. But hey, let's 
kick meow up to the class level:

>>> meow = 10
>>> class Foo:
...meow = 11
...def __init__(self):
...   pass
...
>>> f = Foo()
>>> meow
10

So I guess it's a different ballgame for classes entirely. What are the rules 
in play here for:
1. A first-level function knowing to use a variable globally
2. A Second-level function using the name locally and uniquely
3. Classes having no visibility to upper-level variables at all by default
-- 
https://mail.python.org/mailman/listinfo/python-list


Reversible malformed UTF-8 to malformed UTF-16 encoding

2019-03-19 Thread Florian Weimer
I've seen occasional proposals like this one coming up:

| I therefore suggested 1999-11-02 on the [email protected] mailing
| list the following approach. Instead of using U+FFFD, simply encode
| malformed UTF-8 sequences as malformed UTF-16 sequences. Malformed
| UTF-8 sequences consist excludively of the bytes 0x80 - 0xff, and
| each of these bytes can be represented using a 16-bit value from the
| UTF-16 low-half surrogate zone U+DC80 to U+DCFF. Thus, the overlong
| "K" (U+004B) 0xc1 0x8b from the above example would be represented
| in UTF-16 as U+DCC1 U+DC8B. If we simply make sure that every UTF-8
| encoded surrogate character is also treated like a malformed
| sequence, then there is no way that a single high-half surrogate
| could precede the encoded malformed sequence and cause a valid
| UTF-16 sequence to emerge.



Has this ever been implemented in any Python version?  I seem to
remember something like that, but all I could find was me talking
about this in 2000.

It's not entirely clear whether this is a good idea as the default
encoding for security reasons, but it might be nice to be able to read
XML or JSON which is not quite properly encoded, only nearly so,
without treating it as ISO-8859-1 or some other arbitrarily chose
single-byte character set.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: REPL, global, and local scoping

2019-03-19 Thread Chris Angelico
On Wed, Mar 20, 2019 at 7:23 AM  wrote:
>
> I got hit on the head and decided to try to write something of a Python 
> interpreter for embedding. I'm starting to get into the ugly stuff like 
> scoping. This has been a good way to learn the real deep details of the 
> language. Here's a situation:
>
> >>> meow = 10
> >>> def vartest():
> ... x = 1
> ... y = 2
> ... def first():
> ...x = 3
> ...meow = 11
> ...return x
> ... def second():
> ...y = 4
> ...meow = 12
> ...return y
> ... return first() + second() + x + y + meow
> ...
> >>> vartest()
> 20
>
> first() and second() are messing with their own versions of x and y. Side 
> note: the peephole optimizer doesn't just slap a 3 and 4 on the stack, 
> respectively, and just return that. It'll actually do a STORE_NAME to 0 for 
> each. The meow variable is more peculiar. The first() and second() inner 
> functions are working on their own copy. However, vartest() is using the one 
> from the calling scope, which is the REPL.
>
> I can see in vartest() that it's using a LOAD_GLOBAL for that, yet first() 
> and second() don't go searching upstairs for a meow variable. What is the 
> basis behind this?
>

Both first() and second() assign to the name "meow", so the name is
considered local to each of them. In vartest(), the name isn't
assigned, so it looks for an outer scope.

(Side note: the peephole optimizer COULD be written to simplify that
case, and there's no reason it can't in the future. Probably wouldn't
save all that much work though.)

> I tripped on this in my unit tests when I was trying to note that a class' 
> constructor had run successfully without getting into poking the class' 
> variables. I was trying to have it set a variable in the parent scope that 
> I'd just query after the test.
>
> It looks like in practice, that should totally not work at all:
> >>> meow = 10
> >>> class Foo:
> ...def __init__(self):
> ...   meow = 11
> ...
> >>> f = Foo()
> >>> meow
> 10
>
> ...and it's on me to carve out a throwaway inner meow variable. But hey, 
> let's kick meow up to the class level:

You've made "meow" a local variable here. If you want it to be an
attribute of the object, you would need to apply it to the object
itself ("self.meow = 11").

> >>> meow = 10
> >>> class Foo:
> ...meow = 11
> ...def __init__(self):
> ...   pass
> ...
> >>> f = Foo()
> >>> meow
> 10

This has created a class attribute. If you inspect "Foo.meow" (or
"f.meow", because of the way attribute lookup works), you'll see the
11.

> So I guess it's a different ballgame for classes entirely. What are the rules 
> in play here for:
> 1. A first-level function knowing to use a variable globally
> 2. A Second-level function using the name locally and uniquely
> 3. Classes having no visibility to upper-level variables at all by default

In all cases, you can use the declaration "global meow" to affect the
global (module-level) name. In the inner-function case, you can also
use "nonlocal x" to affect the "x" in the outer function. This applies
any time you *assign to* a name; if you just reference it, the lookup
will extend outwards in the most expected way.

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


Re: I wrote a free book about TDD and clean architecture in Python

2019-03-19 Thread Leonardo Giordani
Ha ha ha, yes I get it! =) I'm sorry, that depends entirely on the LeanPub 
processing chain (I believe, I'll have a look just to be sure). I hope the book 
will be useful even with this little issue. Thanks for reading it!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: tkinter

2019-03-19 Thread Informatico de Neurodesarrollo
Thanks for all yours recommendations, finally I was successfully 
finished my first project about tkinter (and I hope, not the last).


Here is the finally code:

#!/usr/bin/env python
#
#  DetectConn_2_0.py
#
#

from tkinter import *
import time, socket

def isInternet():
        testConn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
       # Force a time limit to conect to the host (5 seg), may be more 
or less

     testConn.settimeout(5)
     output = testConn.connect_ex(('10.44.0.1', 80))
        if output == 0:
            return True
        else:
            return False
        testConn.close()

def colorupdate():
    if isInternet():
        root.config(background="#38EB5C")
    else:
        root.config(background="#F50743")
    root.after(5000, colorupdate)

root = Tk()
root.title("Connection")
root.geometry("80x50")
root.resizable(width=False, height=False)

colorupdate()
root.mainloop()


Thanks again


--

Ing. Jesús Reyes Piedra
Admin Red Neurodesarrollo,Cárdenas
La caja decía:"Requiere windows 95 o superior"...
Entonces instalé LINUX.


--
Este mensaje le ha llegado mediante el servicio de correo electronico que 
ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema 
Nacional de Salud. La persona que envia este correo asume el compromiso de usar 
el servicio a tales fines y cumplir con las regulaciones establecidas

Infomed: http://www.sld.cu/

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


Re: Reversible malformed UTF-8 to malformed UTF-16 encoding

2019-03-19 Thread MRAB

On 2019-03-19 20:32, Florian Weimer wrote:

I've seen occasional proposals like this one coming up:

| I therefore suggested 1999-11-02 on the [email protected] mailing
| list the following approach. Instead of using U+FFFD, simply encode
| malformed UTF-8 sequences as malformed UTF-16 sequences. Malformed
| UTF-8 sequences consist excludively of the bytes 0x80 - 0xff, and
| each of these bytes can be represented using a 16-bit value from the
| UTF-16 low-half surrogate zone U+DC80 to U+DCFF. Thus, the overlong
| "K" (U+004B) 0xc1 0x8b from the above example would be represented
| in UTF-16 as U+DCC1 U+DC8B. If we simply make sure that every UTF-8
| encoded surrogate character is also treated like a malformed
| sequence, then there is no way that a single high-half surrogate
| could precede the encoded malformed sequence and cause a valid
| UTF-16 sequence to emerge.



Has this ever been implemented in any Python version?  I seem to
remember something like that, but all I could find was me talking
about this in 2000.

It's not entirely clear whether this is a good idea as the default
encoding for security reasons, but it might be nice to be able to read
XML or JSON which is not quite properly encoded, only nearly so,
without treating it as ISO-8859-1 or some other arbitrarily chose
single-byte character set.

Python 3 has "surrogate escape". Have a read of PEP 383 -- Non-decodable 
Bytes in System Character Interfaces.

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


Re: tkinter

2019-03-19 Thread MRAB

On 2019-03-19 19:46, Informatico de Neurodesarrollo wrote:

Thanks for all yours recommendations, finally I was successfully
finished my first project about tkinter (and I hope, not the last).

Here is the finally code:

#!/usr/bin/env python
#
#  DetectConn_2_0.py
#
#

from tkinter import *
import time, socket

def isInternet():
          testConn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
         # Force a time limit to conect to the host (5 seg), may be more
or less
       testConn.settimeout(5)
       output = testConn.connect_ex(('10.44.0.1', 80))


The following lines will cause a return from the function, so the 
testConn.close() line will never be reached.


Fortunately, the socket will be closed anyway, when the garbage 
collection occurs.



          if output == 0:
              return True
          else:
              return False
          testConn.close()

def colorupdate():
      if isInternet():
          root.config(background="#38EB5C")
      else:
          root.config(background="#F50743")
      root.after(5000, colorupdate)

root = Tk()
root.title("Connection")
root.geometry("80x50")
root.resizable(width=False, height=False)

colorupdate()
root.mainloop()


Thanks again



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


Re: Reversible malformed UTF-8 to malformed UTF-16 encoding

2019-03-19 Thread Florian Weimer
* MRAB:

> On 2019-03-19 20:32, Florian Weimer wrote:
>> I've seen occasional proposals like this one coming up:
>> 
>> | I therefore suggested 1999-11-02 on the [email protected] mailing
>> | list the following approach. Instead of using U+FFFD, simply encode
>> | malformed UTF-8 sequences as malformed UTF-16 sequences. Malformed
>> | UTF-8 sequences consist excludively of the bytes 0x80 - 0xff, and
>> | each of these bytes can be represented using a 16-bit value from the
>> | UTF-16 low-half surrogate zone U+DC80 to U+DCFF. Thus, the overlong
>> | "K" (U+004B) 0xc1 0x8b from the above example would be represented
>> | in UTF-16 as U+DCC1 U+DC8B. If we simply make sure that every UTF-8
>> | encoded surrogate character is also treated like a malformed
>> | sequence, then there is no way that a single high-half surrogate
>> | could precede the encoded malformed sequence and cause a valid
>> | UTF-16 sequence to emerge.
>> 
>> 
>> 
>> Has this ever been implemented in any Python version?  I seem to
>> remember something like that, but all I could find was me talking
>> about this in 2000.

> Python 3 has "surrogate escape". Have a read of PEP 383 -- Non-decodable 
> Bytes in System Character Interfaces.

Thanks, this is the information I was looking for.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I wrote a free book about TDD and clean architecture in Python

2019-03-19 Thread DL Neil

On 20/03/19 7:18 AM, Leonardo Giordani wrote:

Ha ha ha, yes I get it! =) I'm sorry, that depends entirely on the LeanPub 
processing chain (I believe, I'll have a look just to be sure). I hope the book 
will be useful even with this little issue. Thanks for reading it!



To be fair, that was one of my assumptions - publishers often imagine 
that a simple tool will convert between formats. (Um, no!) However, if 
they think it acceptable to publish a learned text without a ToC (or an 
Index? - haven't read that far), then I'd recommend finding another 
publisher who will properly respect your efforts! "Lean" shouldn't mean 
"lazy"!


Yes, I'm happy reading from cover-to-cover. Unfortunately, not being 
able to refer back to (say) the Mocks chapter, means it will be of 
little utility (to me) in-future. After all, if I access your blog 
on-line, can't I use a search facility to find a remembered post/'chapter'?

(ComSc: sequential/serial cf direct-access!)

Publishing criticisms aside, thank you!
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: REPL, global, and local scoping

2019-03-19 Thread adam . preble
On Tuesday, March 19, 2019 at 3:48:27 PM UTC-5, Chris Angelico wrote:
> > I can see in vartest() that it's using a LOAD_GLOBAL for that, yet first() 
> > and second() don't go searching upstairs for a meow variable. What is the 
> > basis behind this?
> >
> 
> Both first() and second() assign to the name "meow", so the name is
> considered local to each of them. In vartest(), the name isn't
> assigned, so it looks for an outer scope.

Thanks for the responses. I wanted to poke on this part just a little bit more. 
I want to mimic the proper behavior without having to go back to it repeatedly.

Let's say I'm parsing this code and generating the byte code for it. I run into 
meow on the right side of an expression but never the left. At this point, do I 
always generate a LOAD_GLOBAL opcode? Is that done whether or not I know if the 
variable is defined in a higher scope? That's what it looks like from renaming 
it to something I didn't define. I just want to double check.

On the interpreter side seeing the opcode, does that generally mean I walk up 
the variables I have in higher frames until I either run out of them or find it?

Does that mean defining "global meow" basically states "always use 
LOAD/STORE_GLOBAL opcodes for this one, even if it shows up on the left side of 
an assignment first?"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: REPL, global, and local scoping

2019-03-19 Thread Chris Angelico
On Wed, Mar 20, 2019 at 1:31 PM  wrote:
>
> On Tuesday, March 19, 2019 at 3:48:27 PM UTC-5, Chris Angelico wrote:
> > > I can see in vartest() that it's using a LOAD_GLOBAL for that, yet 
> > > first() and second() don't go searching upstairs for a meow variable. 
> > > What is the basis behind this?
> > >
> >
> > Both first() and second() assign to the name "meow", so the name is
> > considered local to each of them. In vartest(), the name isn't
> > assigned, so it looks for an outer scope.
>
> Thanks for the responses. I wanted to poke on this part just a little bit 
> more. I want to mimic the proper behavior without having to go back to it 
> repeatedly.
>
> Let's say I'm parsing this code and generating the byte code for it. I run 
> into meow on the right side of an expression but never the left. At this 
> point, do I always generate a LOAD_GLOBAL opcode? Is that done whether or not 
> I know if the variable is defined in a higher scope? That's what it looks 
> like from renaming it to something I didn't define. I just want to double 
> check.
>
> On the interpreter side seeing the opcode, does that generally mean I walk up 
> the variables I have in higher frames until I either run out of them or find 
> it?
>
> Does that mean defining "global meow" basically states "always use 
> LOAD/STORE_GLOBAL opcodes for this one, even if it shows up on the left side 
> of an assignment first?"
>

I would recommend parsing in two broad steps, as CPython does:

1) Take the source code and turn it into an abstract syntax tree
(AST). This conceptualizes the behaviour of the code more-or-less the
way the programmer wrote it.

2) Implement the AST in byte-code.

The AST for your first() function looks something like this:

FunctionDef(
name='first',
args=arguments(args=[], vararg=None, kwonlyargs=[],
kw_defaults=[], kwarg=None, defaults=[]),
body=[
Assign(
targets=[Name(id='x', ctx=Store())],
value=Constant(value=3, kind=None),
type_comment=None
), Assign(
targets=[Name(id='meow', ctx=Store())],
value=Constant(value=11, kind=None),
type_comment=None
), Return(
value=Name(id='x', ctx=Load())
)
],
decorator_list=[],
returns=None,
type_comment=None
)

(I got this by using ast.parse() and ast.dump() from the CPython 3.8
standard library. If you use a different version or interpreter, it
may look slightly different, but it'll be broadly similar.)

Since there are Assign entries with targets saying Name "x" and Name
"meow", you know that both those names are local to the function. So
you create local-to-function bytecode. But if you had a "global meow"
statement in that function (which translates to an AST node of
Global(names=['meow']) ), you would create STORE_GLOBAL opcodes, and
similarly, any names not assigned in the local scope would be looked
up globally.

Of course, life's never this simple, and there are myriad other
considerations. But hopefully that will help with an understanding of
what Python's doing.

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


RE: Can my python program send me a text message?

2019-03-19 Thread Steve
Thanks for all the suggestions.  It is going to take a while to sift through
them.  I will continue to watch for more discussion and will check back in
if/when I get something working or if I get stuck.

Steve


Footnote:
Fight the hand that feeds the hate.

-Original Message-
From: Python-list  On
Behalf Of Larry Martell
Sent: Tuesday, March 19, 2019 3:46 PM
To: Python 
Subject: Re: Can my python program send me a text message?

On Tue, Mar 19, 2019 at 3:30 PM Steve  wrote:
>
> I have a program that triggers a reminder timer.  When that timer is done,
I would like to receive a text message on my phone to tell me that it is
time to reset the experiment.
>
> Can this be done using Python?

You can send a text with email if you know the carrier:

Alltel [insert 10-digit number]@message.alltel.com 
AT&T [insert 10-digit number]@txt.att.net 
Boost Mobile [insert 10-digit number]@myboostmobile.com 
Cricket Wireless [insert 10-digit number]@mms.cricketwireless.net 
Sprint [insert 10-digit number]@messaging.sprintpcs.com 
T-Mobile [insert 10-digit number]@tmomail.net 
U.S. Cellular [insert 10-digit number]@email.uscc.net 
Verizon [insert 10-digit number]@vtext.com 
Virgin Mobile [insert 10-digit number]@vmobl.com

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

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


Re: Can my python program send me a text message?

2019-03-19 Thread Terry Reedy

On 3/19/2019 10:56 PM, Steve wrote:

Thanks for all the suggestions.  It is going to take a while to sift through
them.  I will continue to watch for more discussion and will check back in
if/when I get something working or if I get stuck.

Steve


Footnote:
Fight the hand that feeds the hate.

-Original Message-
From: Python-list  On
Behalf Of Larry Martell
Sent: Tuesday, March 19, 2019 3:46 PM
To: Python 
Subject: Re: Can my python program send me a text message?

On Tue, Mar 19, 2019 at 3:30 PM Steve  wrote:


I have a program that triggers a reminder timer.  When that timer is done,

I would like to receive a text message on my phone to tell me that it is
time to reset the experiment.


Can this be done using Python?


You can send a text with email if you know the carrier:

Alltel [insert 10-digit number]@message.alltel.com
AT&T [insert 10-digit number]@txt.att.net
Boost Mobile [insert 10-digit number]@myboostmobile.com
Cricket Wireless [insert 10-digit number]@mms.cricketwireless.net
Sprint [insert 10-digit number]@messaging.sprintpcs.com
T-Mobile [insert 10-digit number]@tmomail.net
U.S. Cellular [insert 10-digit number]@email.uscc.net
Verizon [insert 10-digit number]@vtext.com
Virgin Mobile [insert 10-digit number]@vmobl.com


Since I know my carrier, I tried this and it works.

--
Terry Jan Reedy

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