Re: Spread a statement over various lines

2019-09-18 Thread codewizard
On Wednesday, September 18, 2019 at 9:01:21 AM UTC-4, Manfred Lotz wrote:
> On Wed, 18 Sep 2019 08:30:08 +0200
> Peter Otten <__pete...@web.de> wrote:
> 
> > Manfred Lotz wrote:
> > 
> > > I have a function like follows
> > > 
> > > def regex_from_filepat(fpat):
> > > rfpat = fpat.replace('.', '\\.') \
> > >   .replace('%', '.')  \
> > >   .replace('*', '.*')
> > > 
> > > return '^' + rfpat + '$'
> > > 
> > > 
> > > As I don't want to have the replace() functions in one line my
> > > question is if it is ok to spread the statement over various lines
> > > as shown above, or if there is a better way?  
> > 
> > Sometimes you can avoid method-chaining:
> > 
> > >>> REP = str.maketrans({".": "\\.", "%": ".", "*": ".*"})
> > >>> def regex_from_filepat(fpat):  
> > ... return fpat.translate(REP)
> > ... 
> > >>> regex_from_filepat("*foo.%")  
> > '.*foo\\..'
> > 
> 
> Very interesting. Thanks for this.

While I think that str.translate() is the right tool for this job,
here's another way to avoid line continuations (not necessarily better):

def regex_from_filepat(fpat):
replacements = [
('.', '\\.'),
('%', '.'),
('*', '.*'),
]

rfpat = fpat
for old, new in replacements:
rfpat = rfpat.replace(old, new)

return '^' + rfpat + '$'
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: From Mathematica to Jypyter

2018-10-10 Thread codewizard
On Wednesday, October 10, 2018 at 12:09:41 PM UTC-4, Rhodri James wrote:
> On 10/10/18 08:32, Robin Becker wrote:
> > 
> > I'm a great fan of erroneous spelling and this blog needs a spelling 
> > check as this quote shows
> > 
> > "Mathematica exemplifies the horde of new Vandals whose pursuit of 
> > private gain threatens a far greater pubic loss–the collapse of social 
> > systems that took centuries to build."
> > 
> > these Vandals are probably not in favour of the #me-too movement either :)
> 
> OK, colour me confused.  The only spelling mistake I can spot in that is 
> in the subject line of this thread.  What am I missing?

The loss is far greater than a single letter. :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread codewizard
On Thursday, July 12, 2018 at 7:16:48 PM UTC-4, Chris Angelico wrote:
> On Fri, Jul 13, 2018 at 8:10 AM Igor wrote:
> > On Thursday, July 12, 2018 at 5:45:52 AM UTC-4, Ben Bacarisse wrote:
> >> aleiphoenix writes:
> >>
> >> [snip]
> >>
> >>   When an exception has been assigned using as target, it is cleared at
> >>   the end of the except clause. This is as if
> >>
> >>   except E as N:
> >>   foo
> >>
> >>   was translated to
> >>
> >>   except E as N:
> >>   try:
> >>   foo
> >>   finally:
> >>   del N
> >
> > Is there a downside of implementing
> > it similarly to this (untested):
> >
> >   # generate a unique name for __except_N
> >   except E as __except_N:
> > if 'N' in locals() or N in globals():
> >   __original_N = N
> >
> > N = __except_N
> > try:
> >   foo()
> > finally:
> >   del __except_N
> >
> >   if '__original_N' in locals():
> > N = __original_N
> > del __original_N
> >   else:
> > del N
> 
> Not sure, but here's a simpler implementation:
> 
> except Exception as .err.0:
> print(.err.0)
> .err.0 = None
> del .err.0
> 
> In other words, exactly the same as the current behaviour, except that
> (sorry, pun intended) inside the block, the name is modified to
> something that can't actually be used. (The token ".err.0" functions
> like an actual local name, just one that's syntactically invalid and
> thus cannot ever conflict.) Once you exit the except block, the
> previous value will magically reappear, because it didn't go anywhere.
> Multiple except blocks - nested or separate - would have separate
> names (".err.1", ".err.2"), so they won't conflict with each other.
> 
> ChrisA

Simpler is better. The point is that something like this would accomplish both:

1. Break the reference cycle.

2. Avoid what is (IMHO) an unexpected behavior of a variable declared prior to 
try/except disappearing after getting shadowed by "except as".

Regards,
Igor.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread codewizard
On Thursday, July 12, 2018 at 5:45:52 AM UTC-4, Ben Bacarisse wrote:
> aleiphoenix writes:
> 
> [snip]
> 
>   When an exception has been assigned using as target, it is cleared at
>   the end of the except clause. This is as if
> 
>   except E as N:
>   foo
> 
>   was translated to
> 
>   except E as N:
>   try:
>   foo
>   finally:
>   del N

Is there a downside of implementing
it similarly to this (untested):

  # generate a unique name for __except_N
  except E as __except_N:
if 'N' in locals() or N in globals():
  __original_N = N

N = __except_N
try:
  foo()
finally:
  del __except_N

  if '__original_N' in locals():
N = __original_N
del __original_N
  else:
del N


Regards,
Igor.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: translating foreign data

2018-06-21 Thread codewizard
On Thursday, June 21, 2018 at 1:08:35 PM UTC-4, Ethan Furman wrote:
> I need to translate numeric data in a string format into a binary format.  I 
> know there are at least two different 
> methods of representing parts less that 1, such as "10.5" and "10,5".  The 
> data is encoded using code pages, and can 
> vary depending on the file being read (so I can't rely on current locale 
> settings).
> 
> I'm sure this is a solved problem, but I'm not finding those solutions.  Any 
> pointers?
> 
> --
> ~Ethan~

Try this StackOverflow answer: https://stackoverflow.com/a/17815252

Regards,
Igor.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pandas, create new column if previous column(s) are not in [None, '', np.nan]

2018-04-11 Thread codewizard
On Wednesday, April 11, 2018 at 2:49:01 PM UTC-4, zlju...@gmail.com wrote:
> I have a dataframe:
> 
> import pandas as pd
> import numpy as np
> 
> df = pd.DataFrame( { 'A' : ['a', 'b', '', None, np.nan],
>  'B'  : [None, np.nan, 'a', 'b', '']})
> 
>   A B
> 0 a  None
> 1 b   NaN
> 2   a
> 3  None b
> 4   NaN  
> 
> 
> I would like to create column C in the following way:
> column C = column B if column B is not in [None, '', np.nan]
> else column A
> 
> How to do that?
> 
> I tried:
> 
> df['C'] = df[['A', 'B']].apply(lambda x: x[1] if x[1] in [None, '', np.nan] 
> else x[0])
> 
> but I got all np.nan's.
> 
> Where am I wrong?
> 
> I am expecting to get column C as ['a', 'b', 'a', 'b', NaN]
> 
> Regards.

Try this:

df['C'] = df['B'].where(df['B'], other=df['A'])

Regards,
Igor.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Style Q: Instance variables defined outside of __init__

2018-03-20 Thread codewizard
On Tuesday, March 20, 2018 at 1:10:19 PM UTC-4, Irv Kalb wrote:
> I am aware of all the issues involved.  My example code was an attempt to 
> demonstrate the clearest, simplest case possible.  My question is not about 
> this small case.  In classes designed for full games, I often have a "reset" 
> method that resets many instance variables (and potentially other display 
> fields and graphics) for a new round of playing a game.  Grouping this into a 
> method called something like "reset" makes logical sense to me.  You tell the 
> game object to reset itself, and it does whatever it needs to do to reset for 
> a new round.  My __init__ method calls reset to initialize the first round of 
> the game.  This ensures that every play of the game goes through the same 
> initialization.

Calling reset() from __init__() and duplicating resetting logic during 
initialization aren't the only choices.

My personal preference in such situations is to put all initialization code in 
__init__. Then write a separate factory function / method to create the new 
object for the next round. Optionally, this factory can be parametrized by the 
previous round object.

Regards,
Igor.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can mock.mock_open.read return different values?

2018-03-12 Thread codewizard
On Monday, March 12, 2018 at 4:51:53 AM UTC-4, Tim Golden wrote:
> I'm contributing to a codebase which makes heavy use of mock in the test 
> suite, a technique which I'm aware of but have used only rarely. In one 
> situation it uses mock.mock_open(read_data="...") and then asserts again 
> mock_open.return_value.read.call_count.
> 
> A code change I've made results in an increase in the call count but 
> also the open() I've introduced opens the file in binary mode and does 
> something with the resulting data.
> 
> Hugely simplified, the new code and unchanged test looks like this:
> 
> import os, sys
> import unittest
> from unittest import mock
> 
> def read_file(filename):
> 
>  #
>  # This section is new
>  #
>  with open(filename, "rb") as f:
>  text = f.read()
>  if text.startswith(b"#"):
>  pass
> 
>  with open(filename) as f:
>  text = f.read()
>  if text.startswith("#"):
>  pass
> 
>  return text
> 
> class TestS(unittest.TestCase):
> 
>  def test_read_file(self):
>  mock_open = mock.mock_open(read_data="abc")
>  with mock.patch('builtins.open', mock_open):
>  data = read_file("abc")
>  assert mock_open.return_value.read.call_count == 1
> 
> if __name__ == '__main__':
>  unittest.main()
> 
> 
> I would expect the test to fail because of the call_count change. But in 
> fact it errors out because the newly-added "if test.startswith()" 
> receives a string, not bytes, from the Mock's read_data functionality.
> 
> Ignore for the moment any question of changing the read_file 
> implementation to assist testing. And leave aside the question of 
> whether a mock_open is really a good test approach here.
> 
> Is there any way in which I can have the mock_open object return bytes 
> for the first open and a string for the second? I've looked at setting a 
> side_effect function against the mock_open.return_value.read Mock, but I 
> can't see a way of having the function know whether it's supposed to be 
> returning bytes or string.
> 
> 
> TJG

2 ways come to mind:

1. Have the side effect function check something that differentiates
those 2 calls. In this case, checking mode argument value should work.

2. Rely on the order of calls with a local side effect function
closing over a call number. Something like this (untested):

def test_read_file(self):
call_number = 0

def open_side_effect(filename, mode='r'):
call_number += 1

if call_number == 1:
 return b'some bytes'
if call_number == 2:
 return 'some string'

 with mock.patch(..., side_effect=open_side_effect):
  # test

Regards,
Igor.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: This newsgroup (comp.lang.python) may soon be blocked by Google Gro

2018-02-09 Thread codewizard
On Friday, February 9, 2018 at 6:45:18 PM UTC-5, Richard Damon wrote:
> On 2/9/18 6:19 PM, codew...@gmail.com wrote:
> > On Friday, February 9, 2018 at 5:03:45 PM UTC-5, Richard Damon wrote:
> >> On 2/9/18 4:12 PM, Chris Angelico wrote:
> >>> On Sat, Feb 10, 2018 at 8:05 AM,   wrote:
>  On Friday, February 9, 2018 at 2:48:17 PM UTC-5, Chris Green wrote:
> > codew...@gmail.com wrote:
> >> On Saturday, February 3, 2018 at 7:15:16 PM UTC-5, pyotr filipivich 
> >> wrote:
> >>> [snip]
> >>>   Those of us who do not use google-groups may not notice the 
> >>> loss
> >>> of the google groupies.
> >> I use GG to read comp.lang.python because of the following combination
> >> of factors. I would definitely be happier if there was another way to
> >> do this, so that I wouldn't have to wade through lots of spam.
> >>
> >> - I read it from both home and work.
> >>
> >> - I can't install any additional software at work.
> >>
> >> - There is no newsgroup reader software available at work.
> >>
> >> - GG tracks read/unread status of every post. This is shared
> >>   between work and home through my Google account.
> >>
> >> - When I (very rarely) post from work, I can't
> >>   do it by email, since outgoing email is blocked.
> >>
> > Alternative approach, what I do:-
> >
> >   Run a text mode (but very capable and mouse aware) newsreader on
> >   my home system, read news locally using that.
> >
> >   Use ssh (is that available at worK?) to connect from work to home
> >   and run the same newsreader in the same environment. If you can't
> >   even ssh from work then you can always use an 'ssh from the web'
> >   app from your wenb browser.
> >
> > The newsreader I use is tin by the way.
> >
> > --
> > Chris Green
> > ·
>  ssh would be even a bigger problem here. As I mentioned, I can't even 
>  email
>  from work to the outside! All web sites that provide remote connectivity
>  tools are blocked.
> >>> ... yet they're okay with you browsing newsgroups? I think you may
> >>> have a Layer Eight conflict here.
> >>>
> >>> ChrisA
> >> If he can browse, he can get E-Mail with Gmail/Yahoo/AOL/etc, his normal
> >> mail ISP likely even supports some form of Web Mail Client.
> >>
> >> If they are blocking these, but not Google Groups, there is a major
> >> disconnect in the rules.
> >>
> >> -- 
> >> Richard Damon
> > Disconnect or not, I can browse GG and post replies (e.g., this one).
> > I have no access to gmail or any other email provider.
> >
> > Regards,
> > Igor.
> 
> My guess then is that your access to google groups is also against your 
> companies policies, they just haven't put an enforcement in their 
> firewalls because it is too obscure for the IT department to have 
> thought of.
> 
> Based on the sort of broad blocking they are doing, I am a bit surprised 
> they seem to be black listing rather than white listing the web.
> 
> -- 
> Richard Damon

Regardless of what the policies are and how well they're enforced,
if the mailing list is cut off from GG, I will stop reading it.
Probably not a big loss to anyone else, but you might wonder how many others 
are in the same situation...

Regards,
Igor.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: This newsgroup (comp.lang.python) may soon be blocked by Google Gro

2018-02-09 Thread codewizard
On Friday, February 9, 2018 at 5:03:45 PM UTC-5, Richard Damon wrote:
> On 2/9/18 4:12 PM, Chris Angelico wrote:
> > On Sat, Feb 10, 2018 at 8:05 AM,   wrote:
> >> On Friday, February 9, 2018 at 2:48:17 PM UTC-5, Chris Green wrote:
> >>> codew...@gmail.com wrote:
>  On Saturday, February 3, 2018 at 7:15:16 PM UTC-5, pyotr filipivich 
>  wrote:
> > [snip]
> >  Those of us who do not use google-groups may not notice the 
> > loss
> > of the google groupies.
>  I use GG to read comp.lang.python because of the following combination
>  of factors. I would definitely be happier if there was another way to
>  do this, so that I wouldn't have to wade through lots of spam.
> 
> - I read it from both home and work.
> 
> - I can't install any additional software at work.
> 
> - There is no newsgroup reader software available at work.
> 
> - GG tracks read/unread status of every post. This is shared
>   between work and home through my Google account.
> 
> - When I (very rarely) post from work, I can't
>   do it by email, since outgoing email is blocked.
> 
> >>> Alternative approach, what I do:-
> >>>
> >>>  Run a text mode (but very capable and mouse aware) newsreader on
> >>>  my home system, read news locally using that.
> >>>
> >>>  Use ssh (is that available at worK?) to connect from work to home
> >>>  and run the same newsreader in the same environment. If you can't
> >>>  even ssh from work then you can always use an 'ssh from the web'
> >>>  app from your wenb browser.
> >>>
> >>> The newsreader I use is tin by the way.
> >>>
> >>> --
> >>> Chris Green
> >>> ·
> >> ssh would be even a bigger problem here. As I mentioned, I can't even email
> >> from work to the outside! All web sites that provide remote connectivity
> >> tools are blocked.
> > ... yet they're okay with you browsing newsgroups? I think you may
> > have a Layer Eight conflict here.
> >
> > ChrisA
> 
> If he can browse, he can get E-Mail with Gmail/Yahoo/AOL/etc, his normal 
> mail ISP likely even supports some form of Web Mail Client.
> 
> If they are blocking these, but not Google Groups, there is a major 
> disconnect in the rules.
> 
> -- 
> Richard Damon

Disconnect or not, I can browse GG and post replies (e.g., this one).
I have no access to gmail or any other email provider.

Regards,
Igor.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: This newsgroup (comp.lang.python) may soon be blocked by Google Gro

2018-02-09 Thread codewizard
On Friday, February 9, 2018 at 2:48:17 PM UTC-5, Chris Green wrote:
> codew...@gmail.com wrote:
> > On Saturday, February 3, 2018 at 7:15:16 PM UTC-5, pyotr filipivich wrote:
> > > [snip]
> > > Those of us who do not use google-groups may not notice the loss
> > > of the google groupies.
> > 
> > I use GG to read comp.lang.python because of the following combination
> > of factors. I would definitely be happier if there was another way to
> > do this, so that I wouldn't have to wade through lots of spam.
> > 
> >   - I read it from both home and work.
> > 
> >   - I can't install any additional software at work.
> > 
> >   - There is no newsgroup reader software available at work.
> > 
> >   - GG tracks read/unread status of every post. This is shared
> > between work and home through my Google account.
> > 
> >   - When I (very rarely) post from work, I can't
> > do it by email, since outgoing email is blocked.
> > 
> Alternative approach, what I do:-
> 
> Run a text mode (but very capable and mouse aware) newsreader on
> my home system, read news locally using that.
> 
> Use ssh (is that available at worK?) to connect from work to home
> and run the same newsreader in the same environment. If you can't
> even ssh from work then you can always use an 'ssh from the web'
> app from your wenb browser.
> 
> The newsreader I use is tin by the way.
> 
> -- 
> Chris Green
> ·

ssh would be even a bigger problem here. As I mentioned, I can't even email
from work to the outside! All web sites that provide remote connectivity
tools are blocked.

Regards,
Igor.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: This newsgroup (comp.lang.python) may soon be blocked by Google Gro

2018-02-09 Thread codewizard
On Saturday, February 3, 2018 at 7:15:16 PM UTC-5, pyotr filipivich wrote:
> [snip]
> Those of us who do not use google-groups may not notice the loss
> of the google groupies.

I use GG to read comp.lang.python because of the following combination
of factors. I would definitely be happier if there was another way to
do this, so that I wouldn't have to wade through lots of spam.

  - I read it from both home and work.

  - I can't install any additional software at work.

  - There is no newsgroup reader software available at work.

  - GG tracks read/unread status of every post. This is shared
between work and home through my Google account.

  - When I (very rarely) post from work, I can't
do it by email, since outgoing email is blocked.

Regards,
Igor.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Where has the practice of sending screen shots as source code come from?

2018-01-28 Thread codewizard
On Sunday, January 28, 2018 at 3:27:06 PM UTC-5, Chris Angelico wrote:
> On Mon, Jan 29, 2018 at 7:13 AM, Chris Warrick  wrote:
> > On 28 January 2018 at 20:19, Chris Angelico  wrote:
> >> The vanilla Windows console (conhost.exe IIRC) is far from ideal for
> >> copying and pasting from
> >
> > It’s been fixed in recent Windows 10 releases (select and Ctrl+C works now).
> 
> Haven't used it, but that's good news at least.
> 
> >> Windows error popups are *impossible* to copy text from.
> >
> > Most standard error popups support pressing Ctrl+C to copy the text
> > displayed in them.
> 
> Really? Most? That would be a HUGE improvement. Historically, only a
> handful have actually had selectable text. And really, it has to be
> not just the core Windows error popups, but application ones as well;
> so it has to be the underlying message-box API that supports it.
> 
> ChrisA

Most popups in applications using the standard Windows dialogs 
can still be copied from, even if the text doesn't look selectable:

  - give the dialog a focus
  - press Ctrl-A (this invisibly selects all text)
  - press Ctrl-C to copy the text
  - paste (Ctrl-V) into your favorite text editor.

Regards,
Igor.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: @lru_cache on functions with no arguments

2017-07-31 Thread codewizard
On Monday, July 31, 2017 at 7:31:52 PM UTC-4, t...@tomforb.es wrote:
> As part of the Python 3 cleanup in Django there are a fair few uses of 
> @functools.lru_cache on functions that take no arguments. A lru_cache isn't 
> strictly needed here, but it's convenient to just cache the result. Some 
> examples are here: https://github.com/django/django/pull/8825/files
> 
> I did some profiling and I found that using `@lru_cache(maxsize=None)` on 
> such functions is twice as fast as a standard `@lru_cache()`, apparently 
> because with a `maxsize` the lru_cache code requires a lock acquisition and a 
> fair bit more state to track.
> 
> Am I right in thinking that using `maxsize=None` is best for functions that 
> accept no arguments? Should we even be using a `lru_cache` in such 
> situations, or write our own simple cache decorator instead?

If the performance savings are real, another choice would be to improve the 
implementation of lru_cache to special-case no-argument functions to avoid 
locks, etc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Out of memory while reading excel file

2017-05-12 Thread codewizard
On Thursday, May 11, 2017 at 5:01:57 AM UTC-4, Mahmood Naderan wrote:
> Excuse me, I changed 
> 
> csv.writer(outstream)
> 
> to 
> 
> csv.writer(outstream, delimiter =' ')
> 
> 
> It puts space between cells and omits "" around some content. However, 
> between two lines there is a new empty line. In other word, the first line is 
> the first row of excel file. The second line is empty ("\n") and the third 
> line is the second row of the excel file.
> 
> Any thought?
>  
> Regards,
> Mahmood

Try opening the destination file in the binary mode:

open(dest, 'wb')

I ran into extra newlines when using csv.writerows() recently.
Since the default mode for open() is text, I imagine you get
extra newlines, since both csv and file object are adding them.
Switching to binary mode fixed it for me.

Regards,
Igor.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pandas creating a new column based on row values

2017-03-28 Thread codewizard
On Tuesday, March 28, 2017 at 3:36:57 PM UTC-4, zlju...@gmail.com wrote:
> [snip]
> 
> Can I somehow generate a new column by concatenating values for the other 
> columns in a row?
> 

Try this (not tested):

def myfunc(row):
return 'Start_{}_{}_{}_{}_End'.format(row['coverage'], row['name'], 
row['reports'], row['year']) 

df['New'] = df.apply(myfunc, axis=1)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What do you think: good idea to launch a marketplace on python+django?

2016-12-02 Thread codewizard
On Friday, December 2, 2016 at 2:01:57 AM UTC-5, Gus_G wrote:
> Hello, what do you think about building a marketplace website on connection 
> of python+django? End effect-side should look and work similar to these: 
> https://zoptamo.com/uk/s-abs-c-uk, https://www.ownerdirect.com/ . What are 
> your opinions on this idea? Maybe there is other, better way to build it?

Something like this: https://marketplace.django-cms.org/en/ ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Two-Dimensional Expression Layout

2016-08-19 Thread codewizard
On Friday, August 19, 2016 at 6:38:34 PM UTC-4, Chris Angelico wrote:
> On Sat, Aug 20, 2016 at 8:31 AM, Lawrence D’Oliveiro
>  wrote:
> > On Saturday, August 20, 2016 at 9:56:05 AM UTC+12, codew...@gmail.com wrote:
> >>
> >> On Friday, August 19, 2016 at 5:30:22 PM UTC-4, Lawrence D’Oliveiro wrote:
> >>
> >>> On Saturday, August 20, 2016 at 7:52:09 AM UTC+12, codew...@gmail.com
> >>> wrote:
>  if any([
>  not isinstance(src, Image),
>  mask != None and not isinstance(mask, Image),
>  not isinstance(dest, Image),
>  ]):
>  raise TypeError("image args must be Image objects")
> 
>  Or equivalently:
> 
>  if not all([
>  isinstance(src, Image),
>  mask is None or isinstance(mask, Image),
>  isinstance(dest, Image),
>  ]):
>  raise TypeError("image args must be Image objects")
> >>>
> >>> Using “all” or “any” in this sort of situation may not be such a good
> >>> idea.
> >>
> >> Would you care to elaborate?
> >
> > There is no short-cut evaluation when constructing tuples and lists.
> 
> I'm not sure how that would make difference in these examples. The
> three parts are independent - the one place where short-circuiting is
> important is indeed short-circuited.
> 
> ChrisA

Agreed. Besides, just because this technique has limitations, it's still useful 
for me to improve readability.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Two-Dimensional Expression Layout

2016-08-19 Thread codewizard
On Friday, August 19, 2016 at 5:30:22 PM UTC-4, Lawrence D’Oliveiro wrote:
> On Saturday, August 20, 2016 at 7:52:09 AM UTC+12, codew...@gmail.com wrote:
> > if any([
> > not isinstance(src, Image),
> > mask != None and not isinstance(mask, Image),
> > not isinstance(dest, Image),
> > ]):
> > raise TypeError("image args must be Image objects")
> > 
> > Or equivalently:
> > 
> > if not all([
> > isinstance(src, Image),
> > mask is None or isinstance(mask, Image),
> > isinstance(dest, Image),
> > ]):
> > raise TypeError("image args must be Image objects")
> 
> Using “all” or “any” in this sort of situation may not be such a good idea. 
> More reasonable uses would be like 
> :
> 
> if any(uvface.flipped for uvface in island.faces):
> 
> if any(island.bounding_box.x > cage_size.x or island.bounding_box.y > 
> cage_size.y for island in self.islands):

You showed examples where you think it would be a good idea to use any/all.
But you didn't say why my examples "may not be such a good idea".
Would you care to elaborate?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Two-Dimensional Expression Layout

2016-08-19 Thread codewizard
For some special cases, I prefer the versions below.


On Friday, August 19, 2016 at 4:56:31 AM UTC-4, Lawrence D’Oliveiro wrote:
> [snip]
> 
> Computing a variable value (using redundant parentheses to avoid 
> backslash-continuations):
> 
> dest_rect = \
> (
> draw_bounds
> +
> Vector(col, row) * draw_bounds.dimensions
> +
> Vector(0, top_extra)
> )

dest_rect = sum([
draw_bounds,
(col, row) * draw_bounds.dimensions,
Vector(0, top_extra),
])


> From , a complex 
> condition (with redundant parentheses again):
> 
> if (
> not isinstance(src, Image)
> or
> mask != None and not isinstance(mask, Image)
> or
> not isinstance(dest, Image)
> ) :
> raise TypeError("image args must be Image objects")
> #end if

if any([
not isinstance(src, Image),
mask != None and not isinstance(mask, Image),
not isinstance(dest, Image),
]):
raise TypeError("image args must be Image objects")

Or equivalently:

if not all([
isinstance(src, Image),
mask is None or isinstance(mask, Image),
isinstance(dest, Image),
]):
raise TypeError("image args must be Image objects")
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting back into PyQt and not loving it.

2016-06-27 Thread codewizard
On Sunday, June 26, 2016 at 5:45:18 PM UTC-4, Michael Torrie wrote:
> 
> Qt's a fantastic toolkit, and the most mature of any of them, and the
> most portable, but man the bindings are not Pythonic at all.

Enaml feels pretty Pythonic to me:

https://github.com/nucleic/enaml
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Continuing indentation

2016-03-02 Thread codewizard
On Wednesday, March 2, 2016 at 3:44:07 PM UTC-5, Skip Montanaro wrote:
> 
> if (some_condition and
> some_other_condition and
> some_final_condition):
> play_bingo()

How about:

  continue_playing = (
  some_condition and
  some_other_condition and
  some_final_condition
  )

  if continue_playing:
  play_bingo()

or:

  play_conditions = [
  some_condition,
  some_other_condition,
  some_final_condition,
  ]

  if all(play_conditions):
  play_bingo()

Regards,
Igor.
-- 
https://mail.python.org/mailman/listinfo/python-list