Re: Keys in dict and keys not in dict

2018-03-19 Thread Peter Otten
Ben Finney wrote:

> Chris Angelico  writes:
> 
>> Sounds like a set operation to me.
>>
>> expected = {"foo", "bar", "spam"}
>> missing = expected - set(json)
> 
> That works (because iterating a dict returns its keys). But it is less
> immediately understandable, IMO, than this::
> 
> expected = {"foo", "bar", "spam"}
> missing = expected - set(json.keys())

There's no need to materialize the set of keys: 

>>> expected = {"foo", "bar", "ham"}
>>> json = dict(foo=1, bar=2, spam=3)
>>> expected - json.keys()
{'ham'}

In Python 2 use json.viewkeys() instead of keys().

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


Re: Keys in dict and keys not in dict

2018-03-19 Thread INADA Naoki
> expected = {"foo", "bar", "spam"}
> missing = expected - set(json.keys())
>

dict.keys() returns set-like object.
So `missing = expected - json.keys()` works fine, and it's more efficient.

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


Is it possible to do something similar to gnome glib's GSource in asyncio?

2018-03-19 Thread Vitaly Krug
I am looking for a way to get a callback each time before asyncio event
loop goes back to waiting on I/O (select, epoll, etc.). Documentation and
googling for the answer hasn't helped yet. I am looking for something
similar to gnome glib's GSource interface  (
https://developer.gnome.org/glib/stable/glib-The-Main-Event-Loop.html#GSource
).

Here is my use case:

Sometimes it's necessary to wrap an asynchronous implementation in a
synchronous API. This is how Pika AMQP client's BlockingConnection adapter
is built on top of Pika's asynchronous SelectConnection adapter without
incurring the overhead of multi-threading.

The blocking wrapper makes calls into the asynchronous layer and runs the
event loop (pika's proprietary select/epoll/kqueue event loop) while
waiting for the asynchronous request to complete.

For no-reply (i.e., no-ack) type of requests, the blocking wrapper simply
waits for the write buffers to empty out before returning - for this, it
checks the size of the write buffer each time before event loop goes back
to waiting for I/O on select/epoll/kqueue. And if the blocking layer finds
that the write buffer has emptied, it stops the event loop, so control can
return to the user of the blocking interface.

So, I need to be able to do something similar in asyncio to facilitate
rebasing BlockingConnection on asyncio in Python3.

Thank you in advance.

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


Re: Is it possible to do something similar to gnome glib's GSource in asyncio?

2018-03-19 Thread Vitaly Krug
Mea culpa! It sounds like I should be able to create a specialized future
to test for my loop exit condition and then use that future with asyncio
loop's `run_until_complete()` method.

On Sat, Mar 17, 2018 at 7:39 PM, Vitaly Krug  wrote:

> I am looking for a way to get a callback each time before asyncio event
> loop goes back to waiting on I/O (select, epoll, etc.). Documentation and
> googling for the answer hasn't helped yet. I am looking for something
> similar to gnome glib's GSource interface  (https://developer.gnome.org/
> glib/stable/glib-The-Main-Event-Loop.html#GSource).
>
> Here is my use case:
>
> Sometimes it's necessary to wrap an asynchronous implementation in a
> synchronous API. This is how Pika AMQP client's BlockingConnection adapter
> is built on top of Pika's asynchronous SelectConnection adapter without
> incurring the overhead of multi-threading.
>
> The blocking wrapper makes calls into the asynchronous layer and runs the
> event loop (pika's proprietary select/epoll/kqueue event loop) while
> waiting for the asynchronous request to complete.
>
> For no-reply (i.e., no-ack) type of requests, the blocking wrapper simply
> waits for the write buffers to empty out before returning - for this, it
> checks the size of the write buffer each time before event loop goes back
> to waiting for I/O on select/epoll/kqueue. And if the blocking layer finds
> that the write buffer has emptied, it stops the event loop, so control can
> return to the user of the blocking interface.
>
> So, I need to be able to do something similar in asyncio to facilitate
> rebasing BlockingConnection on asyncio in Python3.
>
> Thank you in advance.
>
> Vitaly
>
>
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Keys in dict and keys not in dict

2018-03-19 Thread Andrew Z
Beautiful.
Thank you Chris, Ben, Peter and Inada.

On Mar 19, 2018 3:14 AM, "INADA Naoki"  wrote:

> > expected = {"foo", "bar", "spam"}
> > missing = expected - set(json.keys())
> >
>
> dict.keys() returns set-like object.
> So `missing = expected - json.keys()` works fine, and it's more efficient.
>
> --
> INADA Naoki  
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Thank you Python community!

2018-03-19 Thread Etienne Robillard

You guys just made me realize something very obvious. :-)

I'm in the process right now of watching the excellent documentary named 
"Drugs Inc." on Netflix and I'm basically stunned and deeply concerned 
about the major opioid epidemic in the US.


I would like to thank you guys sincerely for helping a lot of people to 
stay clean, and focus on programming high-level stuff in Python instead 
of doing some really nasty drugs.


I'm also wondering, could we exploit this strategy even further to help 
people willing to stop doing drugs by teaching them some stuff in Python?


Murdering random drug dealers won't help out, i'm afraid.

Neither do putting some of them in jail is sufficient to prevent people 
from trying out cocaine and heroin it seems.


So, I would like to take this opportunity to advocate for this precise 
form of rehabilitation using open source software programming as a 
vector to make people use their brains in positive ways.


The trick I think is to let people use programming as a way to socialize 
more in order to stimulate or distract their minds whiling keeping them 
away from drugs.


It's time we regroup and combine our forces to help people who really 
needs our help.



Sincerely,

Etienne


--
Etienne Robillard
tkad...@yandex.com
https://www.isotopesoftware.ca/

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


Re: how do I retry a command only for a specific exception / error

2018-03-19 Thread Ganesh Pal
On Fri, Mar 16, 2018 at 11:21 AM, Steven D'Aprano <
steve+comp.lang.pyt...@pearwood.info> wrote:

> On Fri, 16 Mar 2018 11:04:22 +0530, Ganesh Pal wrote:
>
> > All that I  am trying to do here is write a generic function that will
> >  re-retry
> > the command  few more times before failing the test
>
>
> Something like this should do it. It gives up immediately on fatal errors
> and tries again on temporary ones. (You have to specify what you consider
> fatal or temporary, of course.) It uses exponential backup to wait longer
> and longer each time you fail, before eventually giving up.
>
>
> This is a good suggestion ,  I like the way this is written , but what I
> have failed to figure out is how to translate the possible  
> TemporaryFailureErrors
> to a different exception class/type  and retry .
>
>  In my case ,  every  command is executed using a run() function  that
> calls out to subprocess.Popen().   Which will return  stdout, stderr,
> exit_code and we would need to retry only for a specific
> TemporaryFailureError .
>
>
>
> Example : Say , If we are not able to  SSH  to the host  , and I get
> “connection refused” error I would want to retry only for this specific case
>
>
>
> # Sample modified code
>
>
>
> delay = 2
>
> max_attempts =4
> for attempts in range(max_attempts):
> try:
>  cmd = "ssh  r...@localhost.com"
>
> stdout, stderr, exit_code = run(cmd, timeout=300)
>
> print stdout, stderr, exit_code
>
> if exit_code != 0:
>
> raise RuntimeError("ERROR (exit_code %d): "
>
>"\nstdout: %s\nstderr: %s\n" % (exit_code,
> stdout, stderr))
>
> except Exeception as e :
> raise
>
> # if we have “connection refused” error then retry after some time
> except TemporaryFailureError:
> sleep(delay)
> delay *= 2
> else:
> break
> else:
> raise RuntimeError("too many attempts")
>
>
>
>
Regards,
Ganesh
-- 
https://mail.python.org/mailman/listinfo/python-list


Style Q: Instance variables defined outside of __init__

2018-03-19 Thread Irv Kalb
I am building some classes for use in future curriculum.  I am using PyCharm 
for my development.  On the right hand edge of the PyCharm editor window, you 
get some little bars indicating warnings or errors in your code.  I like this 
feature and try to clean up as many of those as I can.  However, there is one 
warning that I am seeing often, and I'm not sure about how to handle it.  The 
warning I see is:

"Instance attribute  defined outside of __init__ ... "

The following is a simple example.  I am creating a card class that I am using 
to build card games with PyGame.  
class Card():

BACK_OF_CARD_IMAGE = pygame.image.load('images/backOfCard.png')

def __init__(self, window, name, suit, value):
self.window = window
self.suit = suit
self.cardName = name + ' of ' + suit
self.value = value
fileName = 'images/' + self.cardName + '.png'
self.image = pygame.image.load(fileName)
self.backOfCardImage = Card.BACK_OF_CARD_IMAGE

self.conceal()

def conceal(self):
self.faceUp = False

def reveal(self):
self.faceUp = True


In this class, I get warnings on the single lines of the conceal and reveal 
methods.  Yes, the warnings are correct, the variable "self.faceUp" is not 
defined inside the __init__ method.  My __init__ method calls self.conceal 
which is a more logical place to initialize this variable.
My question is, what is the Pythonic way to handle this?  In the research that 
I have done, I see split results.  Some people say that this type of thing is 
fine and these warnings should just be ignored.  While others say that all 
instance variables should be defined in the __init__ method.  I like that idea 
(and have done so in other languages), but if I define this variable there, 
what value should I give it?  Do I redundantly set it to the proper starting 
value (in case False), or do as others have suggested, set it to None (which 
seems a little odd for something that I will use as a Boolean).

I have many more similar cases.  For example, in many small game programs, at 
the end of my __init__ method, I call a "reset" method in the same class which 
initializes a bunch of instance variables for playing a game.  When the game is 
over, if the user wants to play again, I call the same reset method.  Very 
clean, and works very well, but all the instance variables defined in that 
reset method gets the same warning messages.
Thanks,
Irv

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


Re: Style Q: Instance variables defined outside of __init__

2018-03-19 Thread Ned Batchelder

On 3/19/18 1:04 PM, Irv Kalb wrote:

I am building some classes for use in future curriculum.  I am using PyCharm 
for my development.  On the right hand edge of the PyCharm editor window, you 
get some little bars indicating warnings or errors in your code.  I like this 
feature and try to clean up as many of those as I can.  However, there is one 
warning that I am seeing often, and I'm not sure about how to handle it.  The 
warning I see is:

"Instance attribute  defined outside of __init__ ..."

The following is a simple example.  I am creating a card class that I am using 
to build card games with PyGame.
class Card():

 BACK_OF_CARD_IMAGE = pygame.image.load('images/backOfCard.png')

 def __init__(self, window, name, suit, value):
 self.window = window
 self.suit = suit
 self.cardName = name + ' of ' + suit
 self.value = value
 fileName = 'images/' + self.cardName + '.png'
 self.image = pygame.image.load(fileName)
 self.backOfCardImage = Card.BACK_OF_CARD_IMAGE

 self.conceal()

 def conceal(self):
 self.faceUp = False

 def reveal(self):
 self.faceUp = True
 

In this class, I get warnings on the single lines of the conceal and reveal methods.  
Yes, the warnings are correct, the variable "self.faceUp" is not defined inside 
the __init__ method.  My __init__ method calls self.conceal which is a more logical place 
to initialize this variable.
My question is, what is the Pythonic way to handle this?  In the research that 
I have done, I see split results.  Some people say that this type of thing is 
fine and these warnings should just be ignored.  While others say that all 
instance variables should be defined in the __init__ method.  I like that idea 
(and have done so in other languages), but if I define this variable there, 
what value should I give it?  Do I redundantly set it to the proper starting 
value (in case False), or do as others have suggested, set it to None (which 
seems a little odd for something that I will use as a Boolean).


I understand this tension: it's nice to assign only meaningful values, 
and to do it in as few places as possible.  But it's also nice to have 
all of your attributes in one place.  This is a by-product of Python 
having no declarations, only definitions (assignments).  So to mention 
the attributes initially, you have to choose a value for them.  If I 
were to add faceUp to __init__, I would assign False to it.


I have many more similar cases.  For example, in many small game programs, at the end of 
my __init__ method, I call a "reset" method in the same class which initializes 
a bunch of instance variables for playing a game.  When the game is over, if the user 
wants to play again, I call the same reset method.  Very clean, and works very well, but 
all the instance variables defined in that reset method gets the same warning messages.


You didn't ask about this, so perhaps you already know it, but you can 
disable this particular Pylint warning, either line-by-line, 
file-by-file, or for the entire project.


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


Re: Style Q: Instance variables defined outside of __init__

2018-03-19 Thread Ethan Furman

On 03/19/2018 10:04 AM, Irv Kalb wrote:


I am building some classes for use in future curriculum.  I am using PyCharm 
for my development.  On the right hand edge of the PyCharm editor window, you 
get some little bars indicating warnings or errors in your code.  I like this 
feature and try to clean up as many of those as I can.  However, there is one 
warning that I am seeing often, and I'm not sure about how to handle it.  The 
warning I see is:

"Instance attribute  defined outside of __init__ ..."

The following is a simple example.  I am creating a card class that I am using 
to build card games with PyGame.
class Card():

 BACK_OF_CARD_IMAGE = pygame.image.load('images/backOfCard.png')

 def __init__(self, window, name, suit, value):
 self.window = window
 self.suit = suit
 self.cardName = name + ' of ' + suit
 self.value = value
 fileName = 'images/' + self.cardName + '.png'
 self.image = pygame.image.load(fileName)
 self.backOfCardImage = Card.BACK_OF_CARD_IMAGE

 self.conceal()

 def conceal(self):
 self.faceUp = False

 def reveal(self):
 self.faceUp = True
 

In this class, I get warnings on the single lines of the conceal and reveal methods.  
Yes, the warnings are correct, the variable "self.faceUp" is not defined inside 
the __init__ method.  My __init__ method calls self.conceal which is a more logical place 
to initialize this variable.
My question is, what is the Pythonic way to handle this?  In the research that 
I have done, I see split results.  Some people say that this type of thing is 
fine and these warnings should just be ignored.  While others say that all 
instance variables should be defined in the __init__ method.  I like that idea 
(and have done so in other languages), but if I define this variable there, 
what value should I give it?  Do I redundantly set it to the proper starting 
value (in case False), or do as others have suggested, set it to None (which 
seems a little odd for something that I will use as a Boolean).

I have many more similar cases.  For example, in many small game programs, at the end of 
my __init__ method, I call a "reset" method in the same class which initializes 
a bunch of instance variables for playing a game.  When the game is over, if the user 
wants to play again, I call the same reset method.  Very clean, and works very well, but 
all the instance variables defined in that reset method gets the same warning messages.


Define them in __init__; otherwise, you get an error if reveal() is called before conceal() is.  Also, a card is either 
revealed or concealed, it can't be both and it can't be neither -- so set it in __init__.


As a side note:  I find card_name easier to read than cardName.  :)

--
~Ethan~

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


Re: Style Q: Instance variables defined outside of __init__

2018-03-19 Thread Chris Angelico
On Tue, Mar 20, 2018 at 4:25 AM, Ethan Furman  wrote:
> Define them in __init__; otherwise, you get an error if reveal() is called
> before conceal() is.  Also, a card is either revealed or concealed, it can't
> be both and it can't be neither -- so set it in __init__.

__init__ calls conceal.

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


Re: Thank you Python community!

2018-03-19 Thread bartc

On 19/03/2018 16:08, Etienne Robillard wrote:

You guys just made me realize something very obvious. :-)

I'm in the process right now of watching the excellent documentary named 
"Drugs Inc." on Netflix and I'm basically stunned and deeply concerned 
about the major opioid epidemic in the US.


I would like to thank you guys sincerely for helping a lot of people to 
stay clean, and focus on programming high-level stuff in Python instead 
of doing some really nasty drugs.


I'm also wondering, could we exploit this strategy even further to help 
people willing to stop doing drugs by teaching them some stuff in Python?


You either code in Python, or you're forced to take drugs? Got it.

The trick I think is to let people use programming as a way to socialize 
more in order to stimulate or distract their minds whiling keeping them 
away from drugs.


I've often wondered what the guys who invented C (around 1970) must have 
been smoking to have come up with some of those ideas.



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


Re: Thank you Python community!

2018-03-19 Thread Larry Martell
On Mon, Mar 19, 2018 at 12:08 PM, Etienne Robillard  wrote:
> You guys just made me realize something very obvious. :-)
>
> I'm in the process right now of watching the excellent documentary named
> "Drugs Inc." on Netflix and I'm basically stunned and deeply concerned about
> the major opioid epidemic in the US.

Have no clue what this has to do with python, but the opioid epidemic
was created by collision between big pharma and the government.
-- 
https://mail.python.org/mailman/listinfo/python-list


Missing python36.dll

2018-03-19 Thread Adrian Ordona
Hi - just downloaded the latest version of Python (3.6.4) but keep getting an 
error
because of missing .dll file. i tried uninstalling and reinstalling it but 
still getting the same error. Search online for the file but to no avail. Can 
someone direct me as to where to download the missing dll file or help me with 
the issue.

thanks,
Adrian
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Thank you Python community!

2018-03-19 Thread Tim Daneliuk
On 03/19/2018 02:05 PM, bartc wrote:
> I've often wondered what the guys who invented C (around 1970) must have been 
> smoking to have come up with some of those ideas.

I dunno, but I do know that - if they were smoking something - it was
rolled in greenbar paper ...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Thank you Python community!

2018-03-19 Thread Rob Gaddi

On 03/19/2018 12:40 PM, Tim Daneliuk wrote:

On 03/19/2018 02:05 PM, bartc wrote:

I've often wondered what the guys who invented C (around 1970) must have been 
smoking to have come up with some of those ideas.


I dunno, but I do know that - if they were smoking something - it was
rolled in greenbar paper ...



"Look, you can make a filter out of the pinfeed!"

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


Re: Thank you Python community!

2018-03-19 Thread Etienne Robillard



Le 2018-03-19 à 15:21, Larry Martell a écrit :

On Mon, Mar 19, 2018 at 12:08 PM, Etienne Robillard  wrote:

You guys just made me realize something very obvious. :-)

I'm in the process right now of watching the excellent documentary named
"Drugs Inc." on Netflix and I'm basically stunned and deeply concerned about
the major opioid epidemic in the US.

Have no clue what this has to do with python, but the opioid epidemic
was created by collision between big pharma and the government.
Quite simply, coding stuff in Python (or any other high-level 
programming language) is probably a very effective (and underestimated) 
way to help people in need finding a real goal in their life and the 
feeling of accomplishment.


Etienne

--
Etienne Robillard
tkad...@yandex.com
https://www.isotopesoftware.ca/

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


Re: Missing python36.dll

2018-03-19 Thread MRAB

On 2018-03-19 19:33, Adrian Ordona wrote:

Hi - just downloaded the latest version of Python (3.6.4) but keep getting an 
error
because of missing .dll file. i tried uninstalling and reinstalling it but 
still getting the same error. Search online for the file but to no avail. Can 
someone direct me as to where to download the missing dll file or help me with 
the issue.


You didn't say which installer you used.

I've just updated from Python 3.6.3 to Python 3.6.4 using the 
"executable installer" 
(https://www.python.org/downloads/release/python-364/). I didn't have a 
problem; the DLL was also updated (it's in the Python folder next to 
"python.exe").

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


Re: Missing python36.dll

2018-03-19 Thread Jerry Hill
On Mon, Mar 19, 2018 at 5:07 PM, MRAB  wrote:

> You didn't say which installer you used.
>

​It might also be helpful to know:

Did you install python for "Just Me" or "All Users" in the installer?

Does the user you're logged in as have enough authority to install for All
Users if that's what you picked?

What OS ​are you using?  Since you're asking about DLLs, it's obviously
some flavor of Windows, but you don't say which one.

Did you notice any errors messages or log files generated by the installer?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Thank you Python community!

2018-03-19 Thread Ben Finney
Etienne Robillard  writes:

> I would like to thank you guys sincerely for helping a lot of people
> to stay clean, and focus on programming high-level stuff in Python
> instead of doing some really nasty drugs.

Thank you for the kind words.

I'd love to believe the Python community has the significant benefit you
describe. That just raises the importance of being skeptical (because I
*want* it to be true, means more rigour is needed to avoid the bias to
believe it; read about “confirmation bias” to see the problem).

So, in the interest of having our beliefs match the facts: What is the
verifiable, statistically sound evidence that this effect actually
occurs as a result of the Python community's help with programming?
Where is it pbulished so we can see it? What is the size of the measured
effect?

> It's time we regroup and combine our forces to help people who really
> needs our help.

Combining forces to help the needy is a sentiment I can fully endorse,
for sure.

-- 
 \   "Success is going from one failure to the next without a loss |
  `\ of enthusiasm."  -- Winston Churchill |
_o__)  |
Ben Finney

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


Re: Style Q: Instance variables defined outside of __init__

2018-03-19 Thread Ben Finney
Irv Kalb  writes:

> In this class, I get warnings on the single lines of the conceal and
> reveal methods.

This is good! It prompts the question: Why are those methods defined as
they are?

If those methods are only ever intended to set the value of an
attribute: Why not just set that attribute directly? (Remember that
Python properties allow you to postpone the decision later of whether
that attribute is a property.)

If those methods are intended to later expand to have side effects: Why
are you calling those methods from the initialiser? The initialiser
should instead just set the initial state of the attributes, avoiding
whatever side-effects are in ‘conceal’ etc.

So, it seems that the warning is correct. The initialiser's job is to
initialise the instance, it should not accidentally invoke a bunch of
side effects. This means the initialiser should tend to just setting
attribute values, not calling a bunch of other methods.

-- 
 \“It is undesirable to believe a proposition when there is no |
  `\   ground whatever for supposing it true.” —Bertrand Russell, _The |
_o__)   Value of Scepticism_, 1928 |
Ben Finney

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


Re: Thank you Python community!

2018-03-19 Thread Etienne Robillard

Hi Ben,

Thank you for your reply.

I would like to make such an experimental research/investigation on the 
effects of Python software programming on opioid addiction. :-)


Probably studying the learning of Python in people with cocaine and 
heroin addiction would be significant and interesting.


Kind regards,

Etienne


Le 2018-03-19 à 17:58, Ben Finney a écrit :

Etienne Robillard  writes:


I would like to thank you guys sincerely for helping a lot of people
to stay clean, and focus on programming high-level stuff in Python
instead of doing some really nasty drugs.

Thank you for the kind words.

I'd love to believe the Python community has the significant benefit you
describe. That just raises the importance of being skeptical (because I
*want* it to be true, means more rigour is needed to avoid the bias to
believe it; read about “confirmation bias” to see the problem).

So, in the interest of having our beliefs match the facts: What is the
verifiable, statistically sound evidence that this effect actually
occurs as a result of the Python community's help with programming?
Where is it pbulished so we can see it? What is the size of the measured
effect?


It's time we regroup and combine our forces to help people who really
needs our help.

Combining forces to help the needy is a sentiment I can fully endorse,
for sure.



--
Etienne Robillard
tkad...@yandex.com
https://www.isotoperesearch.ca/

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


Re: Thank you Python community!

2018-03-19 Thread Ben Finney
Etienne Robillard  writes:

> I would like to make such an experimental research/investigation on
> the effects of Python software programming on opioid addiction. :-)

Okay. The wording of your message implied that you know this already
happens now, though. How did you come to know this?

-- 
 \ “Experience is that marvelous thing that enables you to |
  `\   recognize a mistake when you make it again.” —Franklin P. Jones |
_o__)  |
Ben Finney

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


Re: Style Q: Instance variables defined outside of __init__

2018-03-19 Thread Steven D'Aprano
On Mon, 19 Mar 2018 10:04:53 -0700, Irv Kalb wrote:

> Some people say
> that this type of thing is fine and these warnings should just be
> ignored.  While others say that all instance variables should be defined
> in the __init__ method.

Whenever anyone says "you should do this", the question to ask is, "what 
bad thing will happen if I don't?"

You are getting a warning that self.faceUp is not defined in __init__. 
That means that there must be something bad that will happen if you don't 
define faceUp in __init__. Any idea what?

If there is no such bad thing that will happen, then PyCharm is crying 
wolf: it is wasting your time with a warning for a non-problem.


> I like that idea (and have done so in other
> languages), but if I define this variable there, what value should I
> give it?  Do I redundantly set it to the proper starting value (in case
> False), 

Why is it redundant? Since you're going to call conceal() anyway, why not 
just set the value and not bother with conceal? Especially since conceal 
appears to do nothing but set the flag.

Maybe it is *conceal* which is redundant and needs to be removed. On the 
other hand, 

instance.conceal()
instance.reveal()

is much more descriptive than "faceUp = True".


> or do as others have suggested, set it to None (which seems a
> little odd for something that I will use as a Boolean).

Ah yes, the good old "rubbish advice from the internet" strike again.

Unless your faceUp is intended to represent a *three state flag* (say, 
face up, face down, and standing on its side...) then why distinguish 
between None and False? What possible benefit to this is it?

My guess is that they're thinking that setting it to None indicates that 
it is uninitialised. Except that None is a perfectly good falsey value, 
so unless you specifically and carefully change *all* your code that 
currently says:

if self.faceUp: ... 

into:

if self.faceUp is None: raise SomeError
elif self.faceUp: ...

then it makes no difference at all. Just use False and be done with it.


> I have many more similar cases.  For example, in many small game
> programs, at the end of my __init__ method, I call a "reset" method in
> the same class which initializes a bunch of instance variables for
> playing a game.  When the game is over, if the user wants to play again,
> I call the same reset method.  Very clean, and works very well, but all
> the instance variables defined in that reset method gets the same
> warning messages.

Indeed. Linters and code checkers often waste your time warning you 
against things that aren't wrong.



-- 
Steve

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


{:2X} didn't output what I expected

2018-03-19 Thread jfong
D:\Temp>py
Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 19:28:18) [MSC v.1600 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> '{:02X}'.format(256)
'100'
>>>
What I expected is '00'. Am I wrong?

Best Regards,
Jach Fong
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Thank you Python community!

2018-03-19 Thread Etienne Robillard



Le 2018-03-19 à 19:36, Ben Finney a écrit :

Etienne Robillard  writes:


I would like to make such an experimental research/investigation on
the effects of Python software programming on opioid addiction. :-)

Okay. The wording of your message implied that you know this already
happens now, though. How did you come to know this?

I'm not really sure what you mean here. Anyways, i found "Drugs Inc." a 
highly informative and educational documentary.


I just thought that doing some Python coding should be a very effective 
way to stimulate your brain in positive ways.


Etienne

--
Etienne Robillard
tkad...@yandex.com
https://www.isotopesoftware.ca/

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


Re: {:2X} didn't output what I expected

2018-03-19 Thread Chris Angelico
On Tue, Mar 20, 2018 at 10:46 AM,   wrote:
> D:\Temp>py
> Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 19:28:18) [MSC v.1600 32 bit 
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
 '{:02X}'.format(256)
> '100'

> What I expected is '00'. Am I wrong?
>

Python avoids losing data. If you really want to enforce that this is
two characters long, you can either restrict the data first (maybe
with "% 256"), or trim the resulting string:

>>> '{:02X}'.format(256)[-2:]
'00'

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


Re: {:2X} didn't output what I expected

2018-03-19 Thread jfong
Chris Angelico於 2018年3月20日星期二 UTC+8上午8時06分05秒寫道:
> On Tue, Mar 20, 2018 at 10:46 AM,   wrote:
> > D:\Temp>py
> > Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 19:28:18) [MSC v.1600 32 
> > bit (Intel)] on win32
> > Type "help", "copyright", "credits" or "license" for more information.
>  '{:02X}'.format(256)
> > '100'
> 
> > What I expected is '00'. Am I wrong?
> >
> 
> Python avoids losing data. If you really want to enforce that this is
> two characters long, you can either restrict the data first (maybe
> with "% 256"), or trim the resulting string:
> 
> >>> '{:02X}'.format(256)[-2:]
> '00'
> 
> ChrisA

I had overlooked the document there it says "width ... defining the minimum 
field width...'. I was wrong, it's not a demand. Thank you, ChrisA.

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


Re: {:2X} didn't output what I expected

2018-03-19 Thread Chris Angelico
On Tue, Mar 20, 2018 at 11:32 AM,   wrote:
> Chris Angelico於 2018年3月20日星期二 UTC+8上午8時06分05秒寫道:
>> On Tue, Mar 20, 2018 at 10:46 AM,   wrote:
>> > D:\Temp>py
>> > Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 19:28:18) [MSC v.1600 32 
>> > bit (Intel)] on win32
>> > Type "help", "copyright", "credits" or "license" for more information.
>>  '{:02X}'.format(256)
>> > '100'
>> 
>> > What I expected is '00'. Am I wrong?
>> >
>>
>> Python avoids losing data. If you really want to enforce that this is
>> two characters long, you can either restrict the data first (maybe
>> with "% 256"), or trim the resulting string:
>>
>> >>> '{:02X}'.format(256)[-2:]
>> '00'
>>
>> ChrisA
>
> I had overlooked the document there it says "width ... defining the minimum 
> field width...'. I was wrong, it's not a demand. Thank you, ChrisA.

Yep. It's a policy that goes back a long way. These kinds of width
markers are often used for columnar data; but if something doesn't
fit, it's far better to push the column out a bit (ugly) than to chop
off a digit (loss of data, especially bad if it trims from the front).
So if you actually DO want that, you need to specifically request it.

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


Re: Thank you Python community!

2018-03-19 Thread Rick Johnson
On Monday, March 19, 2018 at 6:37:21 PM UTC-5, Ben Finney wrote:

> --
>  \   "Success is going from one failure to the next without a loss |
>   `\ of enthusiasm."  -- Winston Churchill |
> _o__)  |
> Ben Finney


> --
>  \ “Experience is that marvelous thing that enables you to |
>   `\   recognize a mistake when you make it again.” —Franklin P. Jones |
> _o__)  |
> Ben Finney

Okay Ben, i believe it's time to come clean and finally admit to this fine
community, that these quotes of yours are not merely chosen at random, but are
in fact, delectable morsels of laser-focused sarcasm.

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


how to obtain the text for BeautifulSoup object

2018-03-19 Thread Nathan Zhu
 Hi Team,

could anyone help me?

for webpage having source code like this:
...

number
name


I only can use below sentence, since there are a lot of tag em and tag a in
other area.
output = bs4.BeautifulSoup(res.content,'lxml').findAll("span",{"class":"xst
thread-name"})

how can I get the text in tag em and tag a under tag span?

thank you for your support!

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


Re: Style Q: Instance variables defined outside of __init__

2018-03-19 Thread Terry Reedy

On 3/19/2018 1:04 PM, Irv Kalb wrote:

However, there is one warning that I am seeing often, an > I'm not sure about 
how to handle it.  The warning I see is:

"Instance attribute  defined outside of __init__ ..."


Style checkers are notorious for sometimes giving bad advice and being 
overly opinionated.


I think a claim that in all programs all attributes should be set *in* 
__init__, as opposed to *during* initialization, is wrong.  All 
attribute setting is side-effect from a functional view (and usually 
'bad' to a functionalist).  There is no reason to not delegate some of 
it to sub-init functions when it makes sense to do do.  There is good 
reason to do so when it makes the code easier to understand *and test*.


Example: the IDLE's options setting dialog.  Until last summer, it was 
one class* with at perhaps a thousand lines of initialization code (with 
no automated test).  To me, the dictate that they should have all been 
in the __init__ function is absurd.  Fortunately, there were about 9 
subsidiary functions.


* We split off a class for each tab, but keep the separate functions to 
create the tab page widgets and load them with current values.



The following is a simple example.  I am creating a card class that I am using 
to build card games with PyGame.
class Card():

 BACK_OF_CARD_IMAGE = pygame.image.load('images/backOfCard.png')

 def __init__(self, window, name, suit, value):
 self.window = window
 self.suit = suit
 self.cardName = name + ' of ' + suit
 self.value = value
 fileName = 'images/' + self.cardName + '.png'
 self.image = pygame.image.load(fileName)
 self.backOfCardImage = Card.BACK_OF_CARD_IMAGE

 self.conceal()

 def conceal(self):
 self.faceUp = False

 def reveal(self):
 self.faceUp = True


If the single line is all these functions do, I *might* suggest getting 
rid of them.  But this is really a separate issue.


--
Terry Jan Reedy

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