Re: nonlocal fails ?

2019-11-14 Thread Richard Damon
On 11/14/19 12:57 PM, R.Wieser wrote:
> Michael,
>
>> nonlocal does not share or use its *caller's* variables.  Rather it
>> reaches into the scope of the outer function where it was defined.
>> That's a very different concept than what you're proposing.
> Oh blimy!   You're right.Its an at compile-time thing, not a runtime 
> one.
>
> Thanks for the heads-up.
>
>> I know of no sane way that a function could work with the scope of
>> any arbitrary caller.
> The trick seems to be to emulate a "by reference" call, by using a mutable 
> object as the argument and stuff the value inside of it (IIRC a tuple with a 
> single element).

tuples are immutable, use a list or a dictionary.

>> What would happen if the caller's scope didn't have any
>> names that the function was looking for?
> Handle it the same as any other mistake, and throw an error ?
>
> Regards,
> Rudy Wieser
>
>

-- 
Richard Damon

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


Re: nonlocal fails ?

2019-11-14 Thread Richard Damon
On 11/14/19 1:43 PM, R.Wieser wrote:
> Richard,
>
>> Assuming that one language works like another is a danger
> Abitrarily redefining words and using misnomers is another ...  ("global" 
> and "nonlocal" respecivily if you wonder)
>
>> First, Python doesn't really have 'Variables' like a lot of other 
>> languages
>> (they don't hold a bag of bytes), as Python names don't hold values, but
>> are just references to objects which actually hold the value
> That's a principle as old as programming languages itself I believe.

There are at least two very different concepts that act like variables
in different languages. In a language like C, a variable is a 'bucket of
byte' that holds some value. If you assign the value of one variable to
another, that byte pattern is copied from one to another. That
representation might include a pointer to some other block (a pointer or
reference), but generally this is something explicit. In this sort of
language your names represent variables that actually hold values.

In Python, the name for your 'variable' doesn't actually hold the value
that is assigned to it, but instead the bucket of bytes associated with
the name is ALWAYS a pointer to a bucket of bytes that represents the
value. Multiple names are allowed to point to the same value object, so
assigning one name to another just copies that pointer, and they share
the same value object. You shouldn't really think of names as holding
'values' but the names are 'bound' to the value objects (which aren't
tied to a given name).

>
>> If the name is never bound to something, then the name will be also looked
>> for in the global namespace.
> Can you give an example of that ?I currently cannot wrap my head around 
> what you could be meaning there - anything I can imagine simply doesn't make 
> any sense ...
>
> Regards,
> Rudy Wieser
>
#This Function creates a local name and updates it. str will be created
locally and looked up locally

def useslocal():

    str = "String"

    str = str + " Added"


gstr = "Global"

# This function never binds a value to gstr, so it will look in the
'global' space to find the name

def useglobal():

   str = gstr + " Seen"


# This function include a binding to gstr, so it is only looked for
locally,

#so this use will create an error that it can't find gstr,

# even though it was defined in the global name space

def getserror():

    str = gstr + " Error"

    gstr = str

# This works because of the global statement, and updates the global

def workingglobal():

    global gstr

    str = gstr + " Error"

    gstr = str


-- 
Richard Damon

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


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread MRAB

On 2019-11-15 00:37, Dennis Lee Bieber wrote:

On Thu, 14 Nov 2019 21:00:59 +0100, "R.Wieser" 
declaimed the following:


:-)  I already wrote that program in C{something} (I'm not sure what my Pi 
offers by default) a while ago, but "ported" it to python.  For the above 
mentioned "example" reason.




"by default" pretty much any Linux distribution provides gcc
(supporting both "plain C" and "C++"). With apt-get one can augment with
Fortran, Ada (GNAT), "D", Go, Objective-C and Objective-C++. Outside of gcc
one can install free-pascal and Lazarus IDE. There is even a COBOL
compiler.


Objective-C++?

I knew that Objective-C is C with objects.

I knew that C++ is C with objects.

But C with both?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Trouble trying to get started with pygame

2019-11-14 Thread originallmoney
On Tuesday, November 12, 2019 at 7:05:16 PM UTC-5, Terry Reedy wrote:
> On 11/12/2019 2:32 PM, originallmo...@gmail.com wrote:
> > I'm curious: I've been seeing people having multiple pygame programs open 
> > at once (Where each one is a component of a main program, obviously).
> 
> Multiple programs open at once on modern machines is normal.  Do you 
> mean multiple windows for one program?  As is possible with IDLE?
> 
> -- 
> Terry Jan Reedy

Well, the example I was seeing, the person had one window which contained a 
portion of the larger pygame program controlling the display, another for 
controlling the characters, and another for the main program (Plus, I think, 
two others whose purpose I forget). I'm just concerned because, I can't imagine 
that's possible from the command prompt, but, I don't know what they had that 
would allow them to have multiple subprograms open at once in Python. I'm used 
to that in Visual Studio C++, but, I don't know of such a thing for Python.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread Michael Torrie
On 11/14/19 2:13 AM, R.Wieser wrote:
> Too bad that the Pi has no free hardware that can be abused for stuff like 
> this (like a serial port in synchronous mode).

An arduino working in conjunction with the Pi can fill in the gaps.  At
one time you could buy an arduino board that was also a Pi hat.  Python
on the Pi and C on the arduino seemed like a good idea to me.

Also there are microprocessor boards that can run MicroPython which does
offer some real-time functionality with a nice Python script front end.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: nonlocal fails ?

2019-11-14 Thread Michael Torrie
On 11/14/19 2:16 PM, R.Wieser wrote:
> I think I did - though implicitily.   What do normal people use "by 
> reference" arguments for ?   Yep, that is what I wanted too.

Well I've only seen this done in languages where other mechanisms for
returning complex types are not present. For example in C.  Chris talked
about dealing with languages where strings are not first-class citizens,
for example.  In C you can either return a pointer to the string (and
remember who's responsibility it is to free the memory!), or you can
allocate memory yourself and pass the pointer to a function, like strcpy.

In Python there is no similar equivalent, other than hacks involving
passing in mutable objects and using those objects to save the state.
State is maintained either by returning everything from the function you
need to maintain state (in a tuple, for example), or by using OOP.
Another mechanism Python has for doing certain types of state keeping
between calls is the generator idea.

> I'm trying to learn how Python works, and for that I (ofcourse) compare it 
> to other languages.   What-and-how it does something different (or equal!) 
> in regard to them.

Fair enough, but trying to do 1:1 transliterations isn't going to help
you learn idiomatic Python.


> 1) Have value
> 2) use value in procedure 1
> 3) use updated value in procedure 2
> 4) use again updated value in procedure 1, 2 or maybe 3

A clear case for using an object and placing your procedures as methods
to the object.  Everything in Python is OO under the hood, even if you
are not forced to use a particular paradigm.  Even a module is an
object.  It's a sort of singleton really.  functions are like a static
method in other languages.  The beauty of Python's organization, though,
is you don't have to use a forced class structure as your namespace.
Modules and packages provide a nicer namespace than Java or C#'s method.
 But I digress.

> For the sake of learning I'm now going over all of the possibilities to see 
> if and how they work.  For that I've already excluded globals and the 
> practice of feeding the value as an argument to the procedure and than store 
> its result as the new one.  I've also excluded using a class object and put 
> the code in there, as well as faking a "by reference" passing by using a 
> tuple.   "nonlocal" looked to be another option, but it appears to be rather> 
> limited in its application.

Well be sure to add Python's classes and objects to your list of
possibilities.  And also explore generators (coroutines).


> In short, the /ways to the goal/ are (currently) important to me, not the 
> goal itself (I'm sure that apart from the "nonlocal" one all of the above 
> are viable, and I thus can get /something/ to work)
> 
> Yeah, I'm weird like that.  Sorry.

Okay I just was wondering if there is a particular task at hand.  Often
that's the best way to learn a language. You have a specific task you
want to accomplish, or program you need to write, and then find out the
best way to do it within the abilities and strengths of the language.

Years ago I was taught Prolog and man I fought that language because I
never really grasped the concepts and wanted to program in C or Pascal
instead of Prolog.  If I knew then what I know now I would have probably
had an easier time of it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: nonlocal fails ?

2019-11-14 Thread Terry Reedy

On 11/14/2019 4:16 PM, R.Wieser wrote:


If you mentioned what problem you are trying to solve


1) Have value
2) use value in procedure 1
3) use updated value in procedure 2
4) use again updated value in procedure 1, 2 or maybe 3



For the sake of learning I'm now going over all of the possibilities to see
if and how they work.

 >  For that I've already excluded globals and the

practice of feeding the value as an argument to the procedure and than store
its result as the new one.


This is discouraged for anything very complex.


I've also excluded using a class object and put
the code in there,


This is the standard way in Python and other OO languages.  By 
'excluded', do you mean 'rejected', or 'tried that, what else is there?'



as well as faking a "by reference" passing by using a tuple.


One has to pass a mutable, such as list, set, dict, or user class instance.

"nonlocal" looked to be another option, but it appears to be rather

limited in its application.


Closures are standard in functional languages and are less limited than 
you seem to think.  But you have to enclose (nest) many or all of the 
functions that directly rebind 'val' (else one might as well use a 
global value).


def valclass(val):
def set(newval):  # For functions not defined within valclass.
nonlocal val
val = newval
def get()
return val
def proc1(args)
nonlocal val
...
dev proc2(args)
nonlocal val
...
return setval, getval, proc1, proc2
# return {'set':set, 'get':get, 'proc1':proc1, 'proc2':proc2}

setval, getval, proc1, proc2 = valclass(3)
# val = valclass(3)


In short, the /ways to the goal/ are (currently) important to me, not the
goal itself (I'm sure that apart from the "nonlocal" one all of the above
are viable, and I thus can get /something/ to work)



--
Terry Jan Reedy

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


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread Rob Gaddi

On 11/14/19 12:34 PM, R.Wieser wrote:

Dennis,


The R-Pi has never, to my knowledge, been billed as suitable
for industrial/real-time/process-control...


I have not read those specs to be honest.   But for some reason I assumed
that a 1.4 GHz machine should easily be able to generate a 1.6 KHz signal,
even using Python.   I was wrong. It can, but just barily and not without
jitter and hickups.  Lesson learned.

Regards,
Rudy Wieser



The machine itself would be fine.  But between Python and Linux (probably the 
bigger culprit), there are lots of things that aren't interested in your 
deterministicity.


Just run it bare-metal; I'm sure that's straightforward on an rPi and has no 
gotchas or complications that would lead to days/weeks of frustration.


On an actually practical note; ever since they started baking the quasi-realtime 
stuff into the Linux kernel, you've been able to use the whole 
sched_setscheduler(2) family of calls (from C) to set a process's real-time 
priority.  That might get things good enough to do the job, though how one gets 
there from Python I couldn't tell you.  Naïvely I'd say to just use ctypes to 
wrap those calls, but that's some low-level stuff to be getting into from a very 
high-level language.  Might work?


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: nonlocal fails ?

2019-11-14 Thread Chris Angelico
On Fri, Nov 15, 2019 at 8:21 AM R.Wieser  wrote:
>
> Michael,
>
> > I note that you didn't answer the question, what are you trying
> > to accomplish?
>
> I think I did - though implicitily.   What do normal people use "by
> reference" arguments for ?   Yep, that is what I wanted too.
>

That doesn't really answer the question. It's like you just bought a
self-driving car and then ask people how you push the accelerator
pedal. What are you trying to do? Well, what normal people use the
accelerator pedal for! Only, that's irrelevant. The point of your new
car isn't to push the pedal - it's to get you some place. Where are
you trying to get to?

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


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread MRAB

On 2019-11-14 20:00, R.Wieser wrote:

Dave,


Can you expand on what you are trying to accomplish with this?


There is a small 433 MHz rf transmitter connected to the pin, and when I
send the right pattern a wireless wall-wart will respond and switch a lamp
on or off. Its just ment as an example of a real-world application of
Python, nothing serious.

Ofcourse, by doing so I'm learning about how to use python (and the Pi)
myself too. :-)

It seems a small C program or library you interface python too is a better 
solution.


:-)  I already wrote that program in C{something} (I'm not sure what my Pi
offers by default) a while ago, but "ported" it to python.  For the above
mentioned "example" reason.

... Which is also why I didn't even try to just shell to that program, or
try to interface with a C{something} library.

Though doing such interfacing is in the pipeline (I've already
found-and-stored some documentation about it).

Not everything needs to be done in Python. You should use an extension 
for that kind of thing and then tell it what to do from Python.

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


Re: nonlocal fails ?

2019-11-14 Thread R.Wieser
Michael,

> I note that you didn't answer the question, what are you trying
> to accomplish?

I think I did - though implicitily.   What do normal people use "by 
reference" arguments for ?   Yep, that is what I wanted too.

> It looks to me like you're trying to write a program in a different
> language here, not Python.

I'm trying to learn how Python works, and for that I (ofcourse) compare it 
to other languages.   What-and-how it does something different (or equal!) 
in regard to them.

>Although come to that I can't think of very many reasons to do
> what you propose in any language.

I made propositions to its functioning ?And I was thinking that I just 
pointed out oddities in it ...

> If you mentioned what problem you are trying to solve

1) Have value
2) use value in procedure 1
3) use updated value in procedure 2
4) use again updated value in procedure 1, 2 or maybe 3

For the sake of learning I'm now going over all of the possibilities to see 
if and how they work.  For that I've already excluded globals and the 
practice of feeding the value as an argument to the procedure and than store 
its result as the new one.  I've also excluded using a class object and put 
the code in there, as well as faking a "by reference" passing by using a 
tuple.   "nonlocal" looked to be another option, but it appears to be rather 
limited in its application.

In short, the /ways to the goal/ are (currently) important to me, not the 
goal itself (I'm sure that apart from the "nonlocal" one all of the above 
are viable, and I thus can get /something/ to work)

Yeah, I'm weird like that.  Sorry.

Regards,
Rudy Wieser


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


Re: py2 vs py3: zlib.adler32/crc32

2019-11-14 Thread MRAB

On 2019-11-14 19:22, Karsten Hilbert wrote:

Hi all,

I am unsure how to solve: I use adler32/crc32 to generate integer values from 
data
for setting up an advisory lock in PostgreSQL.

The PG function pg_try_advisory_lock()

   
https://www.postgresql.org/docs/12/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS

takes two PG ints which are defined as:

integer 4 bytes typical choice for integer  -2147483648 to 
+2147483647

Now, in Py > 2.5 zlib.adler32/crc32 will return suitable integers.

However, in Py3 the return range has been changed to

The return value is unsigned and in the range [0, 2**32-1] regardless of 
platform.

which will overflow the PostgreSQL function.

Is there a way to convert/modify/shift the py3 value such that it shows the
same representation as the py2 value ?   What I am looking for is:

   v2 = py2.zlib.adler32(data)
   v3 = some_magic(py3.zlib.adler32(data))
   if v2 == v3:
  print('same')

I am sure there's something obvious with struct/<
Unsigned 32-bit to signed 32-bit:

unsigned - (unsigned & 0x8000) * 2

Signed 32-bit to unsigned 32-bit:

signed & 0x
--
https://mail.python.org/mailman/listinfo/python-list


Re: Reading mail getting [, ...

2019-11-14 Thread MRAB

On 2019-11-14 19:43, Abdur-Rahmaan Janhangeer wrote:

Greetings,

Using this code to read mail. I'm printing to file only mails sent by some
people. For some mails i get the body as the below instead of actual text:

[, ]

instead of the actual mail body.

Here is the code:

#
#
import imaplib
import email
import time

my_senders = ['y...@x.com ', 'y...@y.com', 'y...@z.com']
my_mail_count = 1
open('data.txt', 'w+')
def read_email_from_gmail():
 global my_mail_count, my_senders

 mail = imaplib.IMAP4_SSL('imap.gmail.com')
 mail.login('mym...@gmail.com','password')
 mail.select('inbox')

 result, data = mail.search(None, 'ALL')
 mail_ids = data[0]

 id_list = mail_ids.split()
 first_email_id = int(id_list[0])
 latest_email_id = int(id_list[-1])

 for i in range(latest_email_id,first_email_id, -1):
   #pypi  # need str(i)
 result, data = mail.fetch(str(i), '(RFC822)' )

 for response_part in data:
 if isinstance(response_part, tuple):
 # from_bytes, not from_string
 msg = email.message_from_bytes(response_part[1])

 email_subject = msg['subject']
 email_from = msg['from']
 print ('{} {}'.format(my_mail_count, email_subject))
 print('{}'.format(email_from))
 my_mail_count += 1

 #email_body = msg.get_payload(decode=True)

 for m in my_senders:
 if m in email_from:
 if msg.is_multipart():
 for part in msg.get_payload():
 print(msg.get_payload(),
file=open('data.txt', 'a'))
 if isinstance(msg.get_payload(), list):
 print(dir(msg.get_payload()[0]))
 else:
 print(msg.get_payload(), file=open('data.txt',
'a'))
 if isinstance(msg.get_payload(), list):
 print(dir(msg.get_payload()[0]))

read_email_from_gmail()
#
#

Any idea?

The payload is sometimes split into parts that are encoded. Do something 
like this:


from email.header import decode_header

def decode_payload(header, default_encoding='utf-8'):
parts = []

for data, encoding in decode_header(header):
if isinstance(data, str):
parts.append(data)
else:
parts.append(data.decode(encoding or default_encoding))

return ' '.join(parts)
--
https://mail.python.org/mailman/listinfo/python-list


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread Dave Cinege

Rudy,

OK I'm old enough cancer to know what X10 is. :-) I wouldn't think this 
is too difficult to do as you're only sending. For this application IMO 
there is too much going on inside python that can interrupt the cycle of 
modulation. (Intra and Extra python; garbage collection, other 
processes, etc)


I would drop back to a simple program in C that you execute from python 
to do the actual sending putting your 'message' on the command line to 
that program (or use a tmpfile). I think your solution will be to 
execute this program from python.


Let me stress, my advise is doing this *reliably*. In that regard you 
might need look at locking your C process to 1 CPU and giving it highest 
priority. (man nice)


Once you have this working reliably, you could then look to convert it 
to a python c-module to more tightly integrate it.


Dave


On 2019/11/14 15:00, R.Wieser wrote:

Dave,


Can you expand on what you are trying to accomplish with this?


There is a small 433 MHz rf transmitter connected to the pin, and when I
send the right pattern a wireless wall-wart will respond and switch a lamp
on or off. Its just ment as an example of a real-world application of
Python, nothing serious.

Ofcourse, by doing so I'm learning about how to use python (and the Pi)
myself too. :-)


It seems a small C program or library you interface python too is a better
solution.


:-)  I already wrote that program in C{something} (I'm not sure what my Pi
offers by default) a while ago, but "ported" it to python.  For the above
mentioned "example" reason.

... Which is also why I didn't even try to just shell to that program, or
try to interface with a C{something} library.

Though doing such interfacing is in the pipeline (I've already
found-and-stored some documentation about it).

Regards,
Rudy Wieser



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


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread R.Wieser
Dennis,

> The R-Pi has never, to my knowledge, been billed as suitable
> for industrial/real-time/process-control...

I have not read those specs to be honest.   But for some reason I assumed 
that a 1.4 GHz machine should easily be able to generate a 1.6 KHz signal, 
even using Python.   I was wrong. It can, but just barily and not without 
jitter and hickups.  Lesson learned.

Regards,
Rudy Wieser


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


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread R.Wieser
Dennis,

> Ugh -- let's try Google Drive...

I was able to download them, thanks.All but the 100uSec one seemed to be 
rather stable.

> That is what I'd thought, but if you've looked at that simple program I
> used, apparently the "run longer" was taking place between the
>
> t +=
>
> and the
>
> t - time.time()

I don't think so, as that "t +=" is relative and depends on the end time of 
the last sleep - just as it should I might say.   And that means that that 
"run longer" can have been taking place anywhere between the end of the last 
sleep and the "t - time.time()" in the new one.

By the way, on my scope the "wrap around" time seemed to be quite long, in 
the neighborhood of 80 uSec

Alas, the drift-compensated sleep did not seem to make the output any more 
dependable - though I hope it means that I do not need to re-tweak the delay 
when running on another Pi than my current one (a 3B+).

Regards,
Rudy Wieser


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


Re: nonlocal fails ?

2019-11-14 Thread Chris Angelico
On Fri, Nov 15, 2019 at 7:19 AM Michael Torrie  wrote:
>
> On 11/14/19 10:57 AM, R.Wieser wrote:
> >> I know of no sane way that a function could work with the scope of
> >> any arbitrary caller.
> >
> > The trick seems to be to emulate a "by reference" call, by using a mutable
> > object as the argument and stuff the value inside of it (IIRC a tuple with a
> > single element).
>
> Right. You could pass in a dict as an argument. You could even pass in
> the caller's locals() dictionary.  I'm not sure I recommend the latter
> approach, however.

The locals() dict isn't guaranteed to be mutable. At the moment, there
are very very few actual language guarantees regarding changes to
locals(), but there's currently a WIP to define things a little more
tightly:

https://www.python.org/dev/peps/pep-0558/

Neither in the current wording nor in the proposed wording is any sort
of promise that you could pass locals() to another function and have
it usefully modify that.

> I'm coming more and more around to some of the ideas of functional
> programming.  Doing as you suggest, reaching back to the caller's
> variables, sounds extremely messy to me.  And very fragile, hard to
> test, and doesn't lend itself to easily extended functionality by
> chaining(think unix-style piping).
>
> I find Python's ability to return tuples virtually eliminates any need I
> have to "pass by reference."

Agreed. Or Python's ability to return strings. Most of the
pass-by-reference that I do in languages like SourcePawn is just to
get around the problem that strings aren't first-class values.

> I'm coming around to the idea that wherever possible, functions should
> have no side effects.  Those things that need side effects should be
> isolated so they are easy to maintain.  I believe they call this "push
> side effects to the edges."

Something like that. Ideally, a function should be pure - having no
side effects, being unaffected by external state, and having a return
value determined entirely by its arguments. Not every function can be
pure, of course (for instance, print() is most certainly NOT a pure
function), but the more of your functions that are pure, and the purer
your other functions are, the easier it is to reason about your code
and refactor things.

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


Re: nonlocal fails ?

2019-11-14 Thread Michael Torrie
On 11/14/19 10:57 AM, R.Wieser wrote:
> The trick seems to be to emulate a "by reference" call, by using a mutable 
> object as the argument and stuff the value inside of it (IIRC a tuple with a 
> single element).

I note that you didn't answer the question, what are you trying to
accomplish? In other words, what problem are you trying to solve.  It
looks to me like you're trying to write a program in a different
language here, not Python.  Although come to that I can't think of very
many reasons to do what you propose in any language.

If you mentioned what problem you are trying to solve, I'm sure folks
can suggest cleaner, more idiomatic ways of doing it in Python.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: nonlocal fails ?

2019-11-14 Thread Michael Torrie
On 11/14/19 10:57 AM, R.Wieser wrote:
>> I know of no sane way that a function could work with the scope of
>> any arbitrary caller.
> 
> The trick seems to be to emulate a "by reference" call, by using a mutable 
> object as the argument and stuff the value inside of it (IIRC a tuple with a 
> single element).

Right. You could pass in a dict as an argument. You could even pass in
the caller's locals() dictionary.  I'm not sure I recommend the latter
approach, however.

> Handle it the same as any other mistake, and throw an error ?

Sure.

I'm coming more and more around to some of the ideas of functional
programming.  Doing as you suggest, reaching back to the caller's
variables, sounds extremely messy to me.  And very fragile, hard to
test, and doesn't lend itself to easily extended functionality by
chaining(think unix-style piping).

I find Python's ability to return tuples virtually eliminates any need I
have to "pass by reference."

I'm coming around to the idea that wherever possible, functions should
have no side effects.  Those things that need side effects should be
isolated so they are easy to maintain.  I believe they call this "push
side effects to the edges."
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread R.Wieser
Dave,

> Can you expand on what you are trying to accomplish with this?

There is a small 433 MHz rf transmitter connected to the pin, and when I 
send the right pattern a wireless wall-wart will respond and switch a lamp 
on or off. Its just ment as an example of a real-world application of 
Python, nothing serious.

Ofcourse, by doing so I'm learning about how to use python (and the Pi) 
myself too. :-)

> It seems a small C program or library you interface python too is a better 
> solution.

:-)  I already wrote that program in C{something} (I'm not sure what my Pi 
offers by default) a while ago, but "ported" it to python.  For the above 
mentioned "example" reason.

... Which is also why I didn't even try to just shell to that program, or 
try to interface with a C{something} library.

Though doing such interfacing is in the pipeline (I've already 
found-and-stored some documentation about it).

Regards,
Rudy Wieser


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


Reading mail getting [, ...

2019-11-14 Thread Abdur-Rahmaan Janhangeer
Greetings,

Using this code to read mail. I'm printing to file only mails sent by some
people. For some mails i get the body as the below instead of actual text:

[, ]

instead of the actual mail body.

Here is the code:

#
#
import imaplib
import email
import time

my_senders = ['y...@x.com ', 'y...@y.com', 'y...@z.com']
my_mail_count = 1
open('data.txt', 'w+')
def read_email_from_gmail():
global my_mail_count, my_senders

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('mym...@gmail.com','password')
mail.select('inbox')

result, data = mail.search(None, 'ALL')
mail_ids = data[0]

id_list = mail_ids.split()
first_email_id = int(id_list[0])
latest_email_id = int(id_list[-1])

for i in range(latest_email_id,first_email_id, -1):
  #pypi  # need str(i)
result, data = mail.fetch(str(i), '(RFC822)' )

for response_part in data:
if isinstance(response_part, tuple):
# from_bytes, not from_string
msg = email.message_from_bytes(response_part[1])

email_subject = msg['subject']
email_from = msg['from']
print ('{} {}'.format(my_mail_count, email_subject))
print('{}'.format(email_from))
my_mail_count += 1

#email_body = msg.get_payload(decode=True)

for m in my_senders:
if m in email_from:
if msg.is_multipart():
for part in msg.get_payload():
print(msg.get_payload(),
file=open('data.txt', 'a'))
if isinstance(msg.get_payload(), list):
print(dir(msg.get_payload()[0]))
else:
print(msg.get_payload(), file=open('data.txt',
'a'))
if isinstance(msg.get_payload(), list):
print(dir(msg.get_payload()[0]))

read_email_from_gmail()
#
#

Any idea?

Yours,

Abdur-Rahmaan Janhangeer
pythonmembers.club  | github

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


py2 vs py3: zlib.adler32/crc32

2019-11-14 Thread Karsten Hilbert
Hi all,

I am unsure how to solve: I use adler32/crc32 to generate integer values from 
data
for setting up an advisory lock in PostgreSQL.

The PG function pg_try_advisory_lock()

  
https://www.postgresql.org/docs/12/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS

takes two PG ints which are defined as:

   integer  4 bytes typical choice for integer  -2147483648 to 
+2147483647

Now, in Py > 2.5 zlib.adler32/crc32 will return suitable integers.

However, in Py3 the return range has been changed to

   The return value is unsigned and in the range [0, 2**32-1] regardless of 
platform.

which will overflow the PostgreSQL function.

Is there a way to convert/modify/shift the py3 value such that it shows the
same representation as the py2 value ?   What I am looking for is:

  v2 = py2.zlib.adler32(data)
  v3 = some_magic(py3.zlib.adler32(data))
  if v2 == v3:
 print('same')

I am sure there's something obvious with struct/

Re: nonlocal fails ?

2019-11-14 Thread Terry Reedy

On 11/14/2019 12:53 PM, Richard Damon wrote:


On Nov 14, 2019, at 12:20 PM, R.Wieser  wrote:

MRAB,


'nonlocal' is used where the function is nested in another function


The problem is that that was not clear to me from the description - nor is
it logical to me why it exludes the main context from its use.

Regards,
Rudy Wieser


Module ‘main’ content is already available via ‘global’, nonlocal was likely 
added later to get to enclosing function scope, which isn’t global, nor is it 
local.


Correct, and the addition was in two stages.  At first, automatically 
*accessing* non-locals was added.  Note that no declaration is needed, 
just as no declaration is needed to access globals.


>>> >>> f(3)
3

The 'nonlocal' keyward to *rebind* nonlocals, analogous to the 'global' 
keyword to rebind module globals, was added later, for 3.0, after 
considerable bikeshedding  on the new keyword.


The access mechanism is quite different.  Function f accesses globals 
through f.__globals__, which points to the global dict.  In CPython, at 
least, it accesses nonlocals through f.__closure__, a tuple of 'cells'.


>>> def f(a):
b = 'b outer'
def g():
nonlocal b
print(a, b)
b = 'b inner'
print(a, b)
print(g.__closure__)
g()


>>> f(0)
(, at 0x0277AAAF7880: str object at 0x0277AAB0DAB0>)

0 b outer
0 b inner
>>> print(f.__closure__)
None

Closures are used in functional programs, instead of classes, to create 
'groups' of functions than share 'group' variables.


--
Terry Jan Reedy


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


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread Gene Heskett
On Thursday 14 November 2019 13:05:06 Dennis Lee Bieber wrote:

> On Thu, 14 Nov 2019 09:31:34 +0100, "R.Wieser" 
>
> declaimed the following:
> >What I tried to indicate is that the Pi has 500,000 cycles to work
> > with between two of those time events.   I consider that to be quite
> > a few.
>
>   But the ARM instruction set is not a 1:1 with clock cycles. Loading
> the program counter (in effect, jumps and subroutine calls) takes 5
> cycles on an older ARM 9 core. ARM apparently no longer provides
> instruction cycle data for processors (and suggests one should use
> performance counters to profile sections of code).
>
>   And then one needs to take into account that Python is a byte-code
> interpreted language, wherein an instruction may invoke whole
> subroutines of native code.
>
>   The R-Pi has never, to my knowledge, been billed as suitable for
> industrial/real-time/process-control... It was billed as a device for
> learning -- using Python and simple digital GPIO. The newer ones are
> getting closer to serving as a general desktop computer.
>
Gee I hate to burst your bubble Dennis, but I am currently running a 
cnc'd, 70 yo, 1500 lb, Sheldon 11x54 lathe with a 2GB rpi4. And if it 
wasn't for the cost of changing the interfaces, I am considering 
replacing all my intel stuff running 3 more such machines, with rpi4's. 
The pi's all use an spi interface running at several tens of megabites a 
second, where the wintels are using some variation of the old parport at 
about 5 mb/sec. I think its called progress. But at 85 the grim reaper 
has come calling twice, and blinked twice. I'll get a new aortic valve 
in December, which should lengthen my visit here, but who knows for 
sure?
>
>
> --
>   Wulfraed Dennis Lee Bieber AF6VN
>   wlfr...@ix.netcom.comhttp://wlfraed.microdiversity.freeddns.org/


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)
If we desire respect for the law, we must first make the law respectable.
 - Louis D. Brandeis
Genes Web page 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: nonlocal fails ?

2019-11-14 Thread Chris Angelico
On Fri, Nov 15, 2019 at 5:46 AM R.Wieser  wrote:
>
> Richard,
>
> > Assuming that one language works like another is a danger
>
> Abitrarily redefining words and using misnomers is another ...  ("global"
> and "nonlocal" respecivily if you wonder)

Every language that has a concept of "global" still has some sort of
limitation on it. If you look up that word in a dictionary, it won't
say "within the currently-running program" or anything. Yet, we
programmers are quite happy for global variables in one program to be
isolated from another - in fact, I think you'd be seriously
disconcerted if that were NOT the case. Is that "arbitrarily
redefining" the word global?

> > First, Python doesn't really have 'Variables' like a lot of other
> > languages
> > (they don't hold a bag of bytes), as Python names don't hold values, but
> > are just references to objects which actually hold the value
>
> That's a principle as old as programming languages itself I believe.

True, and it's also largely irrelevant here, so let's move on.

> > If the name is never bound to something, then the name will be also looked
> > for in the global namespace.
>
> Can you give an example of that ?I currently cannot wrap my head around
> what you could be meaning there - anything I can imagine simply doesn't make
> any sense ...
>

def foo():
x = 1
print("x is", x)

Inside this function, you have one local name (x), and one name
reference that isn't local (print). When the function looks for print,
it looks in the globals, and then in the built-ins.

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


Re: nonlocal fails ?

2019-11-14 Thread R.Wieser
Richard,

> Assuming that one language works like another is a danger

Abitrarily redefining words and using misnomers is another ...  ("global" 
and "nonlocal" respecivily if you wonder)

> First, Python doesn't really have 'Variables' like a lot of other 
> languages
> (they don't hold a bag of bytes), as Python names don't hold values, but
> are just references to objects which actually hold the value

That's a principle as old as programming languages itself I believe.

> If the name is never bound to something, then the name will be also looked
> for in the global namespace.

Can you give an example of that ?I currently cannot wrap my head around 
what you could be meaning there - anything I can imagine simply doesn't make 
any sense ...

Regards,
Rudy Wieser


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


Re: nonlocal fails ?

2019-11-14 Thread Richard Damon

> On Nov 14, 2019, at 12:56 PM, R.Wieser  wrote:
> 
> Jan,
> 
>> So what you want to do is dynamic scope?
> 
> No, not really.I was looking for method to let one procedure share a 
> variable with its caller - or callers, selectable by me.   And as a "by 
> reference" argument does not seem to exist in Python ...
> 
> And yes, I am a ware that procedures can return multiple results.  I just 
> didn'want to go that way (using the same variable twice in a single 
> calling).
> 
> Regards,
> Rudy Wieser

Watch out about thinking about ‘Variables’ because Python doesn’t really have 
them. In one sense EVERYTHING in Python is by reference, as names are just 
references bound to objects.

If you are pass a mutable object to a function, and the function uses the 
parameter that was bound to the object to mutate the object, that same object 
referenced in the caller has changed. (Note that strings, number, and tupples 
are not mutable, but lists, dictionaries and most class objects are).

The key is that the function should use assignment to the parameter name to try 
and change the object, but use mutating methods on the object to change it.

Thus if the caller creates a list and binds it to a name, and passes that to 
the function, then the function can manipulate the list (things like parm[0] = 
5) and that change will be see by the caller. The function just needs to be 
careful not to do a parm = statement that would rebind the name and thus lose 
the reference to the callers object.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: nonlocal fails ?

2019-11-14 Thread Rhodri James

On 14/11/2019 17:11, R.Wieser wrote:

Rhodri,


MyVar is a global here, so nonlocal explicitly doesn't pick it up.

I do not agree with you there (the variable being global).  If it where than
I would have been able to alter the variable inside the procedure without
having to resort to a "global" override (an override which is only valid for
the context its used in by the way, not anywhere else)

Than again, that is how it works in a few other languages, so I might have
been poisonned by them.:-)


You have been.

  # This is at the top level of a module
  # I.e. it's a global variable
  my_global_variable = 5

  # You can read globals from within a function without declaring them
  def show_my_global():
print(my_global_variable)

  # If you try setting it, you get a local instead
  def fudge_my_global(n):
my_global_variable = n

  show_my_global()  # prints '5'
  fudge_my_global(2)
  show_my_global()  # prints '5'

  # If you read the variable before setting it, you get an exception
  def mess_up_my_global(n):
print(my_global_variable)
my_global_variable = n

  mess_up_my_global(2) # UnboundLocalError!

  # ...because it must be a local because of the assignment, but it
  # doesn't have a value at the time print() is called.

  # To do it right, declare you want the global from the get go
  def love_my_global(n):
global my_global_variable
print("It was ", my_global_variable)
my_global_variable = n

  love_my_global(3) # prints 'It was 5'
  show_my_global()  # prints '3'

--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Re: A more

2019-11-14 Thread Terry Reedy

On 11/14/2019 10:24 AM, James Lu wrote:

Where do I go to find a more complete specification for Python?


The Cpython code, the tests, and its actual behavior.


I want to
learn about common semi-internal language features used by popular
libraries, because I am reimplementing Python.

The reference guide says:


While I am trying to be as precise as possible, I chose to use English
rather than formal specifications for everything except syntax and lexical
analysis. This should make the document more understandable to the average
reader, but will leave room for ambiguities. *Consequently, if you were
coming from Mars and tried to re-implement Python from this document alone,
you might have to guess things and in fact you would probably end up
implementing quite a different language. *


I suspect that this is less true than when Guido wrote it.  There have 
been other implementations since, and the implementers have occasionally 
asked questions that resulted in the docs being clarified.


--
Terry Jan Reedy

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


Re: nonlocal fails ?

2019-11-14 Thread R.Wieser
Michael,

> nonlocal does not share or use its *caller's* variables.  Rather it
> reaches into the scope of the outer function where it was defined.
> That's a very different concept than what you're proposing.

Oh blimy!   You're right.Its an at compile-time thing, not a runtime 
one.

Thanks for the heads-up.

> I know of no sane way that a function could work with the scope of
> any arbitrary caller.

The trick seems to be to emulate a "by reference" call, by using a mutable 
object as the argument and stuff the value inside of it (IIRC a tuple with a 
single element).

> What would happen if the caller's scope didn't have any
> names that the function was looking for?

Handle it the same as any other mistake, and throw an error ?

Regards,
Rudy Wieser


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


Re: nonlocal fails ?

2019-11-14 Thread Richard Damon
> 
> On Nov 14, 2019, at 12:20 PM, R.Wieser  wrote:
> 
> MRAB,
> 
>> 'nonlocal' is used where the function is nested in another function
> 
> The problem is that that was not clear to me from the description - nor is 
> it logical to me why it exludes the main context from its use.
> 
> Regards,
> Rudy Wieser

Module ‘main’ content is already available via ‘global’, nonlocal was likely 
added later to get to enclosing function scope, which isn’t global, nor is it 
local.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: nonlocal fails ?

2019-11-14 Thread R.Wieser
Jan,

> So what you want to do is dynamic scope?

No, not really.I was looking for method to let one procedure share a 
variable with its caller - or callers, selectable by me.   And as a "by 
reference" argument does not seem to exist in Python ...

And yes, I am a ware that procedures can return multiple results.  I just 
didn'want to go that way (using the same variable twice in a single 
calling).

Regards,
Rudy Wieser


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


Re: nonlocal fails ?

2019-11-14 Thread Richard Damon
On Nov 14, 2019, at 12:18 PM, R.Wieser  wrote:
> 
> Rhodri,
> 
>> MyVar is a global here, so nonlocal explicitly doesn't pick it up.
> 
> I do not agree with you there (the variable being global).  If it where than 
> I would have been able to alter the variable inside the procedure without 
> having to resort to a "global" override (an override which is only valid for 
> the context its used in by the way, not anywhere else)
> 
> Than again, that is how it works in a few other languages, so I might have 
> been poisonned by them. :-)
> 
> Regards,
> Rudy Wieser

Assuming that one language works like another is a danger. It really pays to 
learn the base concepts of a language if you are going to be using it.

First, Python doesn’t really have ‘Variables’ like a lot of other languages 
(they don’t hold a bag of bytes), as Python names don’t hold values, but are 
just references to objects which actually hold the value (this can be important 
when several names all reference the same object, that means that if you mutate 
the object through one name they all see the change)

Also, for name lookup, the Python Compiler looks to see if the name is bound to 
an object (via assignment, etc) in the function, if so the name is by default 
local, (changeable by using a global or non local statement). If the name is 
never bound to something, then the name will be also looked for in the global 
namespace.

Yes, this is different than many other languages.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread Rob Gaddi

On 11/13/19 1:26 PM, Dietmar Schwertberger wrote:

On 13.11.2019 21:20, R.Wieser wrote:

300us is getting on towards realtime.

Not really.  Translated to a frequency (toggeling the pin) it would be just
1.6 KHz.   Thats rather slow for an ARM machine running on 1.4 Ghz (about a
million times as fast).


It *is* real-time...
Real-time is not about speed, but about guaranteed timing.



Yeah, that's always the conversation, but at the end of the day "realtime" is 
always a question of "by how much".  Do you really need to be hard periodic with 
0 ns slop in either direction?  Can you afford to come in early but not late? 
By 10%?  By 1%?  By .01%?


If you can afford 1% and you need a 1 second interval, you're only asking for 10 
ms and in practice even a giant preemptive non-RT OS like Linux can do it for 
you.  If you can only afford 1% on a 300 us interval then your lack of rigid 
control over what happens on your processor is a real problem and you're better 
off bare metal on a dedicated $2 Cortex-M than with random timeslices of the 
1.4GHz beast on the rPi.


Is what I was shorthanding with "realtime".


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: nonlocal fails ?

2019-11-14 Thread R.Wieser
MRAB,

> 'nonlocal' is used where the function is nested in another function

The problem is that that was not clear to me from the description - nor is 
it logical to me why it exludes the main context from its use.

Regards,
Rudy Wieser


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


Re: nonlocal fails ?

2019-11-14 Thread R.Wieser
Rhodri,

> MyVar is a global here, so nonlocal explicitly doesn't pick it up.

I do not agree with you there (the variable being global).  If it where than 
I would have been able to alter the variable inside the procedure without 
having to resort to a "global" override (an override which is only valid for 
the context its used in by the way, not anywhere else)

Than again, that is how it works in a few other languages, so I might have 
been poisonned by them. :-)

Regards,
Rudy Wieser


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


Re: nonlocal fails ?

2019-11-14 Thread Michael Torrie
On 11/14/19 7:15 AM, R.Wieser wrote:

> Too bad though, it means that procedures that want to share/use its callers 
> variables using nonlocal can never be called from main.  And that a caller 
> of a procedure using nonlocal cannot have the variable declared as global 
> (just tested it).

nonlocal does not share or use its *caller's* variables.  Rather it
reaches into the scope of the outer function where it was defined.
That's a very different concept than what you're proposing.

I know of no sane way that a function could work with the scope of any
arbitrary caller.  Remember that even inner functions can be returned
and called from anywhere, even other functions or modules.  What would
happen if the caller's scope didn't have any names that the function was
looking for?

What are you trying to accomplish?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logistic Regression Define X and Y for Prediction

2019-11-14 Thread Mike C
Hi Jason,

I will try it out... Nothing in the documentation tells a person.

Thanks


From: Python-list  on behalf 
of Jason Friedman 
Sent: Wednesday, November 13, 2019 7:19 PM
Cc: python-list@python.org 
Subject: Re: Logistic Regression Define X and Y for Prediction

>
>
> When I define the X and Y values for prediction in the train and test
> data, should I capture all the columns that has been "OneHotEncoded" (that
> is all columns with 0 and 1) for the X and Y values???
>

You might have better luck asking on Stackoverflow, per the Pandas
instructions: 
https://eur03.safelinks.protection.outlook.com/?url=https%3A%2F%2Fpandas.pydata.org%2Fcommunity.html&data=02%7C01%7C%7Ce4fa0935f3b0443c3b0f08d768988e72%7C84df9e7fe9f640afb435%7C1%7C0%7C637092876737703023&sdata=%2BO6zx05Szg3TeGdtusSaLU1GhXKp7PEL7beHpqg1hcQ%3D&reserved=0.
--
https://eur03.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmail.python.org%2Fmailman%2Flistinfo%2Fpython-list&data=02%7C01%7C%7Ce4fa0935f3b0443c3b0f08d768988e72%7C84df9e7fe9f640afb435%7C1%7C0%7C637092876737703023&sdata=tDAC3St0kqFfN3rLqBBg9cTsykel5Hhj6MUjzFxZc7I%3D&reserved=0
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread Dave Cinege

Can you expand on what you are trying to accomplish with this?
It seems a small C program or library you interface python too is a 
better solution. With that said, as others mentioned you might need a 
real time OS or micro controller if this needs to be dead on timing.


Dave

On 2019/11/13 09:02, R.Wieser wrote:

Hello all,

I'm writing some code to toggle a pin on a Raspberry Pi, and would like to
have that happen at (multiples of) 300 uSec increments.

I tried time.sleep(), but that one disregards the time after the last one
ends and the new one is started.  In other words, all the time spend in code
(or being interrupted by another thread!) between the end of the previous
and the start of the current sleep throws the whole repetitive timing off.

So, I'm looking for a method that will allow me to wait for a "last time
plus increment".  Is there one with the properties of sleep() (not just
burning processor cycles way, blocking all threads), but referencing a
previous time.

Regards,
Rudy Wieser



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


A more

2019-11-14 Thread James Lu
Where do I go to find a more complete specification for Python? I want to
learn about common semi-internal language features used by popular
libraries, because I am reimplementing Python.

The reference guide says:

> While I am trying to be as precise as possible, I chose to use English
> rather than formal specifications for everything except syntax and lexical
> analysis. This should make the document more understandable to the average
> reader, but will leave room for ambiguities. *Consequently, if you were
> coming from Mars and tried to re-implement Python from this document alone,
> you might have to guess things and in fact you would probably end up
> implementing quite a different language. *
>

So I would like some additional help.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: nonlocal fails ?

2019-11-14 Thread Jan Erik Moström

On 14 Nov 2019, at 15:15, R.Wieser wrote:

Too bad though, it means that procedures that want to share/use its 
callers
variables using nonlocal can never be called from main.  And that a 
caller
of a procedure using nonlocal cannot have the variable declared as 
global

(just tested it).


So what you want to do is dynamic scope? 
https://www.geeksforgeeks.org/static-and-dynamic-scoping/


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


Re: nonlocal fails ?

2019-11-14 Thread R.Wieser
Jan,

> The nonlocal statement causes the listed identifiers to refer to 
> previously bound variables in the nearest **enclosing scope excluding 
> globals**.

I read that too, but didn't get from it that the main scope is excluded (I 
assumed the"excluding globals" was ment at as such declared variables) . 
Thanks the clarification.

Too bad though, it means that procedures that want to share/use its callers 
variables using nonlocal can never be called from main.  And that a caller 
of a procedure using nonlocal cannot have the variable declared as global 
(just tested it).

Regards,
Rudy Wieser


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


Re: nonlocal fails ?

2019-11-14 Thread Rhodri James

On 14/11/2019 13:06, R.Wieser wrote:

Hello all,

I've just tried to use a "nonlocal MyVar" statement in a procedure
defenition, but it throws an error saying "Syntax error: no binding for
nonlocal 'MyVar' found.

According to platform.python_version() I'm running version 3.8.3

Why am I getting that error ? (already googeled ofcourse)

Testcode:
- - - - - - - - - - - -
Def Proc1()
 nonlocal MyVar
 MyVar = 5

MyVar = 7
Proc1()
print(MyVar)
- - - - - - - - - - - -
I've also tried moving "MyVar = 7" to the first line, but that doesn't
change anything.  Using "global MyVar" works..


The Language Reference says 
(https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement):


"The nonlocal statement causes the listed identifiers to refer to 
previously bound variables in the nearest enclosing scope *excluding 
globals.*"  (my emphasis.)


MyVar is a global here, so nonlocal explicitly doesn't pick it up.

--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Re: nonlocal fails ?

2019-11-14 Thread MRAB

On 2019-11-14 13:06, R.Wieser wrote:

Hello all,

I've just tried to use a "nonlocal MyVar" statement in a procedure
defenition, but it throws an error saying "Syntax error: no binding for
nonlocal 'MyVar' found.

According to platform.python_version() I'm running version 3.8.3

Why am I getting that error ? (already googeled ofcourse)

Testcode:
- - - - - - - - - - - -
Def Proc1()
 nonlocal MyVar
 MyVar = 5

MyVar = 7
Proc1()
print(MyVar)
- - - - - - - - - - - -
I've also tried moving "MyVar = 7" to the first line, but that doesn't
change anything.  Using "global MyVar" works..


In section 7.13 of the Help it says:

"""The nonlocal statement causes the listed identifiers to refer to 
previously bound variables in the nearest enclosing scope excluding 
globals."""


'nonlocal' is used where the function is nested in another function and 
you want to be able to bind to the variables in the enclosing function.


In your code, there's no enclosing function. Instead, you want to be 
able to bind to the module's global variables. For that, you should use 
'global' instead.


def Proc1():
global MyVar
MyVar = 5

MyVar = 7
Proc1()
print(MyVar)
--
https://mail.python.org/mailman/listinfo/python-list


Re: nonlocal fails ?

2019-11-14 Thread Jan Erik Moström

On 14 Nov 2019, at 14:06, R.Wieser wrote:


I've also tried moving "MyVar = 7" to the first line, but that doesn't
change anything.  Using "global MyVar" works..


Try

def outer():
MyVar = 10
def Proc1():
nonlocal MyVar
MyVar = 5
Proc1()

MyVar = 7
outer()
print(MyVar)

From the documentation

The nonlocal statement causes the listed identifiers to refer to 
previously bound variables in the nearest **enclosing scope 
excluding globals**. This is important because the default behavior 
for binding is to search the local namespace first. The statement allows 
encapsulated code to rebind variables outside of the local scope besides 
the global (module) scope.


Names listed in a nonlocal statement, unlike those listed in a global 
statement, must refer to pre-existing bindings in an enclosing scope 
(the scope in which a new binding should be created cannot be determined 
unambiguously).


Names listed in a nonlocal statement must not collide with pre-existing 
bindings in the local scope.

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


nonlocal fails ?

2019-11-14 Thread R.Wieser
Hello all,

I've just tried to use a "nonlocal MyVar" statement in a procedure 
defenition, but it throws an error saying "Syntax error: no binding for 
nonlocal 'MyVar' found.

According to platform.python_version() I'm running version 3.8.3

Why am I getting that error ? (already googeled ofcourse)

Testcode:
- - - - - - - - - - - -
Def Proc1()
nonlocal MyVar
MyVar = 5

MyVar = 7
Proc1()
print(MyVar)
- - - - - - - - - - - -
I've also tried moving "MyVar = 7" to the first line, but that doesn't 
change anything.  Using "global MyVar" works..

Regards,
Rudy Wieser



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


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread R.Wieser
Dennis,

> You know... I never finished my thought there...

:-) I already got the feeling I missed something there.

> ... 1.6kHz appears to just be viable (there may still be a context
> switch but it wasn't visible on my o'scope)

Thats ... slow.And a limitation I definitily have to remember.

Than again, its Python, not Cpp or alike.

Too bad that the Pi has no free hardware that can be abused for stuff like 
this (like a serial port in synchronous mode).

Regards,
Rudy Wieser


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


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread R.Wieser
Dennis,

>  Let's see if I can remember how to use my BK Precision
> 2542 scope...

:-) You didn't have to do that.  I was already planning to put my TDS 210 
(tektronics) scope to work today, if only to see what the effect of 
drift-compensated sleeps would be (inserting some print commands here and 
there, maybe doing a search and/or grep at the same time too)

> O'scope screen grabs at:

The connection times out ...  Though that could be an effect of me using FF 
52 (on XPsp3), which seems to lack the newest encryption standards.

> I had to use the max() function in the sleep() call as it was
> periodically failing with a negative sleep value,

It does ?I was already thinking about that problem (some task might run 
longer that the delta), but imagined the sleep would than just return 
directly.   Oh well.

Regards,
Rudy Wieser


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


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread R.Wieser
Dennis,

> Avoiding drift still comes down to computing the time (in some unit)
> at which the interval is to expire, and then delaying for the difference
> between that time and current time.

Yep.   And although that can be done with Python, I had hoped to be able to 
shift all that to lower-level function to forgo the possibility that the 
calculation itself gets interrupted by task switching.

In short, I was looking for a possibly existing command that would solve 
this (imaginary?) problem, before trying to implementing it in Python 
itself.

Regards,
Rudy Wieser


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


Re: How to delay until a next increment of time occurs ?

2019-11-14 Thread R.Wieser
Dietmar,

> It *is* real-time...
> Real-time is not about speed, but about guaranteed timing.

What I tried to indicate is that the Pi has 500,000 cycles to work with 
between two of those time events.   I consider that to be quite a few.

> at least not on a  multitasking non-realtime system.

Yep, that's ofcourse the killer in this game.

Regards,
Rudy Wieser


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