Re: for/ if against dict - one liner

2017-11-14 Thread Thomas Jollans
On 2017-11-14 07:29, Stefan Ram wrote:
> Andrew Z  writes:
>> i wonder how do i get the "for" and "if" to work against a dictionary in
>> one line?
> 
> dict ={ 1 : "one", 2 : "two", 3 : "three" }
> print( *( ( str( key )+ ' ' + str( dict[ key ])) for key in dict if key >= 2 
> ), sep='\n' )
> 
>   prints:
> 
> 2 two
> 3 three
> 

We can build something nicer than that, surely. The repeated str() calls
and dictionary lookups just look like noise to my eyes.

print('\n'.join(f'{k} {v}' for k, v in dict.items() if k >= 2))

But indeed, you can build concise dictionary filters like that with
generator expressions and list comprehensions.


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


Re: from xx import yy (Posting On Python-List Prohibited)

2017-11-14 Thread Lawrence D’Oliveiro
On Monday, November 13, 2017 at 3:18:04 PM UTC+13, bvdp wrote:
> I'm having a conceptual mind-fart today. I just modified a bunch
> of code to use "from xx import variable" when variable is a global
> in xx.py. But, when I change/read 'variable' it doesn't appear to change.

1) Every name in Python is a variable.
2) Every distinct name (including qualifications) is a distinct variable. 
Changing one does not automatically change another. “from xx import yy” creates 
a variable named “yy” in the current scope, initialized to xx.yy but otherwise 
distinct from it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for/ if against dict - one liner

2017-11-14 Thread Vincent Vande Vyvre

Le 14/11/17 à 06:44, Andrew Z a écrit :

Hello,
  i wonder how do i get the "for" and "if" to work against a dictionary in
one line?

basically i want to "squeeze":
  dct= [ 1 : "one", 2:"two", 3:"three"]
  for k, val in dct:
if k >= 2:
   # do magnificent things

Thank you
AZ


Maybe something like that:

lst = [do_magnificent_thing(dct[k]) for k in dct if k >= 2]

lst contains the returns of do_magnificent_thing(k) in unpredictable order.


Vincent

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


Re: for/ if against dict - one liner

2017-11-14 Thread alister via Python-list
On Tue, 14 Nov 2017 00:44:18 -0500, Andrew Z wrote:

> Hello,
>  i wonder how do i get the "for" and "if" to work against a dictionary
>  in
> one line?
> 
> basically i want to "squeeze":
>  dct= [ 1 : "one", 2:"two", 3:"three"]
>  for k, val in dct:
>if k >= 2:
>   # do magnificent things
> 
> Thank you AZ

why the need to single line it?
is your computer running out of new line & space characters?
it probably could be done with a dictionary comprehension but will that 
make things easier or harder to read/understand?

"Readability counts"




-- 
(Presuming for the sake of argument that it's even *possible* to design
better code in Perl than in C.  :-)
-- Larry Wall on core code vs. module code design
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for/ if against dict - one liner

2017-11-14 Thread Thomas Jollans
On 2017-11-14 06:44, Andrew Z wrote:
> Hello,
>  i wonder how do i get the "for" and "if" to work against a dictionary in
> one line?
> 
> basically i want to "squeeze":
>  dct= [ 1 : "one", 2:"two", 3:"three"]
>  for k, val in dct:

Don't you mean dct.items()

>if k >= 2:
>   # do magnificent things
> 
> Thank you
> AZ
> 


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


Re: PySide window does not resize to fit screen

2017-11-14 Thread Heli
Hi Chris and others, 

I have re-designed my user interface to include layouts and now it fits the 
screen perfectly.

Thanks a lot for all your help on this thread, 
Best 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Time travel - how to simplify?

2017-11-14 Thread Ben Finney
Andrew Z  writes:

> Now i want to get certain number of months. Say, i need  3 months duration
> starting from any month in dict.
>
> so if i start @ 7th:
> my_choice =7
>  for mnth, value in fut_suffix:
> if my_choice >= mnth
># life is great
> but if :
> my_choice = 12 then my "time travel" becomes pain in the neck..

The ‘itertools’ library in the Python standard library
https://docs.python.org/3/library/itertools.html> has what you
need:

import itertools

month_values = sorted(list(fut_suffix.keys()))
month_cycle = itertools.cycle(month_values)

month_choice = 7
three_months_starting_at_choice = []
while len(three_months_starting_at_choice) < 3:
this_month = next(month_cycle)
if this_month >= month_choice:
three_months_starting_at_choice.append(this_month)

-- 
 \  “God forbid that any book should be banned. The practice is as |
  `\  indefensible as infanticide.” —Dame Rebecca West |
_o__)  |
Ben Finney

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


Re: Time travel - how to simplify?

2017-11-14 Thread Ben Finney
Ben Finney  writes:

> import itertools
>
> month_values = sorted(list(fut_suffix.keys()))
> month_cycle = itertools.cycle(month_values)
>
> month_choice = 7
> three_months_starting_at_choice = []
> while len(three_months_starting_at_choice) < 3:
> this_month = next(month_cycle)
> if this_month >= month_choice:
> three_months_starting_at_choice.append(this_month)

Sorry, I now realise that won't do what you want; the wrap around from
12 to 1 will cause ‘this_month >= month_choice’ to be false.

Well, I won't correct it; maybe this is a useful exercise. Do you have a
way to fix that so it will work?

-- 
 \  “I am too firm in my consciousness of the marvelous to be ever |
  `\   fascinated by the mere supernatural …” —Joseph Conrad, _The |
_o__) Shadow-Line_ |
Ben Finney

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


inspecting a callable for the arguments it accepts

2017-11-14 Thread Cameron Simpson
I know that this isn't generally solvable, but I'm wondering if it is partially 
solvable.


I have a task manager which accepts callables, usually functions or generators, 
and calls them on data items as needed. For reasons which, frankly, suggest 
user interface ergonomics failure to me it happens that inappropriate functions 
get submtted to this system. For example, functions accepting no arguments but 
which are handed one by the system.


I would like to inspect submitted functions' signatures for suitability at 
submission time, without calling the function. For example to see if this 
function accepts exactly one argument, or to see if it is a generator, etc.


Is this possible, even in a limited way?

The present situation is that when I get this wrong I get highly cryptic 
exceptions at runtime, some of which I think I could be FAR better understood 
if caught at submittion time.


Here's an example failure at runtime:

   pilfer.py: WorkerThreadPool:Later-1:WorkerThreadPool: worker thread: ran task: exception! 
(, TypeError('() takes 0 positional arguments but 1 was 
given',), )
   Traceback (most recent call last):
 File "/Users/cameron/hg/css/cs/threads.py", line 163, in _handler
   result = func()
 File "/Users/cameron/hg/css/cs/app/pilfer.py", line 1550, in retry_func
   return func(P, *a, **kw)
   TypeError: () takes 0 positional arguments but 1 was given
   pilfer.py: MAIN:0:0:retriable().put(Pilfer-0[http://www.smh.com.au/]): (, TypeError('() takes 0 positional arguments but 1 was given',), 
)

Ignoring the slight repetition you can see that (a) there's no direct clue as 
to what the actual submitted function was originally, as it is a lambda and (b) 
there's no direct clue as to where the function came from, because the 
submission call stack is long gone and the function is being called via a 
thread pool.


Had I caught the function as unsuitable at submission time, debugging would be 
far easier.


To be clear: the task manager is my own project, as is the submitted function.  
I'm trying to improve its debuggability.


Cheers,
Cameron Simpson  (formerly [email protected])
--
https://mail.python.org/mailman/listinfo/python-list


Re: from xx import yy

2017-11-14 Thread Cameron Simpson

On 13Nov2017 08:58, bvdp  wrote:

On Sunday, November 12, 2017 at 7:18:04 PM UTC-7, bvdp wrote:

I'm having a conceptual mind-fart today. I just modified a bunch of code to use 
"from xx import variable" when variable is a global in xx.py. But, when I 
change/read 'variable' it doesn't appear to change. I've written a bit of code to show 
the problem:

mod1.py
myvar = 99
def setvar(x):
global myvar
myvar = x

test1.py
import mod1
mod1.myvar = 44
print (mod1.myvar)
mod1.setvar(33)
print (mod1.myvar)

If this test1.py is run myvar is fine. But, if I run:

test2.py
from mod1 import myvar, setvar
myvar = 44
print (myvar)
setvar(33)
print (myvar)

It doesn't print the '33'.

I thought (apparently incorrectly) that import as would import the name myvar 
into the current module's namespace where it could be read by functions in the 
module


Thanks all for confirming that I was wrong to use "from .. import". Hmmm, 
perhaps for functions it might be okay. But, in most cases it's a lot more obvious to use 
module.function() when calling. Maybe a bit slower, but I'm sure it's negligible in most 
cases.


You're wrong to use it for this particular special case, and ony because you 
lose the reference to the module itself, which means you're no longer accessing 
the _reference_ "mod1.myvar", you're accessing a copy of the reference. So the 
wrong reference gets changed.


In the general case, this isn't something people do a great deal. For most 
imports you want access to things from the module with no intention of changing 
those references in the source module.


So "from xx import yy" is perfectly find for that, the most common use case.

Consider:

 from os.path import basename, dirname

Is your code more readable with:

 from os.path import basename, dirname
 base_of_parent_dir = basename(dirname(some_path))

or as:

 import os.path
 base_of_parent_dir = os.path.basename(os.path.dirname(some_path))

particularly when you make lots of such calls? I much prefer the former.

And, yes, I am trying to share state info between modules. Is this a bad 
thing? I guess I would write getter() and setter() functions for all this. But 
that does seem to remind me too much of some other language :)


In controlled situations it can be ok. Usually I define a small class for this 
kind of thing and keep all the state in class instances. That way it can scale 
(keeping multiple "states" at once).


However, it does depend on your particular situation. I find situations where I 
want to directly change "global" values in other modules very rare, though not 
unknown.


Cheers,
Cameron Simpson  (formerly [email protected])
--
https://mail.python.org/mailman/listinfo/python-list


Re: inspecting a callable for the arguments it accepts

2017-11-14 Thread Chris Angelico
On Wed, Nov 15, 2017 at 8:05 AM, Cameron Simpson  wrote:
> I know that this isn't generally solvable, but I'm wondering if it is
> partially solvable.
>
> I have a task manager which accepts callables, usually functions or
> generators, and calls them on data items as needed. For reasons which,
> frankly, suggest user interface ergonomics failure to me it happens that
> inappropriate functions get submtted to this system. For example, functions
> accepting no arguments but which are handed one by the system.
>
> I would like to inspect submitted functions' signatures for suitability at
> submission time, without calling the function. For example to see if this
> function accepts exactly one argument, or to see if it is a generator, etc.
>
> Is this possible, even in a limited way?

Yes, it is. Sometimes in a very limited way, other times fairly well.
(NOTE: I'm using CPython for this. Other interpreters may differ
wildly.) First off, you can look at the function's attributes to see
some of the info you want:

>>> def wants_one_arg(x): pass
...
>>> wants_one_arg.__code__.co_argcount
1
>>> wants_one_arg.__code__.co_varnames
('x',)

co_varnames has the names of all local variables, and the first N of
those are the arguments. You aren't matching on the argument names,
but they might help you make more readable error messages.

As to recognizing generators, every function has a set of flags which
will tell you whether it yields or just returns:

>>> def fun(): pass
...
>>> def gen(): yield 1
...
>>> fun.__code__.co_flags
67
>>> gen.__code__.co_flags
99

That's the raw info. For human-friendly functions that look at this
info, check out the inspect module:

>>> inspect.isgeneratorfunction(fun)
False
>>> inspect.isgeneratorfunction(gen)
True
>>> inspect.signature(wants_one_arg)


Poke around with its functions and you should be able to find most of
what you want, I think.

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


Re: Windows10 keyboard interupt

2017-11-14 Thread Lawrence D’Oliveiro
On Wednesday, November 15, 2017 at 3:01:37 AM UTC+13, Kasper Jepsen wrote:

> Forgot.. python 2.7


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


Re: Time travel - how to simplify?

2017-11-14 Thread Rick Johnson
On Tuesday, November 14, 2017 at 1:44:17 PM UTC-6, Ben Finney wrote:
> Andrew Z  writes:
> 
> > Now i want to get certain number of months. Say, i need  3 months duration
> > starting from any month in dict.
> >
> > so if i start @ 7th:
> > my_choice =7
> >  for mnth, value in fut_suffix:
> > if my_choice >= mnth
> ># life is great
> > but if :
> > my_choice = 12 then my "time travel" becomes pain in the neck..
> 
> The ‘itertools’ library in the Python standard library
> https://docs.python.org/3/library/itertools.html> has what you
> need:
> 
> import itertools
> 
> month_values = sorted(list(fut_suffix.keys()))
> month_cycle = itertools.cycle(month_values)
> 
> month_choice = 7
> three_months_starting_at_choice = []
> while len(three_months_starting_at_choice) < 3:
> this_month = next(month_cycle)
> if this_month >= month_choice:
> three_months_starting_at_choice.append(this_month)

Ben's advice is spot on[1], and exactly what i would do, but
i believe it's important for you to discover how to
implement a simple cycling algorithm yourself, _before_
reaching for the pre-packaged junkfood in the itertools
module. Can you do it? If not, then do as much as you can
and then ask for help. Hey, you're only hurting yourself if
you don't learn how. And it's surprisingly easy!

[1] and it looks as though he included the kitchen sink,
washcloths, dish soap, and some fine china as well! ಠ_ಠ
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: inspecting a callable for the arguments it accepts

2017-11-14 Thread Chris Angelico
On Wed, Nov 15, 2017 at 9:03 AM, Stefan Ram  wrote:
> Cameron Simpson  writes:
>>I would like to inspect submitted functions' signatures for suitability at
>>submission time, without calling the function. For example to see if this
>>function accepts exactly one argument, or to see if it is a generator, etc.
>
>   Sometimes, there is a __text__signature__:
>
> |>>> cos.__text_signature__
> |'($module, x, /)'
>
>   , but not always.

True. However, I'm pretty sure that applies only to Argument Clinic
functions, which are all implemented in C; the context suggests that
the functions in question will all be implemented in Python.

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


Re: inspecting a callable for the arguments it accepts

2017-11-14 Thread Cameron Simpson

On 15Nov2017 09:12, Chris Angelico  wrote:

On Wed, Nov 15, 2017 at 8:05 AM, Cameron Simpson  wrote:

I know that this isn't generally solvable, but I'm wondering if it is
partially solvable.

I have a task manager which accepts callables, usually functions or
generators, and calls them on data items as needed. For reasons which,
frankly, suggest user interface ergonomics failure to me it happens that
inappropriate functions get submtted to this system. For example, functions
accepting no arguments but which are handed one by the system.

I would like to inspect submitted functions' signatures for suitability at
submission time, without calling the function. For example to see if this
function accepts exactly one argument, or to see if it is a generator, etc.

Is this possible, even in a limited way?


Yes, it is. Sometimes in a very limited way, other times fairly well.
(NOTE: I'm using CPython for this. Other interpreters may differ
wildly.)


I'm using CPython too.


First off, you can look at the function's attributes to see
some of the info you want:


def wants_one_arg(x): pass

...

wants_one_arg.__code__.co_argcount

1

wants_one_arg.__code__.co_varnames

('x',)

co_varnames has the names of all local variables, and the first N of
those are the arguments. You aren't matching on the argument names,
but they might help you make more readable error messages.

As to recognizing generators, every function has a set of flags which
will tell you whether it yields or just returns:


def fun(): pass

...

def gen(): yield 1

...

fun.__code__.co_flags

67

gen.__code__.co_flags

99

That's the raw info. For human-friendly functions that look at this
info, check out the inspect module:


inspect.isgeneratorfunction(fun)

False

inspect.isgeneratorfunction(gen)

True

inspect.signature(wants_one_arg)



Poke around with its functions and you should be able to find most of
what you want, I think.


Thank you, looks like just what I need.

Cheers,
Cameron Simpson  (formerly [email protected])
--
https://mail.python.org/mailman/listinfo/python-list


Re: inspecting a callable for the arguments it accepts

2017-11-14 Thread Gregory Ewing

Chris Angelico wrote:


wants_one_arg.__code__.co_argcount


1


wants_one_arg.__code__.co_varnames


('x',)


That will give you some idea, but it's not foolproof -- e.g.
if the function has * or ** arguments, it's impossible to tell
in general how many arguments it accepts without studying the
code (and maybe not even then -- halting problem, etc.)

Some of the co_flags seem to indicate presence of * and **:

0x04 - has *args
0x08 - has **kwds

In Py3 there is also co_kwonlyargcount.

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


Re: inspecting a callable for the arguments it accepts

2017-11-14 Thread Chris Angelico
On Wed, Nov 15, 2017 at 4:34 PM, Gregory Ewing
 wrote:
> Chris Angelico wrote:
>
> wants_one_arg.__code__.co_argcount
>>
>>
>> 1
>>
> wants_one_arg.__code__.co_varnames
>>
>>
>> ('x',)
>
>
> That will give you some idea, but it's not foolproof -- e.g.
> if the function has * or ** arguments, it's impossible to tell
> in general how many arguments it accepts without studying the
> code (and maybe not even then -- halting problem, etc.)
>
> Some of the co_flags seem to indicate presence of * and **:
>
> 0x04 - has *args
> 0x08 - has **kwds
>
> In Py3 there is also co_kwonlyargcount.

Yep. Browsing __code__'s attributes was the stepping-stone to the
actual way of doing it: the inspect module. But I figured it's better
to look at those attributes briefly rather than say "here's the
inspect module, it uses magic".

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