Re: Supply condition in function call

2015-03-29 Thread Manuel Graune
Cameron Simpson  writes:

>
> In xterm and I think several other X11 terminals, Shift-Insert
> pastes. I found that _way_ more convenient than middle click. The
> mouse is not your friend.
>

This information might prove as useful as your answer to my
original question. ;-)

Thanks for both!

-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-29 Thread Cameron Simpson

On 28Mar2015 20:57, Steven D'Aprano  
wrote:

On Sat, 28 Mar 2015 08:19 pm, Ian Kelly wrote:

I've never been a fan of the primary selection style anyway. Copying
text is conceptually an action. Selecting text is how one indicates
the target of an action; conceptually it is not an action itself and
shouldn't cause an action to be performed. It leads to muddled
processes like "highlight this text, paste it there, highlight that
text, delete it, paste in the replacement text from before -- oops, I
accidentally pasted back in the text that I just deleted instead."


Everything you say is absolutely correct. And yet middle-click paste is so
convenient when it works that I all but cry from frustration when I find an
application that doesn't support it.


In xterm and I think several other X11 terminals, Shift-Insert pastes. I found 
that _way_ more convenient than middle click. The mouse is not your friend.


Cheers,
Cameron Simpson 

Unix is user-friendly. It's just picky about who its friends are.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-28 Thread Steven D'Aprano
On Sat, 28 Mar 2015 08:19 pm, Ian Kelly wrote:

> I've never been a fan of the primary selection style anyway. Copying
> text is conceptually an action. Selecting text is how one indicates
> the target of an action; conceptually it is not an action itself and
> shouldn't cause an action to be performed. It leads to muddled
> processes like "highlight this text, paste it there, highlight that
> text, delete it, paste in the replacement text from before -- oops, I
> accidentally pasted back in the text that I just deleted instead."

Everything you say is absolutely correct. And yet middle-click paste is so
convenient when it works that I all but cry from frustration when I find an
application that doesn't support it.



-- 
Steven

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


Re: Supply condition in function call

2015-03-28 Thread Steven D'Aprano
On Sat, 28 Mar 2015 06:50 pm, Marko Rauhamaa wrote:

> Larry Hudson :
> 
>> Highlight the selection you want copied, move the mouse cursor to the
>> location you want it copied to and middle-click with the mouse. Works
>> between programs as well as within a single program. And it copies
>> directly without going through the clipboard.
> 
> Unfortunately, Linux nowadays employs both schemes. They just couldn't
> resist the lure of the clipboard.

"Unfortunately"?

The only "unfortunately" I have with two copy/paste schemes are:

- When I am forced to use a Windows application, middle-click *never*
pastes :-(

- Certain Linux applications like OpenOffice seem to have buggy
implementations of middle-click, and sometimes fail to recognise when
you've copied something in another application. But only sometimes.



-- 
Steven

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


Re: Supply condition in function call

2015-03-28 Thread Ian Kelly
On Sat, Mar 28, 2015 at 1:50 AM, Marko Rauhamaa  wrote:
> Larry Hudson :
>
>> Highlight the selection you want copied, move the mouse cursor to the
>> location you want it copied to and middle-click with the mouse. Works
>> between programs as well as within a single program. And it copies
>> directly without going through the clipboard.

As I understand it, the primary selection and the clipboard selection
both work the same way under the hood: a client that wishes to paste
the selection requests it from the client that owns it. The clipboard
selection may be called "the clipboard" but it does not refer to an
OS-level buffer as in Windows.

> Unfortunately, Linux nowadays employs both schemes. They just couldn't
> resist the lure of the clipboard.

For good reason. Anything that can only be done with a mouse is not accessible.

I've never been a fan of the primary selection style anyway. Copying
text is conceptually an action. Selecting text is how one indicates
the target of an action; conceptually it is not an action itself and
shouldn't cause an action to be performed. It leads to muddled
processes like "highlight this text, paste it there, highlight that
text, delete it, paste in the replacement text from before -- oops, I
accidentally pasted back in the text that I just deleted instead."
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-28 Thread Marko Rauhamaa
Larry Hudson :

> Highlight the selection you want copied, move the mouse cursor to the
> location you want it copied to and middle-click with the mouse. Works
> between programs as well as within a single program. And it copies
> directly without going through the clipboard.

Unfortunately, Linux nowadays employs both schemes. They just couldn't
resist the lure of the clipboard.


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


Re: Supply condition in function call

2015-03-28 Thread Chris Angelico
On Sat, Mar 28, 2015 at 6:32 PM, Steven D'Aprano
 wrote:
>>  |  Methods defined here:
>
> This is the usual guff that help() prints when you pass it a class or type.
> Occasionally it is useful. Often it is not, especially the dunder methods.
>
> Unfortunately help's UI is rather primitive. It would be nice if it provided
> a menu of commands whereby you could hide/show dunders (hidden by default,
> perhaps), but that's an order of magnitude more complexity. It might make a
> nice third-party tool though.

This is why I would never point someone to help() as a means of
primary learning. It's great for quickly checking a function's
parameters (especially their order) when you already know what it
does. Otherwise, how do you know what to call help() on? Much more
useful to start with the online module docs, which are searchable
(unlike help(modulename), broadly speaking), and which omit all the
dunders.

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


Re: Supply condition in function call

2015-03-28 Thread Steven D'Aprano
By the way, you're not alone in recognising that Python 3 may be a little
harder to teach to beginners than Python 2. Raymond Hettinger, one of the
most respected Pythonistas around, has pointed out the same thing.

More below.


On Sat, 28 Mar 2015 12:48 am, Rustom Mody wrote:

> On Friday, March 27, 2015 at 10:05:21 AM UTC+5:30, Steven D'Aprano wrote:
>> On Fri, 27 Mar 2015 01:21 pm, Rustom Mody wrote:
>> 
>> > Anyway my point is that in python (after 2.2??) saying something is an
>> > object is a bit of a tautology -- ie verbiage without information.
>> 
>> 
>> Er, it's *always* been a tautology. Every value in Python is an object,
>> including classes, and that has been always the case.
>> 
>> However, just because it's a tautology doesn't mean it isn't useful to
>> know. (Tautologies are also known as *facts* and knowing facts is usually
>> a good thing.) For the majority of programming languages, it is not the
>> case that all values are objects, and not all people reading the
>> documentation should be expected to know that this applies to Python.
> 
> I am making a point of pedagogy not semantics.

I'm also making a point of pedagogy. You cannot possibly understand Python
without understanding the words Python programmers use to discuss Python
code, and that includes "object", a word with multiple meanings.

How can you talk about teaching people to use filter without discussing the
semantics of filter? What are you teaching them then, the way the word
looks when written down using calligraphy?

Any meaningful discussion about pedagogy cannot avoid semantics. You cannot
teach people about filter without expressing what filter is and does and
what sort of thing it returns. This is all semantics. In my opinion, once
somebody is reduced to dismissing an argument as "that's just semantics",
they've already lost, they just don't know it.


> This is help(filter) for python 2 and 3.
> 
> Python2:
> Help on built-in function filter in module __builtin__:
> 
> filter(...)
> filter(function or None, sequence) -> list, tuple, or string
> 
> Return those items of sequence for which function(item) is true.  If
> function is None, return the items that are true.  If sequence is a
> tuple or string, return the same type, else return a list.


Right. filter is Python 2 is a function, and it returns a list, tuple or
string.


> Python 3
> Help on class filter in module builtins:
> 
> class filter(object)
>  |  filter(function or None, iterable) --> filter object
>  |  
>  |  Return an iterator yielding those items of iterable for which
>  |  function(item) is true. If function is None, return the items that are
>  |  true.

Right. filter in Python 3 is a class (a.k.a. a type). Calling a type
normally returns an instance of that type, in this case a "filter object"
in the same way that calling str(x) returns a str object or list(x) returns
a list object.

Are we learning yet? :-)

filter is *more powerful* in Python 3, because it is no longer eager. It is
lazy, and returns an iterator. What sort of iterator? A *filter instance*.
We have to call it something, and Python wouldn't be improved if filter was
a function which returned a "pimwit instance". That helps neither beginners
nor experts.



>  |  Methods defined here:

This is the usual guff that help() prints when you pass it a class or type.
Occasionally it is useful. Often it is not, especially the dunder methods.

Unfortunately help's UI is rather primitive. It would be nice if it provided
a menu of commands whereby you could hide/show dunders (hidden by default,
perhaps), but that's an order of magnitude more complexity. It might make a
nice third-party tool though.



> Try and put yourself in the place of a noob:
> 
> Knows some C, not much else.

Why C? Why not somebody who knows Java and not much else, or PHP, or Ruby,
or no other programming language at all? People can come to Python from all
sorts of backgrounds. C is not and never has been a prerequisite for
learning Python. Not every programmer, or programming beginner, knows C.

Coming to Python from C is possibly the worst place to start from. Coming
from another OOP language like Ruby or Java is better, since the basic
concepts will be more familiar, although you will have to unlearn many of
the idioms and details. Having no preconceptions is even better.

Instead of a C programmer, how about a Scheme or Lisp programmer reading
help(filter) in Python 2:

"I know what Python lists, tuples and strings are, this sounds just like the
filter I know from Scheme. Easy! By the way, why is there no car and cdr
function for processing lists?"

The point being that preconceptions often need to be unlearned. If the C
programmer needs to learn what an object is, the Scheme programmer needs to
unlearn what a list is. Should we therefore decide that Python's use of the
word "list" is harmful?

(I'm hoping that you will agree that it is not, but if you wish to debate
it, I'm game.)

It's 2015

Re: Supply condition in function call

2015-03-27 Thread Rustom Mody
On Saturday, March 28, 2015 at 5:57:08 AM UTC+5:30, Larry Hudson wrote:
> On 03/26/2015 06:56 PM, Chris Angelico wrote:
> > On Fri, Mar 27, 2015 at 12:41 PM, Rustom Mody wrote:
> [snip]
> >> After selecting the line above [inside python inside help(filter) ]for
> >> cut-pasting here, by mistake I pressed Ctrl-C rather than Ctrl-Shift-C
> >> An exception was thrown and the terminal remained in some sort of raw mode
> >> even after exiting python
> >
> > Yes, confirmed. It'll be something to do with what happens when you
> > have 'less' and readline working together, probably.
> >
> > Tip: Use Ctrl-Insert rather than Ctrl-Shift-C. It's the more standard
> > keystroke anyway.
> >
> > ChrisA
> >
> It seems that many people are not aware of the standard Unix/Linux 
> middle-click copy method.
> 
> Highlight the selection you want copied, move the mouse cursor to the 
> location you want it 
> copied to and middle-click with the mouse.  Works between programs as well as 
> within a single 
> program.  And it copies directly without going through the clipboard.
> 
> I use this all the time, VERY handy.  It's been standard in Unix/Linux since 
> forever...  :-)

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


Re: Supply condition in function call

2015-03-27 Thread Larry Hudson

On 03/26/2015 06:56 PM, Chris Angelico wrote:

On Fri, Mar 27, 2015 at 12:41 PM, Rustom Mody  wrote:

[snip]

After selecting the line above [inside python inside help(filter) ]for
cut-pasting here, by mistake I pressed Ctrl-C rather than Ctrl-Shift-C
An exception was thrown and the terminal remained in some sort of raw mode
even after exiting python


Yes, confirmed. It'll be something to do with what happens when you
have 'less' and readline working together, probably.

Tip: Use Ctrl-Insert rather than Ctrl-Shift-C. It's the more standard
keystroke anyway.

ChrisA


It seems that many people are not aware of the standard Unix/Linux middle-click 
copy method.

Highlight the selection you want copied, move the mouse cursor to the location you want it 
copied to and middle-click with the mouse.  Works between programs as well as within a single 
program.  And it copies directly without going through the clipboard.


I use this all the time, VERY handy.  It's been standard in Unix/Linux since 
forever...  :-)

 -=- Larry -=-

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


Re: Supply condition in function call

2015-03-27 Thread Cameron Simpson

On 27Mar2015 21:02, Manuel Graune  wrote:

Cameron Simpson  writes:


This passes the local variables inside test1() to "condition" as a
single parameter. Now, I grant that vars['i'] is a miracle of
tediousness. So consider this elaboration:

 from collections import namedtuple

 condition_test = lambda vars: vars.i + vars.j > 4

 def test1(a, b, condition):
   for i, j in zip(a,b):
 c = i + j
 vars = locals()
 varnames = list(vars.keys())
 varstupletype = namedtuple("locals", varnames)
 varstuple = varstupletype(*[ vars[k] for k in varnames ])
 if condition(varstuple):
   print("Foo")

Here, the condition_test function/lambda uses "vars.i" and "vars.j",
which i think you'll agree is easier to read and write. The price is
the construction of a "namedtuple" to hold the variable name
values. See:

 https://docs.python.org/3/library/collections.html#collections.namedtuple



This is probably getting off topic,


I think it is on topic.


but is there any relevant difference
or benefit to using namedtuple instead of something like types.SimpleNamespace?

https://docs.python.org/3/library/types.html#additional-utility-classes-and-functions


Probably not. SimpleNamespace is much easier to construct; I hadn't thought of 
it. As the doc remarks, a namedtuple is probably better for fixed records (eg 
mapping out rows of a CSV file) because it will prevent you using the wrong 
name. But for a comparison function SimpleNamespace is probably better.


Cheers,
Cameron Simpson 

The Horn of Vengeance: When he pushes the horn button, the device produces
the sound of fingernails scraping on a blackboard, amplified beyond pain
threshold.  If that doesn't work, the horn then plays the Pina Colada song.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-27 Thread Peter Otten
Manuel Graune wrote:

> Peter Otten <__pete...@web.de> writes:
> 
>> Cameron Simpson wrote:
>>
>>>   test1([0,1,2,3], [1,2,3,4], condition_test)
>>> 
>>> This passes the local variables inside test1() to "condition" as a
>>> single parameter. Now, I grant that vars['i'] is a miracle of
>>> tediousness. So consider this elaboration:
>>> 
>>>   from collections import namedtuple
>>> 
>>>   condition_test = lambda vars: vars.i + vars.j > 4
>>> 
>>>   def test1(a, b, condition):
>>> for i, j in zip(a,b):
>>>   c = i + j
>>>   vars = locals()
>>>   varnames = list(vars.keys())
>>
>> instead or pass the list of arguments explicitly, optionally with some
>> inspect fallback:
>>
>> $ cat pass_condition_inspect.py
>> import inspect
>>
>> def test3(a, b, condition, args=None):
>> if args is None:
>> args = inspect.getargspec(condition).args
>>
>> for i, j in zip(a,b):
>> c = i + j
>> _locals = locals()
>> if condition(*[_locals[name] for name in args]):
>> print("Foo", i, j)
>>
>> def condition(c, i):
>> return i * i > c
>>
>> test3([1, 2, 3], [2, 3, 4], condition)
>> print("---")
>> # note reverse order of argument names
>> test3([1, 2, 3], [2, 3, 4], condition, ["i", "c"])
>> $ python3 pass_condition_inspect.py
>> Foo 3 4
>> ---
>> Foo 1 2
>> Foo 2 3
>> Foo 3 4
>>
> 
> I'm just comparing the different solutions. For most of them, the
> logic and the costs/benefits are pretty clear to me. Can you
> elaborate on your code? I'm not clear what you are achieving with
> explicitly passing the arguments instead of simply passing some
> variant of the complete locals()-dictionary.

Positional arguments are the most common calling convention, and the 
resulting condition() function

def condition(c, i):
   return i * i > c

looks more natural to my eye than the

def condition(d):
return d["i"] * d["i"] > d["c"]

or

def condition(s):
return d.i * d.i > d.c

variants that you have to write when you follow Cameron's suggestions. You
are basically trading cleaner condition() client functions for messier 
testX() calling code.

You might also be able to reuse functions not written specifically for that 
interface. Example using the sum() builtin:

test3([1, 2, 3], [10, 20, 30], sum, ("a", "j"))

Not that sum() makes much sense here, but I hope you get the idea...

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


Re: Supply condition in function call

2015-03-27 Thread Manuel Graune
Cameron Simpson  writes:

> This passes the local variables inside test1() to "condition" as a
> single parameter. Now, I grant that vars['i'] is a miracle of
> tediousness. So consider this elaboration:
>
>  from collections import namedtuple
>
>  condition_test = lambda vars: vars.i + vars.j > 4
>
>  def test1(a, b, condition):
>for i, j in zip(a,b):
>  c = i + j
>  vars = locals()
>  varnames = list(vars.keys())
>  varstupletype = namedtuple("locals", varnames)
>  varstuple = varstupletype(*[ vars[k] for k in varnames ])
>  if condition(varstuple):
>print("Foo")
>
> Here, the condition_test function/lambda uses "vars.i" and "vars.j",
> which i think you'll agree is easier to read and write. The price is
> the construction of a "namedtuple" to hold the variable name
> values. See:
>
>  https://docs.python.org/3/library/collections.html#collections.namedtuple
>

This is probably getting off topic, but is there any relevant difference
or benefit to using namedtuple instead of something like types.SimpleNamespace?

https://docs.python.org/3/library/types.html#additional-utility-classes-and-functions



-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-27 Thread Manuel Graune
Peter Otten <__pete...@web.de> writes:

> Cameron Simpson wrote:
>
>>   test1([0,1,2,3], [1,2,3,4], condition_test)
>> 
>> This passes the local variables inside test1() to "condition" as a single
>> parameter. Now, I grant that vars['i'] is a miracle of tediousness. So
>> consider this elaboration:
>> 
>>   from collections import namedtuple
>> 
>>   condition_test = lambda vars: vars.i + vars.j > 4
>> 
>>   def test1(a, b, condition):
>> for i, j in zip(a,b):
>>   c = i + j
>>   vars = locals()
>>   varnames = list(vars.keys())
>
> instead or pass the list of arguments explicitly, optionally with some 
> inspect fallback:
>
> $ cat pass_condition_inspect.py
> import inspect
>
> def test3(a, b, condition, args=None):
> if args is None:
> args = inspect.getargspec(condition).args
>
> for i, j in zip(a,b):
> c = i + j
> _locals = locals()
> if condition(*[_locals[name] for name in args]):
> print("Foo", i, j)
>
> def condition(c, i):
> return i * i > c
>
> test3([1, 2, 3], [2, 3, 4], condition)
> print("---")
> # note reverse order of argument names
> test3([1, 2, 3], [2, 3, 4], condition, ["i", "c"]) 
> $ python3 pass_condition_inspect.py
> Foo 3 4
> ---
> Foo 1 2
> Foo 2 3
> Foo 3 4
>

I'm just comparing the different solutions. For most of them, the
logic and the costs/benefits are pretty clear to me. Can you
elaborate on your code? I'm not clear what you are achieving with
explicitly passing the arguments instead of simply passing some
variant of the complete locals()-dictionary.


-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-27 Thread Mark Lawrence

On 27/03/2015 13:48, Rustom Mody wrote:

On Friday, March 27, 2015 at 10:05:21 AM UTC+5:30, Steven D'Aprano wrote:

On Fri, 27 Mar 2015 01:21 pm, Rustom Mody wrote:


Anyway my point is that in python (after 2.2??) saying something is an
object is a bit of a tautology -- ie verbiage without information.



Er, it's *always* been a tautology. Every value in Python is an object,
including classes, and that has been always the case.

However, just because it's a tautology doesn't mean it isn't useful to know.
(Tautologies are also known as *facts* and knowing facts is usually a good
thing.) For the majority of programming languages, it is not the case that
all values are objects, and not all people reading the documentation should
be expected to know that this applies to Python.


I am making a point of pedagogy not semantics.
This is help(filter) for python 2 and 3.

Python2:
Help on built-in function filter in module __builtin__:

filter(...)
 filter(function or None, sequence) -> list, tuple, or string

 Return those items of sequence for which function(item) is true.  If
 function is None, return the items that are true.  If sequence is a tuple
 or string, return the same type, else return a list.
--

Python 3
Help on class filter in module builtins:

class filter(object)
  |  filter(function or None, iterable) --> filter object
  |
  |  Return an iterator yielding those items of iterable for which 
function(item)
  |  is true. If function is None, return the items that are true.
  |
  |  Methods defined here:
  |
  |  __getattribute__(self, name, /)
  |  Return getattr(self, name).
  |
  |  __iter__(self, /)
  |  Implement iter(self).
  |
  |  __new__(*args, **kwargs) from builtins.type
  |  Create and return a new object.  See help(type) for accurate signature.
  |
  |  __next__(self, /)
  |  Implement next(self).
  |
  |  __reduce__(...)
  |  Return state information for pickling.


Try and put yourself in the place of a noob:

Knows some C, not much else.
Starts studying python.
Good until a point.
Then suddenly hit... map, filter, and the worst of all lambda.
More he reads less he understands.
Tries help... Gets the above.

So which do you think helps him more python 2 or 3?



Can't say it bothers me personally as I never use Python 2 any more. 
What does bother me is the stream of complaints you make about the docs 
or docstrings but there are very few if any tracker issues to get these 
things sorted.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: Supply condition in function call

2015-03-27 Thread Chris Angelico
On Sat, Mar 28, 2015 at 12:48 AM, Rustom Mody  wrote:
> Knows some C, not much else.
> Starts studying python.
> Good until a point.
> Then suddenly hit... map, filter, and the worst of all lambda.
> More he reads less he understands.
> Tries help... Gets the above.
>
> So which do you think helps him more python 2 or 3?

Python 3, because scaring someone off filter() might push him towards
comprehensions instead :)

No, seriously: I wouldn't expect anyone to be using help(filter) in
that way. Someone who knows C and not much Python is simply not going
to stumble upon filter, but will have a task/problem in mind. From
there, either the online documentation or a Q&A forum like this or
Stack Overflow will be the next port of call, not the help for one
particular function.

And frankly, if someone says "what you want is filter()" and doesn't
explain what it does, why it's useful, and why it's better than a list
comp/genexp, is doing a poor job of helping. The most common case of
filter can be trivially converted into a genexp:

filter(lambda x: some_expression, some_iterable)
(x for x in some_iterable if some_expression)

Unlike map(), filter() doesn't accept multiple iterables, so you don't
even need to worry about zip(). The only time you really need filter()
is when you're using a pre-existing function, and even then, a genexp
is often not much worse:

filter(int, list_of_strings)
(s for s in list_of_strings if int(s))

Instead of building up more and more complex nestings of map, filter,
etc, just go straight to a genexp (or a list comp, if you're about to
wrap it in list()) and add the complexity you need. Teaching a new
Python programmer about comprehensions is MUCH more useful than
teaching him/her about map and filter.

So, no. I don't think the help() difference between Py2 and Py3 is
going to be much of a problem to a new programmer who knows only C.
Maybe one who knows only LISP, but not one who knows C.

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


Re: Supply condition in function call

2015-03-27 Thread Rustom Mody
On Friday, March 27, 2015 at 10:05:21 AM UTC+5:30, Steven D'Aprano wrote:
> On Fri, 27 Mar 2015 01:21 pm, Rustom Mody wrote:
> 
> > Anyway my point is that in python (after 2.2??) saying something is an
> > object is a bit of a tautology -- ie verbiage without information.
> 
> 
> Er, it's *always* been a tautology. Every value in Python is an object,
> including classes, and that has been always the case.
> 
> However, just because it's a tautology doesn't mean it isn't useful to know.
> (Tautologies are also known as *facts* and knowing facts is usually a good
> thing.) For the majority of programming languages, it is not the case that
> all values are objects, and not all people reading the documentation should
> be expected to know that this applies to Python.

I am making a point of pedagogy not semantics.
This is help(filter) for python 2 and 3.

Python2:
Help on built-in function filter in module __builtin__:

filter(...)
filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true.  If
function is None, return the items that are true.  If sequence is a tuple
or string, return the same type, else return a list.
--

Python 3
Help on class filter in module builtins:

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |  Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |  Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |  Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |  Implement next(self).
 |  
 |  __reduce__(...)
 |  Return state information for pickling.


Try and put yourself in the place of a noob:

Knows some C, not much else.
Starts studying python.
Good until a point.
Then suddenly hit... map, filter, and the worst of all lambda.
More he reads less he understands.
Tries help... Gets the above.

So which do you think helps him more python 2 or 3?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-27 Thread Dave Angel

On 03/26/2015 09:41 PM, Rustom Mody wrote:

On Thursday, March 26, 2015 at 11:30:57 AM UTC+5:30, Chris Angelico wrote:



Python 3.5.0a0 (default:4709290253e3, Jan 20 2015, 21:48:07)
[GCC 4.7.2] on linux

class filter(object)
  |  filter(function or None, iterable) --> filter object
  |
  |  Return an iterator yielding those items of iterable for which 
function(item)
  |  is true. If function is None, return the items that are true.
  |
  |  Methods defined here:


...


On a more specific note, its the 1st line:

class filter(object)

which knocks me off.
If a more restricted type from the ABC was shown which exactly captures all
the iterator-specific stuff like __iter__, __next__ it would sure help (me)



Since it's not actually derived from anything else, I'd leave that part 
alone.  But it could be useful to add something like:


ducktype: collections.abc.Iterable

if nothing else, it'd get beginners to the language to start thinking 
more of what duck typing is, in Python.


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


Re: Supply condition in function call

2015-03-26 Thread Steven D'Aprano
On Fri, 27 Mar 2015 01:21 pm, Rustom Mody wrote:

> Anyway my point is that in python (after 2.2??) saying something is an
> object is a bit of a tautology -- ie verbiage without information.


Er, it's *always* been a tautology. Every value in Python is an object,
including classes, and that has been always the case.

However, just because it's a tautology doesn't mean it isn't useful to know.
(Tautologies are also known as *facts* and knowing facts is usually a good
thing.) For the majority of programming languages, it is not the case that
all values are objects, and not all people reading the documentation should
be expected to know that this applies to Python.

Besides, "object" in Python circles is ambiguous. It can also mean:

* the Python type "object";

* an instance of the Python type "object";

* any non-class instance of any old-style class (Python 2 only) 
  or type (new-style class);

* "boxed" values in object-oriented languages;

and possibly others as well. Personally, I dislike using object as a synonym
for "instance", as it fails to account for classes which are instances. But
other than that, all those meanings are valid and have to be distinguished
from context.





-- 
Steven

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


Re: Supply condition in function call

2015-03-26 Thread Rustom Mody
On Friday, March 27, 2015 at 7:56:16 AM UTC+5:30, Ian wrote:
> On Thu, Mar 26, 2015 at 7:56 PM, Chris Angelico  wrote:
> >> On a more specific note, its the 1st line:
> >>
> >> class filter(object)
> >>
> >> which knocks me off.
> >> If a more restricted type from the ABC was shown which exactly captures all
> >> the iterator-specific stuff like __iter__, __next__ it would sure help (me)
> >
> > But there's no point in subclassing for everything. In this case,
> > filter doesn't subclass anything but object, so there's no value in
> > stating anything else. You want to know if it's iterable? Check for an
> > __iter__ method. Etcetera.
> 
> Also, filter is a builtin, while collections.abc.Iterable is in a
> library module written in Python, so there's a bootstrapping problem
> with having the one inherit from the other.

As I said to Chris, I am not talking of the facts but of the docs
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-26 Thread Rustom Mody
On Friday, March 27, 2015 at 7:26:54 AM UTC+5:30, Chris Angelico wrote:
> On Fri, Mar 27, 2015 at 12:41 PM, Rustom Mody  wrote:
> > On a more specific note, its the 1st line:
> >
> > class filter(object)
> >
> > which knocks me off.
> > If a more restricted type from the ABC was shown which exactly captures all
> > the iterator-specific stuff like __iter__, __next__ it would sure help (me)
> 
> But there's no point in subclassing for everything. In this case,
> filter doesn't subclass anything but object, so there's no value in
> stating anything else. You want to know if it's iterable? Check for an
> __iter__ method. Etcetera.

Well maybe... I dont the ABC thing very well in python.
[It does seem to be underutilized]

Anyway my point is that in python (after 2.2??) saying something is an object 
is a bit of a tautology -- ie verbiage without information.


Note: We are not talking of the *fact* that something -- in this case filter --
subclasses object, but the output of help(filter)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-26 Thread Ian Kelly
On Thu, Mar 26, 2015 at 7:56 PM, Chris Angelico  wrote:
>> On a more specific note, its the 1st line:
>>
>> class filter(object)
>>
>> which knocks me off.
>> If a more restricted type from the ABC was shown which exactly captures all
>> the iterator-specific stuff like __iter__, __next__ it would sure help (me)
>
> But there's no point in subclassing for everything. In this case,
> filter doesn't subclass anything but object, so there's no value in
> stating anything else. You want to know if it's iterable? Check for an
> __iter__ method. Etcetera.

Also, filter is a builtin, while collections.abc.Iterable is in a
library module written in Python, so there's a bootstrapping problem
with having the one inherit from the other.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-26 Thread Chris Angelico
On Fri, Mar 27, 2015 at 12:41 PM, Rustom Mody  wrote:
> On Thursday, March 26, 2015 at 11:30:57 AM UTC+5:30, Chris Angelico wrote:
>> On Thu, Mar 26, 2015 at 3:02 PM, Rustom Mody  wrote:
>> > [And BTW
>> > help(filter) in python2 is much better documention than in python3
>> > ]
>>
>> Python 2.7.3 (default, Mar 13 2014, 11:03:55)
>> [GCC 4.7.2] on linux2
>>
>> filter(...)
>> filter(function or None, sequence) -> list, tuple, or string
>>
>> Return those items of sequence for which function(item) is true.  If
>> function is None, return the items that are true.  If sequence is a tuple
>> or string, return the same type, else return a list.
>>
>> Python 3.5.0a0 (default:4709290253e3, Jan 20 2015, 21:48:07)
>> [GCC 4.7.2] on linux
>>
>> class filter(object)
>>  |  filter(function or None, iterable) --> filter object
>>  |
>>  |  Return an iterator yielding those items of iterable for which 
>> function(item)
>>  |  is true. If function is None, return the items that are true.
>>  |
>>  |  Methods defined here:
>> (chomp a handful of method details)
>
> Sackful may be more accurate :-)

Not really. Here's the entire help(filter) text:

Help on class filter in module builtins:

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 |
 |  Methods defined here:
 |
 |  __getattribute__(self, name, /)
 |  Return getattr(self, name).
 |
 |  __iter__(self, /)
 |  Implement iter(self).
 |
 |  __new__(*args, **kwargs) from builtins.type
 |  Create and return a new object.  See help(type) for accurate signature.
 |
 |  __next__(self, /)
 |  Implement next(self).
 |
 |  __reduce__(...)
 |  Return state information for pickling.


> On a different note... I wonder how you do it:
> Look at 300 lines of code and notice exactly those 3 that... um... cause
> a lot of trouble :-)
> [My eyes just glaze over]

That's called experience. It's an intrinsic part of being a programmer.

> On a more specific note, its the 1st line:
>
> class filter(object)
>
> which knocks me off.
> If a more restricted type from the ABC was shown which exactly captures all
> the iterator-specific stuff like __iter__, __next__ it would sure help (me)

But there's no point in subclassing for everything. In this case,
filter doesn't subclass anything but object, so there's no value in
stating anything else. You want to know if it's iterable? Check for an
__iter__ method. Etcetera.

> On a 3rd note: I think Ive found a little buglet while trying to post this 
> message, can you confirm?
> [Linux Debian Xfce]
>
> After selecting the line above [inside python inside help(filter) ]for
> cut-pasting here, by mistake I pressed Ctrl-C rather than Ctrl-Shift-C
> An exception was thrown and the terminal remained in some sort of raw mode
> even after exiting python

Yes, confirmed. It'll be something to do with what happens when you
have 'less' and readline working together, probably.

Tip: Use Ctrl-Insert rather than Ctrl-Shift-C. It's the more standard
keystroke anyway.

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


Re: Supply condition in function call

2015-03-26 Thread Rustom Mody
On Thursday, March 26, 2015 at 11:30:57 AM UTC+5:30, Chris Angelico wrote:
> On Thu, Mar 26, 2015 at 3:02 PM, Rustom Mody  wrote:
> > [And BTW
> > help(filter) in python2 is much better documention than in python3
> > ]
> 
> Python 2.7.3 (default, Mar 13 2014, 11:03:55)
> [GCC 4.7.2] on linux2
> 
> filter(...)
> filter(function or None, sequence) -> list, tuple, or string
> 
> Return those items of sequence for which function(item) is true.  If
> function is None, return the items that are true.  If sequence is a tuple
> or string, return the same type, else return a list.
> 
> Python 3.5.0a0 (default:4709290253e3, Jan 20 2015, 21:48:07)
> [GCC 4.7.2] on linux
> 
> class filter(object)
>  |  filter(function or None, iterable) --> filter object
>  |
>  |  Return an iterator yielding those items of iterable for which 
> function(item)
>  |  is true. If function is None, return the items that are true.
>  |
>  |  Methods defined here:
> (chomp a handful of method details)

Sackful may be more accurate :-)

On a different note... I wonder how you do it:
Look at 300 lines of code and notice exactly those 3 that... um... cause 
a lot of trouble :-)
[My eyes just glaze over]

On a more specific note, its the 1st line:

class filter(object)

which knocks me off.
If a more restricted type from the ABC was shown which exactly captures all
the iterator-specific stuff like __iter__, __next__ it would sure help (me)

On a 3rd note: I think Ive found a little buglet while trying to post this 
message, can you confirm?
[Linux Debian Xfce]

After selecting the line above [inside python inside help(filter) ]for
cut-pasting here, by mistake I pressed Ctrl-C rather than Ctrl-Shift-C
An exception was thrown and the terminal remained in some sort of raw mode
even after exiting python
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-26 Thread Cameron Simpson

On 26Mar2015 11:37, Peter Otten <__pete...@web.de> wrote:

You are right. [...]

By the way, in this case you don't need the list at all:

def vartuple(vars):
   return namedtuple("locals", vars)._make(vars.values())


Hmm. Neat. I had not realised that was available.

You'd need "vars.keys()", not "vars", for the first use of "vars", BTW:

 return namedtuple("locals", vars.keys())._make(vars.values())

A remark for the OP: a method name like "_make" would normally be something you 
would avoid as it is Python convenion that _* names are "private", which in 
Python usually means subject to arbitrary change and probably not documented; 
internal implementation mechanisms as opposed to published interfaces.


However, in namedtuple the word "_make" is chosen specificly to avoid clashes 
with the "named" tuple values (which would normally not start with "_"), and it 
is explicitly documented.


Thanks Peter!

Cheers,
Cameron Simpson 

Nothing is impossible for the man who doesn't have to do it.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-26 Thread Grant Edwards
On 2015-03-25, Ian Kelly  wrote:
> On Wed, Mar 25, 2015 at 1:53 PM, Grant Edwards  
> wrote:
>> On 2015-03-25, Ian Kelly  wrote:
>>> On Wed, Mar 25, 2015 at 11:29 AM, Manuel Graune  
>>> wrote:
>>>
 I'm looking for a way to supply a condition to an if-statement inside a
 function body when calling the function. I can sort of get what I want
 with using eval [...]
>>>
>>> Pass the condition as a function.
>>>
>>> def test1(a, b, condition=lambda i, j: True):
>>> for i,j in zip(a,b):
>>> c=i+j
>>> if condition(i, j):
>>> print("Foo")
>>>
>>> test1([0,1,2,3],[1,2,3,4], lambda i, j: i+j > 4)
>>> # etc.
>>
>> FWIW, back in the day such a function was referred to as a "thunk"
>> (particularly if it was auto-generated by a compiler that used
>> pass-by-name instead of pass-by-value or pass-by-reference):
>>
>>   http://en.wikipedia.org/wiki/Thunk
>>
>> Dunno if people still use that term or not.
>
> I've heard the term (though not since my college days, I think), but
> I've always understood thunks to be parameterless (hence the use as a
> form of pass-by-name).

You're right -- I misread the example. Somehow I skipped the "for i,j"
line completely, and was thinking that i and j were defined in the
caller's context. Thus the OP was trying to implment something akin to
call by name.

-- 
Grant Edwards   grant.b.edwardsYow! Here I am in the
  at   POSTERIOR OLFACTORY LOBULE
  gmail.combut I don't see CARL SAGAN
   anywhere!!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-26 Thread Peter Otten
Cameron Simpson wrote:

> On 26Mar2015 10:03, Peter Otten <__pete...@web.de> wrote:
>>Cameron Simpson wrote:
>>>   vars = locals()
>>>   varnames = list(vars.keys())
>>
>>That leaves varnames in undefined order. Consider
>>
>>varnames = sorted(vars)
> 
> Actually, not necessary.
> 
> I started with sorted, but it is irrelevant, so I backed off to "list" to
> avoid introducing an unwarranted implication, in fact precisely the
> implicaion you are making.
> 
> The only requirement, which I mentioned, is that the values used to
> initialise the namedtuple are supplied in the same order as the tuple
> field names, so all that is needed is to suck the .keys() out once and use
> them in the same order when we construct the namedtuple. Hence just a
> list.

You are right. 

Once I spotted the "error" I failed to notice that you pass the named tuple 
as a single argument, i. e. condition(nt), not condition(*nt) :(

By the way, in this case you don't need the list at all:

def vartuple(vars):
return namedtuple("locals", vars)._make(vars.values())


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


Re: Supply condition in function call

2015-03-26 Thread Cameron Simpson

On 26Mar2015 10:03, Peter Otten <__pete...@web.de> wrote:

Cameron Simpson wrote:

  vars = locals()
  varnames = list(vars.keys())


That leaves varnames in undefined order. Consider

varnames = sorted(vars)


Actually, not necessary.

I started with sorted, but it is irrelevant, so I backed off to "list" to avoid 
introducing an unwarranted implication, in fact precisely the implicaion you 
are making.


The only requirement, which I mentioned, is that the values used to initialise 
the namedtuple are supplied in the same order as the tuple field names, so all 
that is needed is to suck the .keys() out once and use them in the same order 
when we construct the namedtuple. Hence just a list.


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


Re: Supply condition in function call

2015-03-26 Thread Peter Otten
Cameron Simpson wrote:

> On 26Mar2015 07:27, Manuel Graune  wrote:
>>Gary Herron  writes:
>>> On 03/25/2015 10:29 AM, Manuel Graune wrote:
 def test1(a, b, condition="True"):
  for i,j in zip(a,b):
  c=i+j
  if eval(condition):
 print("Foo")

 test1([0,1,2,3],[1,2,3,4],"i+j >4")
 print("Bar")
 test1([0,1,2,3],[1,2,3,4],"c >4")
 print("Bar")
 test1([0,1,2,3],[1,2,3,4],"a[i] >2")
>>>
>>> This is nicely done with lambda expressions:
>>>
>>> To pass in a condition as a function:
>>>test1([0,1,2,3],[1,2,3,4], lambda i,j: i+j<4)
>>>
>>> To check the condition in the function:
>>> if condition(i,j):
>>
>>This seems to be the right direction and a good solution for simple
>>cases. Unfortunately this:
>>
>>> To get the full range of conditions, you will need to include all the
>>> variables needed by any condition you can imagine.  So the above
>>> suggestions may need to be expanded to:
>>>  ... lambda i,j,a,b: ... or whatever
>>>
>>> and
>>>   ... condition(i,j,a,b) ... or whatever
>>>
>>
>>is not as concise as I had hoped for. Is there a possibility to do
>>(maybe with a helper function inside the main function's body) solve
>>this more elegantly? I'm thinking of some combination of e. g. **kwargs,
>>dir() and introspection.
> 
> Yes.
> 
> Consider locals():
> 
>   https://docs.python.org/3/library/functions.html#locals
> 
> which is a built in function returning a copy of the current local
> variables in a dict. Example:
> 
>   condition_test = lambda vars: vars['i'] + vars[j'] > 4
> 
>   def test1(a, b, condition):
> for i, j in zip(a,b):
>   c = i + j
>   if condition(locals()):
> print("Foo")
> 
>   test1([0,1,2,3], [1,2,3,4], condition_test)
> 
> This passes the local variables inside test1() to "condition" as a single
> parameter. Now, I grant that vars['i'] is a miracle of tediousness. So
> consider this elaboration:
> 
>   from collections import namedtuple
> 
>   condition_test = lambda vars: vars.i + vars.j > 4
> 
>   def test1(a, b, condition):
> for i, j in zip(a,b):
>   c = i + j
>   vars = locals()
>   varnames = list(vars.keys())

That leaves varnames in undefined order. Consider

varnames = sorted(vars)

instead or pass the list of arguments explicitly, optionally with some 
inspect fallback:

$ cat pass_condition_inspect.py
import inspect

def test3(a, b, condition, args=None):
if args is None:
args = inspect.getargspec(condition).args

for i, j in zip(a,b):
c = i + j
_locals = locals()
if condition(*[_locals[name] for name in args]):
print("Foo", i, j)

def condition(c, i):
return i * i > c

test3([1, 2, 3], [2, 3, 4], condition)
print("---")
# note reverse order of argument names
test3([1, 2, 3], [2, 3, 4], condition, ["i", "c"]) 
$ python3 pass_condition_inspect.py
Foo 3 4
---
Foo 1 2
Foo 2 3
Foo 3 4

A simpler alternative is changing the signature of condition() and passing 
keyword arguments:

$ cat pass_condition.py
def test2(a, b, condition):
for i, j in zip(a,b):
c = i + j
if condition(**locals()):
print("Foo", i, j)

def condition(c, i, **unused):
return i * i > c

test2([1, 2, 3], [2, 3, 4], condition)
$ python3 pass_condition.py 
Foo 3 4

Creating a locals() dict on every iteration is still costly, and personally 
I would prefer the tighter interface where you pass a limited set of 
arguments explicitly.

>   varstupletype = namedtuple("locals", varnames)
>   varstuple = varstupletype(*[ vars[k] for k in varnames ])
>   if condition(varstuple):
> print("Foo")
> 
> Here, the condition_test function/lambda uses "vars.i" and "vars.j", which
> i think you'll agree is easier to read and write. The price is the
> construction of a "namedtuple" to hold the variable name values. See:
> 
>   
https://docs.python.org/3/library/collections.html#collections.namedtuple
> 
> So the (untested) code above:
> 
>   - get the locals() as before
>   - get the names of the variables; it is important to have this in a
>   array because we need to access the values in the same order when we
>   make the tuple - make a new namedtuple class "varstupletype", which is
>   used to make the named tuple - make the named tuple itself with the
>   values of the variables in order
> 
> If you're writing a lot of test functions like test1 you can push the
> namedtuple stuff off into a helper function:
> 
>   def vartuple(vars):
> varnames = list(vars.keys())
> varstupletype = namedtuple("locals", varnames)
> varstuple = varstupletype(*[ vars[k] for k in varnames ])
> return varstuple
> 
> and then "test1()" can look like this:
> 
>   def test1(a, b, condition):
> for i, j in zip(a,b):
>   c = i + j
>   if condition(vartuple(locals())):
> print("Foo")
> 
> which makes it much easier to write test2 and so on later.


-- 
https://mail.python.org/mailman/lis

Re: Supply condition in function call

2015-03-26 Thread Cameron Simpson

On 26Mar2015 07:27, Manuel Graune  wrote:

Gary Herron  writes:

On 03/25/2015 10:29 AM, Manuel Graune wrote:

def test1(a, b, condition="True"):
 for i,j in zip(a,b):
 c=i+j
 if eval(condition):
print("Foo")

test1([0,1,2,3],[1,2,3,4],"i+j >4")
print("Bar")
test1([0,1,2,3],[1,2,3,4],"c >4")
print("Bar")
test1([0,1,2,3],[1,2,3,4],"a[i] >2")


This is nicely done with lambda expressions:

To pass in a condition as a function:
   test1([0,1,2,3],[1,2,3,4], lambda i,j: i+j<4)

To check the condition in the function:
if condition(i,j):


This seems to be the right direction and a good solution for simple
cases. Unfortunately this:


To get the full range of conditions, you will need to include all the variables 
needed by any condition you can imagine.  So the above suggestions may need to 
be expanded to:
 ... lambda i,j,a,b: ... or whatever

and
  ... condition(i,j,a,b) ... or whatever



is not as concise as I had hoped for. Is there a possibility to do
(maybe with a helper function inside the main function's body) solve
this more elegantly? I'm thinking of some combination of e. g. **kwargs,
dir() and introspection.


Yes.

Consider locals():

 https://docs.python.org/3/library/functions.html#locals

which is a built in function returning a copy of the current local variables in 
a dict. Example:


 condition_test = lambda vars: vars['i'] + vars[j'] > 4

 def test1(a, b, condition):
   for i, j in zip(a,b):
 c = i + j
 if condition(locals()):
   print("Foo")

 test1([0,1,2,3], [1,2,3,4], condition_test)

This passes the local variables inside test1() to "condition" as a single 
parameter. Now, I grant that vars['i'] is a miracle of tediousness. So consider 
this elaboration:


 from collections import namedtuple

 condition_test = lambda vars: vars.i + vars.j > 4

 def test1(a, b, condition):
   for i, j in zip(a,b):
 c = i + j
 vars = locals()
 varnames = list(vars.keys())
 varstupletype = namedtuple("locals", varnames)
 varstuple = varstupletype(*[ vars[k] for k in varnames ])
 if condition(varstuple):
   print("Foo")

Here, the condition_test function/lambda uses "vars.i" and "vars.j", which i 
think you'll agree is easier to read and write. The price is the construction 
of a "namedtuple" to hold the variable name values. See:


 https://docs.python.org/3/library/collections.html#collections.namedtuple

So the (untested) code above:

 - get the locals() as before
 - get the names of the variables; it is important to have this in a array 
because we need to access the values in the same order when we make the tuple
 - make a new namedtuple class "varstupletype", which is used to make the named 
tuple
 - make the named tuple itself with the values of the variables in order

If you're writing a lot of test functions like test1 you can push the 
namedtuple stuff off into a helper function:


 def vartuple(vars):
   varnames = list(vars.keys())
   varstupletype = namedtuple("locals", varnames)
   varstuple = varstupletype(*[ vars[k] for k in varnames ])
   return varstuple

and then "test1()" can look like this:

 def test1(a, b, condition):
   for i, j in zip(a,b):
 c = i + j
 if condition(vartuple(locals())):
   print("Foo")

which makes it much easier to write test2 and so on later.

Does this help?

Cheers,
Cameron Simpson 

Your reality is lies and balderdash, and I'm glad to say that I have no grasp
of it.  - Baron Munchausen
--
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-25 Thread Manuel Graune
Gary Herron  writes:

> On 03/25/2015 10:29 AM, Manuel Graune wrote:
>>
>> def test1(a, b, condition="True"):
>>  for i,j in zip(a,b):
>>  c=i+j
>>  if eval(condition):
>> print("Foo")
>>
>> test1([0,1,2,3],[1,2,3,4],"i+j >4")
>> print("Bar")
>> test1([0,1,2,3],[1,2,3,4],"c >4")
>> print("Bar")
>> test1([0,1,2,3],[1,2,3,4],"a[i] >2")
>>
>
> This is nicely done with lambda expressions:
>
> To pass in a condition as a function:
>test1([0,1,2,3],[1,2,3,4], lambda i,j: i+j<4)
>
> To check the condition in the function:
> if condition(i,j):

This seems to be the right direction and a good solution for simple
cases. Unfortunately this:

> To get the full range of conditions, you will need to include all the 
> variables needed by any condition you can imagine.  So the above suggestions 
> may need to be expanded to:
>  ... lambda i,j,a,b: ... or whatever
>
> and
>   ... condition(i,j,a,b) ... or whatever
>

is not as concise as I had hoped for. Is there a possibility to do
(maybe with a helper function inside the main function's body) solve
this more elegantly? I'm thinking of some combination of e. g. **kwargs,
dir() and introspection.

Regards,

Manuel



-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-25 Thread Chris Angelico
On Thu, Mar 26, 2015 at 3:02 PM, Rustom Mody  wrote:
> [And BTW
> help(filter) in python2 is much better documention than in python3
> ]

Python 2.7.3 (default, Mar 13 2014, 11:03:55)
[GCC 4.7.2] on linux2

filter(...)
filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true.  If
function is None, return the items that are true.  If sequence is a tuple
or string, return the same type, else return a list.

Python 3.5.0a0 (default:4709290253e3, Jan 20 2015, 21:48:07)
[GCC 4.7.2] on linux

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 |
 |  Methods defined here:
(chomp a handful of method details)

Looks pretty comparable to me. Py2 clearly stipulates that it's a
function that returns a tuple, string, or list. Py3 defines it as a
class, and then describes what it does (it's an iterator) and then its
methods.

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


Re: Supply condition in function call

2015-03-25 Thread Rustom Mody
On Thursday, March 26, 2015 at 12:44:03 AM UTC+5:30, Gary Herron wrote:
> On 03/25/2015 10:29 AM, Manuel Graune wrote:
> > Hi,
> >
> > I'm looking for a way to supply a condition to an if-statement inside a
> > function body when calling the function. I can sort of get what I want
> > with using eval (see code below) but I would like to achieve this in a
> > safer way. If there is a solution which is safer while being
> > less flexible, that would be fine. Also, supplying the condition as a
> > string is not necessary. What I want to do is basically like this:
> >
> > def test1(a, b, condition="True"):
> >  for i,j in zip(a,b):
> >  c=i+j
> >  if eval(condition):
> > print("Foo")
> >
> > test1([0,1,2,3],[1,2,3,4],"i+j >4")
> > print("Bar")
> > test1([0,1,2,3],[1,2,3,4],"c >4")
> > print("Bar")
> > test1([0,1,2,3],[1,2,3,4],"a[i] >2")
> > print("Bar")
> > test1([0,1,2,3],[1,2,3,4])
> >
> >
> 
> This is nicely done with lambda expressions:

The builtin function filter is for this (more or less).
Comprehensions are usually better than filter.

[And BTW
help(filter) in python2 is much better documention than in python3
]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-25 Thread Ian Kelly
On Wed, Mar 25, 2015 at 1:53 PM, Grant Edwards  wrote:
> On 2015-03-25, Ian Kelly  wrote:
>> On Wed, Mar 25, 2015 at 11:29 AM, Manuel Graune  
>> wrote:
>>
>>> I'm looking for a way to supply a condition to an if-statement inside a
>>> function body when calling the function. I can sort of get what I want
>>> with using eval [...]
>>
>> Pass the condition as a function.
>>
>> def test1(a, b, condition=lambda i, j: True):
>> for i,j in zip(a,b):
>> c=i+j
>> if condition(i, j):
>> print("Foo")
>>
>> test1([0,1,2,3],[1,2,3,4], lambda i, j: i+j > 4)
>> # etc.
>
> FWIW, back in the day such a function was referred to as a "thunk"
> (particularly if it was auto-generated by a compiler that used
> pass-by-name instead of pass-by-value or pass-by-reference):
>
>   http://en.wikipedia.org/wiki/Thunk
>
> Dunno if people still use that term or not.

I've heard the term (though not since my college days, I think), but
I've always understood thunks to be parameterless (hence the use as a
form of pass-by-name).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-25 Thread Grant Edwards
On 2015-03-25, Ian Kelly  wrote:
> On Wed, Mar 25, 2015 at 11:29 AM, Manuel Graune  
> wrote:
>
>> I'm looking for a way to supply a condition to an if-statement inside a
>> function body when calling the function. I can sort of get what I want
>> with using eval [...]
>
> Pass the condition as a function.
>
> def test1(a, b, condition=lambda i, j: True):
> for i,j in zip(a,b):
> c=i+j
> if condition(i, j):
> print("Foo")
>
> test1([0,1,2,3],[1,2,3,4], lambda i, j: i+j > 4)
> # etc.

FWIW, back in the day such a function was referred to as a "thunk"
(particularly if it was auto-generated by a compiler that used
pass-by-name instead of pass-by-value or pass-by-reference):

  http://en.wikipedia.org/wiki/Thunk

Dunno if people still use that term or not.

-- 
Grant Edwards   grant.b.edwardsYow! I'm RELIGIOUS!!
  at   I love a man with
  gmail.coma HAIRPIECE!!  Equip me
   with MISSILES!!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-25 Thread Gary Herron

On 03/25/2015 10:29 AM, Manuel Graune wrote:

Hi,

I'm looking for a way to supply a condition to an if-statement inside a
function body when calling the function. I can sort of get what I want
with using eval (see code below) but I would like to achieve this in a
safer way. If there is a solution which is safer while being
less flexible, that would be fine. Also, supplying the condition as a
string is not necessary. What I want to do is basically like this:

def test1(a, b, condition="True"):
 for i,j in zip(a,b):
 c=i+j
 if eval(condition):
print("Foo")

test1([0,1,2,3],[1,2,3,4],"i+j >4")
print("Bar")
test1([0,1,2,3],[1,2,3,4],"c >4")
print("Bar")
test1([0,1,2,3],[1,2,3,4],"a[i] >2")
print("Bar")
test1([0,1,2,3],[1,2,3,4])




This is nicely done with lambda expressions:

To pass in a condition as a function:
   test1([0,1,2,3],[1,2,3,4], lambda i,j: i+j<4)

To check the condition in the function:
if condition(i,j):

To get the full range of conditions, you will need to include all the variables 
needed by any condition you can imagine.  So the above suggestions may need to 
be expanded to:
 ... lambda i,j,a,b: ... or whatever

and
  ... condition(i,j,a,b) ... or whatever

If any of your conditions gets too long/complex for a lambda (or you just don't 
like Python's lambda expressions), then just create a function for your 
condition:

  def cond1(i,j,a,b):
  return i+j>4

and do
   test1(..., cond1)
and
if condition(i,j,a,b):




--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

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


Re: Supply condition in function call

2015-03-25 Thread Terry Reedy

On 3/25/2015 1:29 PM, Manuel Graune wrote:

Hi,

I'm looking for a way to supply a condition to an if-statement inside a
function body when calling the function. I can sort of get what I want
with using eval (see code below) but I would like to achieve this in a
safer way. If there is a solution which is safer while being
less flexible, that would be fine. Also, supplying the condition as a
string is not necessary. What I want to do is basically like this:

def test1(a, b, condition="True"):
 for i,j in zip(a,b):
 c=i+j
 if eval(condition):
print("Foo")


The standard solution to the above is to have a boolean parameter, such 
as print_wanted=False.



test1([0,1,2,3],[1,2,3,4],"i+j >4")
print("Bar")


For this, follow Ian's suggestion of passing a predicate function.

--
Terry Jan Reedy

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


Re: Supply condition in function call

2015-03-25 Thread Joel Goldstick
On Wed, Mar 25, 2015 at 2:22 PM, Ian Kelly  wrote:
> On Wed, Mar 25, 2015 at 12:17 PM, Joel Goldstick
>  wrote:
>> Oh, now I see.  Do you know about this:
>> https://docs.python.org/2/library/ast.html#ast.literal_eval
>
> As the name suggests, that only evals literals. It won't work for
> complex expressions like "i + j > 4"
> --
Thanks Ian, sorry for the misdirection ...
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-25 Thread Ian Kelly
On Wed, Mar 25, 2015 at 12:17 PM, Joel Goldstick
 wrote:
> Oh, now I see.  Do you know about this:
> https://docs.python.org/2/library/ast.html#ast.literal_eval

As the name suggests, that only evals literals. It won't work for
complex expressions like "i + j > 4"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-25 Thread Joel Goldstick
On Wed, Mar 25, 2015 at 1:51 PM, Manuel Graune  wrote:
> Joel Goldstick  writes:
>
>> On Wed, Mar 25, 2015 at 1:29 PM, Manuel Graune  
>> wrote:
>>>
>>> def test1(a, b, condition="True"):
>>> for i,j in zip(a,b):
>>> c=i+j
>>> if eval(condition):
>>>print("Foo")
>>>
>> I'm not sure I understand your question, but condition will evaluate
>> to True or False regardless, so:
>>  if condition:
>> print ("Foo")
>>  else:
>> print ("Bar")
>>
>
> The point is (see examples below) to specify the condition that is to be
> evaluated when calling the function (as opposed to when stating the function).
>
>> eval can be dangerous as someone could put some unknown command with
>> side effects in condition
>>
>
> I know that. That's why I'm looking for an alternative. ;-)

Oh, now I see.  Do you know about this:
https://docs.python.org/2/library/ast.html#ast.literal_eval


>
>>> test1([0,1,2,3],[1,2,3,4],"i+j >4")
>>> print("Bar")
>>> test1([0,1,2,3],[1,2,3,4],"c >4")
>>> print("Bar")
>>> test1([0,1,2,3],[1,2,3,4],"a[i] >2")
>>>
>>> Resulting in
>>>
>>> Foo
>>> Foo
>>> Bar
>>> Foo
>>> Foo
>>> Bar
>>> Foo
>
> Regards,
>
> Manuel
>
> --
> A hundred men did the rational thing. The sum of those rational choices was
> called panic. Neal Stephenson -- System of the world
> http://www.graune.org/GnuPG_pubkey.asc
> Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-25 Thread Manuel Graune
Joel Goldstick  writes:

> On Wed, Mar 25, 2015 at 1:29 PM, Manuel Graune  wrote:
>>
>> def test1(a, b, condition="True"):
>> for i,j in zip(a,b):
>> c=i+j
>> if eval(condition):
>>print("Foo")
>>
> I'm not sure I understand your question, but condition will evaluate
> to True or False regardless, so:
>  if condition:
> print ("Foo")
>  else:
> print ("Bar")
>

The point is (see examples below) to specify the condition that is to be
evaluated when calling the function (as opposed to when stating the function). 

> eval can be dangerous as someone could put some unknown command with
> side effects in condition
>

I know that. That's why I'm looking for an alternative. ;-)

>> test1([0,1,2,3],[1,2,3,4],"i+j >4")
>> print("Bar")
>> test1([0,1,2,3],[1,2,3,4],"c >4")
>> print("Bar")
>> test1([0,1,2,3],[1,2,3,4],"a[i] >2")
>>
>> Resulting in
>>
>> Foo
>> Foo
>> Bar
>> Foo
>> Foo
>> Bar
>> Foo

Regards,

Manuel

-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-25 Thread Ian Kelly
On Wed, Mar 25, 2015 at 11:29 AM, Manuel Graune  wrote:
> Hi,
>
> I'm looking for a way to supply a condition to an if-statement inside a
> function body when calling the function. I can sort of get what I want
> with using eval (see code below) but I would like to achieve this in a
> safer way. If there is a solution which is safer while being
> less flexible, that would be fine. Also, supplying the condition as a
> string is not necessary. What I want to do is basically like this:
>
> def test1(a, b, condition="True"):
> for i,j in zip(a,b):
> c=i+j
> if eval(condition):
>print("Foo")

Pass the condition as a function.

def test1(a, b, condition=lambda i, j: True):
for i,j in zip(a,b):
c=i+j
if condition(i, j):
print("Foo")

test1([0,1,2,3],[1,2,3,4], lambda i, j: i+j > 4)
# etc.

If you find lambdas confusing and prefer named functions, those will
work just as well.

def i_plus_j_gt_4(i, j):
return i + j > 4

test1([0,1,2,3],[1,2,3,4], i_plus_j_gt_4)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-25 Thread Joel Goldstick
On Wed, Mar 25, 2015 at 1:29 PM, Manuel Graune  wrote:
> Hi,
>
> I'm looking for a way to supply a condition to an if-statement inside a
> function body when calling the function. I can sort of get what I want
> with using eval (see code below) but I would like to achieve this in a
> safer way. If there is a solution which is safer while being
> less flexible, that would be fine. Also, supplying the condition as a
> string is not necessary. What I want to do is basically like this:
>
> def test1(a, b, condition="True"):
> for i,j in zip(a,b):
> c=i+j
> if eval(condition):
>print("Foo")
>
I'm not sure I understand your question, but condition will evaluate
to True or False regardless, so:
 if condition:
print ("Foo")
 else:
print ("Bar")

eval can be dangerous as someone could put some unknown command with
side effects in condition

> test1([0,1,2,3],[1,2,3,4],"i+j >4")
> print("Bar")
> test1([0,1,2,3],[1,2,3,4],"c >4")
> print("Bar")
> test1([0,1,2,3],[1,2,3,4],"a[i] >2")
> print("Bar")
> test1([0,1,2,3],[1,2,3,4])
>
> Resulting in
>
> Foo
> Foo
> Bar
> Foo
> Foo
> Bar
> Foo
> Bar
> Foo
> Foo
> Foo
> Foo
>
> Thanks for your help
>
> Regards,
>
> Manuel
>
> --
> A hundred men did the rational thing. The sum of those rational choices was
> called panic. Neal Stephenson -- System of the world
> http://www.graune.org/GnuPG_pubkey.asc
> Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Supply condition in function call

2015-03-25 Thread Manuel Graune
Hi,

I'm looking for a way to supply a condition to an if-statement inside a
function body when calling the function. I can sort of get what I want
with using eval (see code below) but I would like to achieve this in a
safer way. If there is a solution which is safer while being
less flexible, that would be fine. Also, supplying the condition as a
string is not necessary. What I want to do is basically like this:

def test1(a, b, condition="True"):
for i,j in zip(a,b):
c=i+j
if eval(condition):
   print("Foo")

test1([0,1,2,3],[1,2,3,4],"i+j >4")
print("Bar")
test1([0,1,2,3],[1,2,3,4],"c >4")
print("Bar")
test1([0,1,2,3],[1,2,3,4],"a[i] >2")
print("Bar")
test1([0,1,2,3],[1,2,3,4])

Resulting in

Foo
Foo
Bar
Foo
Foo
Bar
Foo
Bar
Foo
Foo
Foo
Foo

Thanks for your help

Regards,

Manuel

-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
https://mail.python.org/mailman/listinfo/python-list