Re: Can somebody tell me what's wrong wrong with my code? I don't understand

2016-11-23 Thread Larry Hudson via Python-list

On 11/21/2016 07:10 PM, rmjbr...@gmail.com wrote:

Hi! This is my first post! I'm having trouble understanding my code. I get 
"SyntaxError:invalid syntax" on line 49. I'm trying to code a simple text-based 
rpg on repl.it. Thank you for reading.



print("Welcome to Gladiator Game! Choose your character race, class, and starting 
equipment!")

print('')

print("Race selection: ")

print('')

print("(1) Orcs. Known for their very wide, robust physiques. They are the strongest 
of all the races in Polaris.")

print('')

print("(2) Elves. Thin and wiry. They are known for their amazing agility and 
hand-eye coordiation. They originate from the desert island of Angolia.")

print('')

print("(3) Silverbacks. A hairy, ape-like race from Nothern Polaris. Their metal fur 
provides them with much needed protection.")

print('')

print("(4) Pomongos. An amphibian race believed to inhabit the wet jungles of 
Central Polaris. Legends say they have highly corrosive spit...")

print('')

raceNum=int(input("Select your character's race by entering the corresponding 
number. Then press enter: "))

print('')

while raceNum<1 or raceNum>4:
  raceNum=int(input('Invalid input. Try again: '))

print('')

if raceNum==1:
  print("You're an orc, eh? I won't be sayin' anything mean about you...")
  print('')
  classNum=int(input("What's your profession big fella?"))

elif raceNum==2:
  print("I never liked you elven folk...Let's get on with this.")
  print('')
  classNum=int(input("What's your profession ? Do ye even have one ?"))

elif raceNum==3:
  print("Nice fur. I don't see too many of your kind 'round here. Maybe that's a 
good thing...")
  print('')
  classNum=int(input("What's your profession mate?")

elif raceNum==4: #this line has an error for some reason
  print("Your a 'Mongo eh? I thought you lads were extinct...Just keep your tongue 
in ya mouth and we'll get along fine mate.")
  classNum=int(input("What's your profession?"))



You've already received answers about your typo so I won't repeat that.  However I have a couple 
minor suggestions about your approach.


First, the empty string in your print('') statements is unnecessary.  Just use print(), it does 
the same thing.


Next your menu for the raceNum selection is straight-forward, and there is nothing wrong with 
that.  But another approach that might be a bit shorter is to use a list of strings displayed in 
a loop.  Something like this (very simplified) example...



options = ['First option',
'Next option',
'One more time',
#  etc
]
#  This version assumes the option number is part of the strings
for opt in options:
print(opt)
print()#  If you really want the double-spacing, personally I don't 
think it's needed


Here's a bit more advanced version of the for loop, this one assumnes the option numbers are not 
in the strings in the list...



for num, opt in enumerate(options, 1):
print('({})  {}'.format(num, opt))#  OR   print('(%d)  %s' % (num, opt))
print()#  Again, double-spacing is optional


A similar approach could be used for your classNum section.

Just some suggestions to read/study/adapt...  or ignore.  Whatever you feel 
like.  ;-)

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


Re: How to you convert list of tuples to string

2016-11-23 Thread Larry Hudson via Python-list

On 11/22/2016 08:51 AM, Michiel Overtoom wrote:

Hi Ganesh,


Any better suggestion to improve this piece of code and make it look more 
pythonic?



import random

# A list of tuples. Note that the L behind a number means that the number is a 
'long'.

data = [(1, 1, 373891072L, 8192), (1, 3, 390348800L, 8192), (1, 4, 372719616L,
8192), (2, 3, 382140416L, 8192), (2, 5, 398721024L, 8192), (3, 1,
374030336L, 8192), (3, 3, 374079488L, 8192), (3, 5, 340058112L, 8192)]

item = random.choice(data)  # Select a random item from the 'data' list.

msg = "%d,%d,%d:%d" % item  # Format it in the way you like.

print msg


Greetings,



Or using the new string formatting syntax:

msg = '{},{},{}:{}'.format(*item)

The *item in the format() unpacks the tuple.

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


Is this pythonic?

2016-11-23 Thread Frank Millman

Hi all

Sometimes I write something that I think is quite clever, but later on I 
look at it and ask 'What was I thinking?'.


I have just come up with a 'clever' solution to a problem. Would this cause 
raised eyebrows if you were reviewing this?


I have a class that represents a single database column - there could be 
hundreds of instances at any time.


The class has a getval() method to return the current value.

Usually the value is stored in the instance, and can be returned 
immediately, but sometimes it has to be computed, incurring further database 
lookups.


In many cases the computed value is never actually requested, so I want to 
delay the computation until the first call to getval().


I could add an 'if computation_required: ' block to getval(), but I am 
trying to avoid that, partly because this would have to be checked for every 
call to getval() but would only used in a small number of cases, and partly 
because I have a few subclasses where getval() is over-ridden so I would 
have to add the extra code to every one (or call the superclass on every 
one).


This is what I have come up with.

1. Rename all instances of 'getval()' to '_getval()'.

2. Add a new method '_getval_with_comp()'.

3. When instantiating an object, check if it would need computation -
   if computation_required:
   self.getval = self._getval_with_comp
   else:
   self.getval = self._getval

4. In _getval_with_comp, perform the computation, then add the following -
   self.getval = self._getval
   return self._getval()

What is the verdict? -1, 0, or +1?

Frank Millman


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


Re: Is this pythonic?

2016-11-23 Thread Marko Rauhamaa
"Frank Millman" :

> 3. When instantiating an object, check if it would need computation -
>if computation_required:
>self.getval = self._getval_with_comp
>else:
>self.getval = self._getval
>
> 4. In _getval_with_comp, perform the computation, then add the following -
>self.getval = self._getval
>return self._getval()
>
> What is the verdict? -1, 0, or +1?

Perfectly cromulent, run-of-the-mill Python code.


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


Re: Is this pythonic?

2016-11-23 Thread Frank Millman

"Marko Rauhamaa"  wrote in message news:87inrer0dl@elektro.pacujo.net...


"Frank Millman" :




> What is the verdict? -1, 0, or +1?

Perfectly cromulent, run-of-the-mill Python code.



A new word to add to my vocabulary - thanks :-)

Frank


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


Re: Question about working with html entities in python 2 to use them as filenames

2016-11-23 Thread Steven Truppe

type=  title =  Wizo - Anderster Full Album - YouTube
type=  title =  Wizo - Bleib Tapfer / für'n Arsch Full 
Album - YouTube

Traceback (most recent call last):
  File "./music-fetcher.py", line 39, in 
title = HTMLParser.HTMLParser().unescape(title)
  File "/usr/lib/python2.7/HTMLParser.py", line 475, in unescape
return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", 
replaceEntities, s)

  File "/usr/lib/python2.7/re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: 
ordinal not in range(128)


The pastebins from below are showing how i parse the html data from the 
 and i wan to have a normal filename with Ü,Ö etc if possible,


i've tried converting with decode('utf-8') and encode or str.encode() 
and other thing but i think i'm missing here.



I want to create filename out of the DATA, it's realy 
important.



Hope in regards,

Truppe Steven


On 2016-11-23 02:32, Steve D'Aprano wrote:

On Wed, 23 Nov 2016 09:00 am, Lew Pitcher wrote:


2) Apparently os.mkdir() (at least) defaults to requiring an ASCII
pathname.

No, you have misinterpreted what you have seen.

Even in Python 2, os.mkdir will accept a Unicode argument. You just have to
make sure it is given as unicode:

os.mkdir(u'/tmp/für')

Notice the u' delimiter instead of the ordinary ' delimiter? That tells
Python to use a unicode (text) string instead of an ascii byte-string.

If you don't remember the u' delimiter, and write an ordinary byte-string '
delimiter, then the result you get will depend on some combination of your
operating system, the source code encoding, and Python's best guess of what
you mean.

os.mkdir('/tmp/für')  # don't do this!

*might* work, if all the factors align correctly, but often won't. And when
it doesn't, the failure can be extremely mysterious, usually involving a
spurious

UnicodeDecodeError: 'ascii' codec

error.

Dealing with Unicode text is much simpler in Python 3. Dealing with
*unknown* encodings is never easy, but so long as you can stick with
Unicode and UTF-8, Python 3 makes it easy.






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


Re: How to you convert list of tuples to string

2016-11-23 Thread Ned Batchelder
On Wednesday, November 23, 2016 at 3:43:05 AM UTC-5, Larry Hudson wrote:
> On 11/22/2016 08:51 AM, Michiel Overtoom wrote:
> > Hi Ganesh,
> >
> >> Any better suggestion to improve this piece of code and make it look more 
> >> pythonic?
> >
> >
> > import random
> >
> > # A list of tuples. Note that the L behind a number means that the number 
> > is a 'long'.
> >
> > data = [(1, 1, 373891072L, 8192), (1, 3, 390348800L, 8192), (1, 4, 
> > 372719616L,
> > 8192), (2, 3, 382140416L, 8192), (2, 5, 398721024L, 8192), (3, 1,
> > 374030336L, 8192), (3, 3, 374079488L, 8192), (3, 5, 340058112L, 8192)]
> >
> > item = random.choice(data)  # Select a random item from the 'data' list.
> >
> > msg = "%d,%d,%d:%d" % item  # Format it in the way you like.
> >
> > print msg
> >
> >
> > Greetings,
> >
> 
> Or using the new string formatting syntax:
> 
> msg = '{},{},{}:{}'.format(*item)
> 
> The *item in the format() unpacks the tuple.


"new" == "Introduced in 2.6, available since 2008" :)

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


Re: Is this pythonic?

2016-11-23 Thread Frank Millman

"Marko Rauhamaa"  wrote in message news:87inrer0dl@elektro.pacujo.net...

"Frank Millman" :


> 3. When instantiating an object, check if it would need computation -
>if computation_required:
>self.getval = self._getval_with_comp
>else:
>self.getval = self._getval
>
> 4. In _getval_with_comp, perform the computation, then add the 
> following -

>self.getval = self._getval
>return self._getval()
>
> What is the verdict? -1, 0, or +1?

Perfectly cromulent, run-of-the-mill Python code.



Gah! The law of unintended consequences strikes again!

As I mentioned, the class in question represents a database column. A 
separate class represents a database row. I have a __str__() method on the 
'row' class that prints a nicely formatted representation of the object with 
all of its column objects and their values.


With the above changes, I had to turn getval() into a coroutine. My 
__str__() method uses getval() to obtain the values, so I had to prefix 
getval() with 'await', but then I get a syntax error on __str__(). I can add 
'async' to remove the syntax error, but then print(obj) does not work - 
TypeError: __str__ returned non-string (type coroutine)


I don't think there is an answer to this, but any suggestions will be 
appreciated.


I can say 'print(await obj.__str__())', and it works, but I lose the ability 
to include it in a larger print statement.


Ah well :-(

Frank


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


Re: Is this pythonic?

2016-11-23 Thread Steve D'Aprano
On Wed, 23 Nov 2016 08:10 pm, Frank Millman wrote:

[...]
> The class has a getval() method to return the current value.
> 
> Usually the value is stored in the instance, and can be returned
> immediately, but sometimes it has to be computed, incurring further
> database lookups.

This is called memoisation, or caching, and is a perfectly standard
programming technique. It's not without its traps though: there's a famous
quote that says there are only two hard problems in computing, naming
things and cache invalidation. But putting that aside:


def getval(self):
sentinel = object()
value = getattr(self, '_cached_value', sentinel)
if value is sentinel:
# compute the value and store it
value = ...
self._cached_value = value
return value

To invalidate the cache and force a recalculation:

del self._cached_value


Now it's easy to override:

class Subclass(ParentClass):
def getval(self):
value = super(Subclass, self).getval()
return value + 1



> This is what I have come up with.
> 
> 1. Rename all instances of 'getval()' to '_getval()'.
> 
> 2. Add a new method '_getval_with_comp()'.
> 
> 3. When instantiating an object, check if it would need computation -
> if computation_required:
> self.getval = self._getval_with_comp
> else:
> self.getval = self._getval

So this check only happens once, on instantiation? And you're sure that once
the instance is created, there will never be any circumstances where you
want to re-calculate the value?



> 4. In _getval_with_comp, perform the computation, then add the following -
> self.getval = self._getval
> return self._getval()

So you have something like this?

def _getval(self):
return self._cached_value

def __getval_with_comp(self):
value = ... # long computation
self._cached_value = value
self.getval = self._getval
# return value
return self._getval()
# why call the method when you already know the answer?


How are subclasses supposed to override getval?




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Is this pythonic?

2016-11-23 Thread Chris Angelico
On Wed, Nov 23, 2016 at 10:11 PM, Frank Millman  wrote:
> Gah! The law of unintended consequences strikes again!
>
> As I mentioned, the class in question represents a database column. A
> separate class represents a database row. I have a __str__() method on the
> 'row' class that prints a nicely formatted representation of the object with
> all of its column objects and their values.
>
> With the above changes, I had to turn getval() into a coroutine. My
> __str__() method uses getval() to obtain the values, so I had to prefix
> getval() with 'await', but then I get a syntax error on __str__(). I can add
> 'async' to remove the syntax error, but then print(obj) does not work -
> TypeError: __str__ returned non-string (type coroutine)
>
> I don't think there is an answer to this, but any suggestions will be
> appreciated.
>
> I can say 'print(await obj.__str__())', and it works, but I lose the ability
> to include it in a larger print statement.
>
> Ah well :-(

This strongly suggests that str(x) is the wrong way to get the
information. You shouldn't be doing database requests inside __str__
or __repr__.

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


Re: Is this pythonic?

2016-11-23 Thread Peter Otten
Frank Millman wrote:

> Hi all
> 
> Sometimes I write something that I think is quite clever, but later on I
> look at it and ask 'What was I thinking?'.
> 
> I have just come up with a 'clever' solution to a problem. Would this
> cause raised eyebrows if you were reviewing this?
> 
> I have a class that represents a single database column - there could be
> hundreds of instances at any time.
> 
> The class has a getval() method to return the current value.
> 
> Usually the value is stored in the instance, and can be returned
> immediately, but sometimes it has to be computed, incurring further
> database lookups.
> 
> In many cases the computed value is never actually requested, so I want to
> delay the computation until the first call to getval().
> 
> I could add an 'if computation_required: ' block to getval(), but I am
> trying to avoid that, partly because this would have to be checked for
> every call to getval() but would only used in a small number of cases, and
> partly because I have a few subclasses where getval() is over-ridden so I
> would have to add the extra code to every one (or call the superclass on
> every one).
> 
> This is what I have come up with.
> 
> 1. Rename all instances of 'getval()' to '_getval()'.
> 
> 2. Add a new method '_getval_with_comp()'.
> 
> 3. When instantiating an object, check if it would need computation -
> if computation_required:
> self.getval = self._getval_with_comp
> else:
> self.getval = self._getval

You can also have the method replace itself:

>>> class Foo:
... def get_val(self):
... print("computing...")
... val = self._val = 42
... self.get_val = self.get_cached_val
... return val
... def get_cached_val(self):
... return self._val
... 
>>> foo = Foo()
>>> foo.get_val()
computing...
42
>>> foo.get_val()
42

 
> 4. In _getval_with_comp, perform the computation, then add the following -
> self.getval = self._getval
> return self._getval()
> 
> What is the verdict? -1, 0, or +1?
> 
> Frank Millman


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


Re: Is this pythonic?

2016-11-23 Thread Frank Millman

"Frank Millman"  wrote in message news:o13meh$p2g$1...@blaine.gmane.org...


3. When instantiating an object, check if it would need computation -
if computation_required:
self.getval = self._getval_with_comp
else:
self.getval = self._getval

4. In _getval_with_comp, perform the computation, then add the following -
   self.getval = self._getval
return self._getval()

What is the verdict? -1, 0, or +1?



Thanks for the responses. I will reply to them all here -

@Peter

You can also have the method replace itself ...


I like it. Thanks for the suggestion.

@Steve
So this check only happens once, on instantiation? And you're sure that 
once

the instance is created, there will never be any circumstances where you
want to re-calculate the value?


Well, the process that I call 'computation' includes setting up some 
variables that will trigger a recalculation when certain values change.


Part of my motivation was to avoid all of this if the value is never 
accessed.



def __getval_with_comp(self):
value = ... # long computation
self._cached_value = value
self.getval = self._getval
# return value
return self._getval()
# why call the method when you already know the answer?

How are subclasses supposed to override getval?



Two questions there, but the answer is the same.

I don't want subclasses to override the computation part of the process. I 
just want then to 'massage' the result before returning it. Therefore the 
answer to the first question is, to force the subclass to return the result, 
if it has its own _getval(). The answer to the second question is that they 
override _getval(), and therefore they will be invoked when getval() is 
called, provided getval has been set to be equal to _getval.


Hope that makes sense.

@Chris

This strongly suggests that str(x) is the wrong way to get the
information. You shouldn't be doing database requests inside __str__
or __repr__.


I guess you are right, but still it is a pity. __str__ has been working for 
me beautifully for a long time now. The only change is that, previously, all 
the values had been read in or computed before calling __str__(), now I am 
delaying the computation until requested.


It is a bit like quantum theory. I have no way of telling whether the 
computation has been carried out without looking at it, but the act of 
looking at it triggers the computation. I can tell, of course, by looking at 
the underlying attribute, but not by using the public methods.


Frank


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


Re: Is this pythonic?

2016-11-23 Thread Chris Angelico
On Wed, Nov 23, 2016 at 11:27 PM, Frank Millman  wrote:
>
> @Chris
>>
>> This strongly suggests that str(x) is the wrong way to get the
>> information. You shouldn't be doing database requests inside __str__
>> or __repr__.
>
>
> I guess you are right, but still it is a pity. __str__ has been working for
> me beautifully for a long time now. The only change is that, previously, all
> the values had been read in or computed before calling __str__(), now I am
> delaying the computation until requested.
>
> It is a bit like quantum theory. I have no way of telling whether the
> computation has been carried out without looking at it, but the act of
> looking at it triggers the computation. I can tell, of course, by looking at
> the underlying attribute, but not by using the public methods.

That makes sense. What you could do is have __repr__ do something like this:

def __repr__(self):
if self.has_data:
return "<%s: %r>" % (self.col_name, self.data)
return "<%s:  >" % self.col_name

I'm not sure that that would be appropriate for __str__, though; maybe
it could return the string of data if it exists, otherwise it could
fall back on __repr__?

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


Re: Is this pythonic?

2016-11-23 Thread Frank Millman
"Chris Angelico"  wrote in message 
news:CAPTjJmqGEwHPVyrR+Ti9bV=S5MsLt3nquF4TvE=xpees188...@mail.gmail.com...


On Wed, Nov 23, 2016 at 11:27 PM, Frank Millman  
wrote:

>
> @Chris
>>
>> This strongly suggests that str(x) is the wrong way to get the
>> information. You shouldn't be doing database requests inside __str__
>> or __repr__.
>
>
> I guess you are right, but still it is a pity. __str__ has been working 
> for
> me beautifully for a long time now. The only change is that, previously, 
> all
> the values had been read in or computed before calling __str__(), now I 
> am

> delaying the computation until requested.
>
> It is a bit like quantum theory. I have no way of telling whether the
> computation has been carried out without looking at it, but the act of
> looking at it triggers the computation. I can tell, of course, by 
> looking at

> the underlying attribute, but not by using the public methods.

That makes sense. What you could do is have __repr__ do something like 
this:


def __repr__(self):
if self.has_data:
return "<%s: %r>" % (self.col_name, self.data)
return "<%s:  >" % self.col_name

I'm not sure that that would be appropriate for __str__, though; maybe
it could return the string of data if it exists, otherwise it could
fall back on __repr__?



Thanks for the ideas. I will have to experiment a bit.

There is a certain irony in all this. When I started using asyncio, I just 
converted the networking functions into coroutines and waited for it to 
stabilise. Then I wanted to extend it, and found that coroutines can only be 
called by other coroutines, and I had some long chains of function calls, so 
I backed off. Then I eventually bit the bullet, converted everything in the 
chain to a coroutine, and let it settle down again. I have done this a few 
times, and each time I sensed an improvement in the way that my entire 
application was beginning to 'flow' in an async manner, which was good. 
However, I have managed to avoid turning getval() into a coroutine, until 
now. Now I am ready to embrace the change, but this time it is Python that 
is tripping me up.


For the time being I will use 'print(await obj.__str__())', as this is a 
good compromise. Of course I don't have to use __str__, I can call it 
anything, so I will probably create a helper function to make it easy to 
call on any object.


One of the things that was deterring me from turning getval() into a 
coroutine was the inability to use a coroutine inside a comprehension. I see 
that Python 3.6 now allows this, so I must download a beta version and try 
it out.


Frank


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


Quick help for a python newby, please

2016-11-23 Thread jones . dayton
I'm just learning, so please excuse my ignorance for what I know is a simple 
issue...

I'm writing a "Hello, World" type of script to see how things work in python3.  
I'm asking for input to get a person's birthday, then I want to compare that to 
"today" and see how many days have past.

--code--
from datetime import datetime, date

person = input("Enter your name: ")
bmonth = int(input("Enter the numerical month you were born: "))
bday = int(input("Enter the numerical day of the month you were born: "))
byear = int(input("Enter the year you were born: "))

today = date.today()
-- end --

I know to get what I want, I need to do something like:
d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d0 - d1
print(delta.days)


but how do I replace the "2008, 8, 18" and "2008, 9, 26" with *my* values?  
I've tried several things (which I can't remember all of) but usually end up 
with an error like this:

   ...
delta = (b - a)
TypeError: unsupported operand type(s) for -: 'str' and 'str'
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Quick help for a python newby, please

2016-11-23 Thread Thomas Nyberg

On 11/23/2016 09:18 AM, jones.day...@gmail.com wrote:


but how do I replace the "2008, 8, 18" and "2008, 9, 26" with *my* values?  
I've tried several things (which I can't remember all of) but usually end up with an error like 
this:


Does this not work for you?

d = date(byear, bmonth, bday)

Then you could write something like:

diff = date.today() - d

Of course you'll need to a do a bit more work to deal with years (e.g. 
has your birthday happened this year yet or not?), but does this not fix 
your problem?


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


Re: Quick help for a python newby, please

2016-11-23 Thread Dayton Jones
ah...yes, but then how could I strip the rest (h:m:s) from it?

Enter the numerical month you were born: 3
Enter the numerical day of the month you were born: 30
Enter the year you were born: 1989
10100 days, 0:00:00
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Quick help for a python newby, please

2016-11-23 Thread Anssi Saari
jones.day...@gmail.com writes:

> but how do I replace the "2008, 8, 18" and "2008, 9, 26" with *my* values?  
> I've tried several things (which I can't remember all of) but usually end up 
> with an error like this:

Something like this?

today = date.today()
birthday = date(byear, bmonth, bday)
delta = today - birthday
print(delta.days)


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


Re: Is this pythonic?

2016-11-23 Thread Tim Chase
On 2016-11-23 22:15, Steve D'Aprano wrote:
> On Wed, 23 Nov 2016 08:10 pm, Frank Millman wrote:
> > The class has a getval() method to return the current value.
> > 
> > Usually the value is stored in the instance, and can be returned
> > immediately, but sometimes it has to be computed, incurring
> > further database lookups.  
> 
> This is called memoisation, or caching, and is a perfectly standard
> programming technique. It's not without its traps though: there's a
> famous quote that says there are only two hard problems in
> computing, naming things and cache invalidation.

Fortunately, you can offload some odd edge-cases to the standard
library, no?

  from functools import lru_cache
  # ...
  @lru_cache(maxsize=1)
  def getval(...):
return long_computation()

It doesn't cache across multiple instances of the same class, but
does cache multiple calls to the same instance's function:

  >>> from functools import lru_cache
  >>> class Foo:
  ...   def __init__(self, name):
  ... self.name = name
  ...   @lru_cache(maxsize=1)
  ...   def getval(self):
  ... print("Long process")
  ... return self.name
  ... 
  >>> f1 = Foo("f1")
  >>> f2 = Foo("f2")
  >>> f1.getval()
  Long process
  'f1'
  >>> f1.getval()
  'f1'
  >>> f2.getval()
  Long process
  'f2'
  >>> f2.getval()
  'f2'

-tkc





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


Re: Quick help for a python newby, please

2016-11-23 Thread Dayton Jones
Ah, perfect - thanks.  I was overly complicating things.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Quick help for a python newby, please

2016-11-23 Thread justin walters
On Wed, Nov 23, 2016 at 7:13 AM, Dayton Jones 
wrote:

> ah...yes, but then how could I strip the rest (h:m:s) from it?
>
> Enter the numerical month you were born: 3
> Enter the numerical day of the month you were born: 30
> Enter the year you were born: 1989
> 10100 days, 0:00:00
> --
> https://mail.python.org/mailman/listinfo/python-list
>


You'll probably want to use `timedelta`:
https://docs.python.org/3.4/library/datetime.html#timedelta-objects
-- 
https://mail.python.org/mailman/listinfo/python-list


How to concatenate strings in different lists

2016-11-23 Thread Daiyue Weng
Hi, I am wondering how to concatenate corresponding strings in two lists,
assuming that the lists are of same length, e.g.

val_1 = ['a', 'b', 'c']
val_2 = ['A', 'B', 'C']

# concatenate corresponding strings in 'val_1' and 'val_2'
# and put results in another list 'val' so that
# val = ['aA', 'bB', 'cC']

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


Re: How to concatenate strings in different lists

2016-11-23 Thread Joonas Liik
On 23 November 2016 at 19:40, Daiyue Weng  wrote:
> Hi, I am wondering how to concatenate corresponding strings in two lists,
> assuming that the lists are of same length, e.g.
>
> val_1 = ['a', 'b', 'c']
> val_2 = ['A', 'B', 'C']
>
> # concatenate corresponding strings in 'val_1' and 'val_2'
> # and put results in another list 'val' so that
> # val = ['aA', 'bB', 'cC']
>
> cheers
> --
> https://mail.python.org/mailman/listinfo/python-list

one way to do it:

val = [''.join(pair) for pair in zip(val_1, val2)]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to concatenate strings in different lists

2016-11-23 Thread Thomas Nyberg

On 11/23/2016 12:40 PM, Daiyue Weng wrote:

Hi, I am wondering how to concatenate corresponding strings in two lists,
assuming that the lists are of same length, e.g.

val_1 = ['a', 'b', 'c']
val_2 = ['A', 'B', 'C']

# concatenate corresponding strings in 'val_1' and 'val_2'
# and put results in another list 'val' so that
# val = ['aA', 'bB', 'cC']

cheers


Hello,

The easiest is probably first to zip them (i.e. pair the corresponding 
pieces together) and then to join them as you normally would with lists 
of strings:


>>> print([''.join(pair) for pair in zip(val_1, val_2)])
['aA', 'bB', 'cC']

That uses list comprehensions which might be a bit confusing. In two 
steps, you could do the following


>>> pairs = zip(val_1, val_2)
>>> catted_strings = []
>>> for pair in pairs:
catted_string = ''.join(pair)
catted_strings.append(catted_string)
>>> print(catted_strings)
['aA', 'bB', 'cC']

Hope this this helps.

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


Can I print 2 calendars side by side?

2016-11-23 Thread Dayton Jones
I'd like to be able to display 2 calendars side by side, instead of stacked... 
is this possible?

for instance:

print(calendar.month(year_a,month))
print()
print(calendar.month(year_b,month))

prints:
 June 1971
Mo Tu We Th Fr Sa Su
1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30


 June 2017
Mo Tu We Th Fr Sa Su
  1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30



but what I would like is:
 June 1971   June 2017
Mo Tu We Th Fr Sa SuMo Tu We Th Fr Sa Su
1  2  3  4  5  6  1  2  3  4
 7  8  9 10 11 12 13 5  6  7  8  9 10 11
14 15 16 17 18 19 2012 13 14 15 16 17 18
21 22 23 24 25 26 2719 20 21 22 23 24 25
28 29 3026 27 28 29 30
-- 
https://mail.python.org/mailman/listinfo/python-list


K-means Python code analyse

2016-11-23 Thread Alex
Can please anyone explaine me what do each of these code lines and how k-means 
algorithm works?


from scipy.cluster.vq import *
from scipy.misc import imresize
from pylab import *
from PIL import Image
steps = 500 
im = array(Image.open("empire.jpg"))
dx = im.shape[0] / steps
dy = im.shape[1] / steps
# compute color features for each region
features = []
for x in range(steps): 
for y in range(steps):
R = mean(im[x*dx:(x+1)*dx,y*dy:(y+1)*dy,0])
G = mean(im[x*dx:(x+1)*dx,y*dy:(y+1)*dy,1])
B = mean(im[x*dx:(x+1)*dx,y*dy:(y+1)*dy,2])
features.append([R,G,B]) 
features = array(features,"f") # make into array
# cluster
centroids,variance = kmeans(features,3)
code,distance = vq(features,centroids)
# create image with cluster labels
codeim = code.reshape(steps,steps)
codeim = imresize(codeim,im.shape[:2],interp="nearest")
figure()
imshow(codeim)
show()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can I print 2 calendars side by side?

2016-11-23 Thread Tim Chase
On 2016-11-23 10:02, Dayton Jones wrote:
> I'd like to be able to display 2 calendars side by side, instead of
> stacked... is this possible?
> 
> for instance:
> 
> print(calendar.month(year_a,month))
> print()
> print(calendar.month(year_b,month))
> 
> prints:
>  June 1971
> Mo Tu We Th Fr Sa Su
> 1  2  3  4  5  6
>  7  8  9 10 11 12 13
> 14 15 16 17 18 19 20
> 21 22 23 24 25 26 27
> 28 29 30
> 
> 
>  June 2017
> Mo Tu We Th Fr Sa Su
>   1  2  3  4
>  5  6  7  8  9 10 11
> 12 13 14 15 16 17 18
> 19 20 21 22 23 24 25
> 26 27 28 29 30
> 
> 
> but what I would like is:
>  June 1971   June 2017
> Mo Tu We Th Fr Sa SuMo Tu We Th Fr Sa Su
> 1  2  3  4  5  6  1  2  3  4
>  7  8  9 10 11 12 13 5  6  7  8  9 10 11
> 14 15 16 17 18 19 2012 13 14 15 16 17 18
> 21 22 23 24 25 26 2719 20 21 22 23 24 25
> 28 29 3026 27 28 29 30

This seems to do the trick for me

  from itertools import izip_longest
  print ('\n'.join(
"%-24s %s" % (week1, week2)
for week1, week2
in izip_longest(
  month(1971, 6).splitlines(),
  month(2017, 6).splitlines(),
  fillvalue='',
  )
))

Adjust the "-24" to put your desired amount of padding between the
calendars (needs to be at least 21=3 character-columns per day * 7
days per week).  If you want more than two weeks, you can generalize
it:

  dates = [
month(1971, 6),
month(2001, 6),
month(2017, 6),
]

  print ('\n'.join(
'  '.join(w.ljust(21) for w in weeks)
for weeks
in izip_longest(
  *[cal.splitlines() for cal in dates],
  fillvalue=''
  )
))

Hope this helps,

-tkc



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


Re: Can I print 2 calendars side by side?

2016-11-23 Thread Peter Otten
Dayton Jones wrote:

> I'd like to be able to display 2 calendars side by side, instead of
> stacked... is this possible?

I'm too lazy to look around for a ready-to-use solution, so here's my own:

$ cat side_by_side.py
from itertools import zip_longest

def zip_lines(*columns, sep="  "):
columns = [c.splitlines() for c in columns]
widths = [max(len(s) for s in c) for c in columns]
return "\n".join(
sep.join(c.ljust(w) for c, w in zip(row, widths))
for row in zip_longest(*columns, fillvalue="")
)

if __name__ == "__main__":
import calendar

print(zip_lines(calendar.month(2016, 1), calendar.month(2015, 1)))
print()

columns = [calendar.month(2016, month) for month in range(6, 9)]
print(zip_lines(*columns, sep="  |  "))
$ python3 side_by_side.py 
January 2016  January 2015
Mo Tu We Th Fr Sa Su  Mo Tu We Th Fr Sa Su
 1  2  31  2  3  4
 4  5  6  7  8  9 10   5  6  7  8  9 10 11
11 12 13 14 15 16 17  12 13 14 15 16 17 18
18 19 20 21 22 23 24  19 20 21 22 23 24 25
25 26 27 28 29 30 31  26 27 28 29 30 31   

 June 2016|   July 2016|  August 2016 
Mo Tu We Th Fr Sa Su  |  Mo Tu We Th Fr Sa Su  |  Mo Tu We Th Fr Sa Su
   1  2  3  4  5  |   1  2  3  |   1  2  3  4  5  6  7
 6  7  8  9 10 11 12  |   4  5  6  7  8  9 10  |   8  9 10 11 12 13 14
13 14 15 16 17 18 19  |  11 12 13 14 15 16 17  |  15 16 17 18 19 20 21
20 21 22 23 24 25 26  |  18 19 20 21 22 23 24  |  22 23 24 25 26 27 28
27 28 29 30   |  25 26 27 28 29 30 31  |  29 30 31


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


Re: Can I print 2 calendars side by side?

2016-11-23 Thread MRAB

On 2016-11-23 18:02, Dayton Jones wrote:

I'd like to be able to display 2 calendars side by side, instead of stacked... 
is this possible?

for instance:

print(calendar.month(year_a,month))
print()
print(calendar.month(year_b,month))

prints:
 June 1971
Mo Tu We Th Fr Sa Su
1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30


 June 2017
Mo Tu We Th Fr Sa Su
  1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30



but what I would like is:
 June 1971   June 2017
Mo Tu We Th Fr Sa SuMo Tu We Th Fr Sa Su
1  2  3  4  5  6  1  2  3  4
 7  8  9 10 11 12 13 5  6  7  8  9 10 11
14 15 16 17 18 19 2012 13 14 15 16 17 18
21 22 23 24 25 26 2719 20 21 22 23 24 25
28 29 3026 27 28 29 30


The functions return strings, so you can split them into lines:

rows_a = calendar.month(year_a, month).splitlines()
rows_b = calendar.month(year_b, month).splitlines()

You can then zip them together:

rows = ['{}{}'.format(row_a, row_b) for row_a, row_b in zip(rows_a, 
rows_b)]


However:

1. The 2 months might have a different number of rows. 'zip' will 
truncate to the shorter one, so use itertools.zip_longest instead (give 
it a fillvalue of '').


2. The lines aren't all the same length, so you'll need to pad the 
left-hand one to the correct length (20 characters) to make everything 
line-up.


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


Re: Can I print 2 calendars side by side?

2016-11-23 Thread Dayton Jones
Perfect!  Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Random number help

2016-11-23 Thread Thomas Grops via Python-list
I need a way of generating a random number but there is a catch:

I don't want to include certain numbers, is this possible?

random.randint(1,100) works as it will randomly pick numbers between 1 and 100 
but say i don't want 48 to come out is there a way of doing this. It needs to 
be an integer too so not a list unless there is a way to convert list to int

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


Re: Random number help

2016-11-23 Thread Marko Rauhamaa
Thomas Grops :

> random.randint(1,100) works as it will randomly pick numbers between 1
> and 100 but say i don't want 48 to come out is there a way of doing
> this. It needs to be an integer too so not a list unless there is a way
> to convert list to int

   r = 48
   while r == 48:
   r = random.randint(1, 100)


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


Re: Random number help

2016-11-23 Thread Thomas Nyberg

On 11/23/2016 02:17 PM, Thomas Grops via Python-list wrote:

I need a way of generating a random number but there is a catch:

I don't want to include certain numbers, is this possible?

random.randint(1,100) works as it will randomly pick numbers between 1 and 100 
but say i don't want 48 to come out is there a way of doing this. It needs to 
be an integer too so not a list unless there is a way to convert list to int

Many Thanks Tom

If you specifically want to exclude 48, you could create the list of 
acceptable numbers and make a random choice from it. For example:


>>> import random
>>> l = list(range(1, 48)) + list(range(49, 101))
>>> random.choice(l)
64

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


Re: Random number help

2016-11-23 Thread Chris Kaynor
On Wed, Nov 23, 2016 at 11:17 AM, Thomas Grops via Python-list
 wrote:
> I need a way of generating a random number but there is a catch:
>
> I don't want to include certain numbers, is this possible?
>
> random.randint(1,100) works as it will randomly pick numbers between 1 and 
> 100 but say i don't want 48 to come out is there a way of doing this. It 
> needs to be an integer too so not a list unless there is a way to convert 
> list to int

There are a few ways to accomplish this, depending on the exact
requirements. Here are some basic ideas:
- Generate a list of all valid values, and take the one at a random
index. random.sample may be useful. This is guaranteed to complete
(and in only one try), but generally takes extra memory. It is also a
reasonably easy way to sample without replacement (remove the picked
item each time).
- Generate a random number from the larger range, and retry if you get
one in the invalid set. Basically akin to rolling a die, and rerolling
until you don't get a 6. This could theoretically take forever,
however it is often good enough in practice. This will become more and
more inefficient as set of invalid values grows (especially if the
invalid set is a superset of the whole range)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Random number help

2016-11-23 Thread Achilleas Michailidis


You can use a while statement until you get a number out of your 
excluded numbers


excludedNumbers = [1,2,3,4]
randomNumber = random.randomint(1,100)

while randomNumber in excludedNumbers:
randomNumber = random.randomint(1,100)

After the while you have a number outside the excluded numbers




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


Re: Random number help

2016-11-23 Thread Thomas Grops via Python-list
On Wednesday, 23 November 2016 19:30:04 UTC, Thomas Nyberg  wrote:
> On 11/23/2016 02:17 PM, Thomas Grops via Python-list wrote:
> > I need a way of generating a random number but there is a catch:
> >
> > I don't want to include certain numbers, is this possible?
> >
> > random.randint(1,100) works as it will randomly pick numbers between 1 and 
> > 100 but say i don't want 48 to come out is there a way of doing this. It 
> > needs to be an integer too so not a list unless there is a way to convert 
> > list to int
> >
> > Many Thanks Tom
> >
> If you specifically want to exclude 48, you could create the list of 
> acceptable numbers and make a random choice from it. For example:
> 
>  >>> import random
>  >>> l = list(range(1, 48)) + list(range(49, 101))
>  >>> random.choice(l)
> 64
> 
> Cheers,
> Thomas

Thankyou, I just tried this but it seems to be printing every value excluding 
48, I am just after a single value
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Random number help

2016-11-23 Thread Thomas Grops via Python-list
On Wednesday, 23 November 2016 19:30:21 UTC, Chris Kaynor  wrote:
> On Wed, Nov 23, 2016 at 11:17 AM, Thomas Grops via Python-list
>  wrote:
> > I need a way of generating a random number but there is a catch:
> >
> > I don't want to include certain numbers, is this possible?
> >
> > random.randint(1,100) works as it will randomly pick numbers between 1 and 
> > 100 but say i don't want 48 to come out is there a way of doing this. It 
> > needs to be an integer too so not a list unless there is a way to convert 
> > list to int
> 
> There are a few ways to accomplish this, depending on the exact
> requirements. Here are some basic ideas:
> - Generate a list of all valid values, and take the one at a random
> index. random.sample may be useful. This is guaranteed to complete
> (and in only one try), but generally takes extra memory. It is also a
> reasonably easy way to sample without replacement (remove the picked
> item each time).
> - Generate a random number from the larger range, and retry if you get
> one in the invalid set. Basically akin to rolling a die, and rerolling
> until you don't get a 6. This could theoretically take forever,
> however it is often good enough in practice. This will become more and
> more inefficient as set of invalid values grows (especially if the
> invalid set is a superset of the whole range)

many thanks but am I missing something when I use a list it returns a value 
with the type list not integer? I need an integer
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Random number help

2016-11-23 Thread MRAB

On 2016-11-23 19:29, Chris Kaynor wrote:

On Wed, Nov 23, 2016 at 11:17 AM, Thomas Grops via Python-list
 wrote:

I need a way of generating a random number but there is a catch:

I don't want to include certain numbers, is this possible?

random.randint(1,100) works as it will randomly pick numbers between 1 and 100 
but say i don't want 48 to come out is there a way of doing this. It needs to 
be an integer too so not a list unless there is a way to convert list to int


There are a few ways to accomplish this, depending on the exact
requirements. Here are some basic ideas:
- Generate a list of all valid values, and take the one at a random
index. random.sample may be useful. This is guaranteed to complete
(and in only one try), but generally takes extra memory. It is also a
reasonably easy way to sample without replacement (remove the picked
item each time).
- Generate a random number from the larger range, and retry if you get
one in the invalid set. Basically akin to rolling a die, and rerolling
until you don't get a 6. This could theoretically take forever,
however it is often good enough in practice. This will become more and
more inefficient as set of invalid values grows (especially if the
invalid set is a superset of the whole range)

Another way is to map a shorter range to the desired numbers using an 
offset:


r = random.randint(1, 99)
if r >= 48:
r += 1

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


Re: Random number help

2016-11-23 Thread Thomas Grops via Python-list
Thankyou for all your help I have managed to pick a way that works from your 
suggestions :D
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is this pythonic?

2016-11-23 Thread Gregory Ewing

Frank Millman wrote:
For the time being I will use 'print(await obj.__str__())', as this is a 
good compromise.


It seems more like a very *bad* compromise to me.

I can't see how this gains you anything over just doing
print(await obj.getvalue()), and you lose the ability to
do anything that calls __str__ implicitly.

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


Re: Is this pythonic?

2016-11-23 Thread Steve D'Aprano
On Wed, 23 Nov 2016 11:27 pm, Frank Millman wrote:

> It is a bit like quantum theory. I have no way of telling whether the
> computation has been carried out without looking at it, but the act of
> looking at it triggers the computation. I can tell, of course, by looking
> at the underlying attribute, but not by using the public methods.

Then give it a public method (or better, a property) to tell.


@property
def needs_computation(self):
return not hasattr(self, '_cached_value')




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Quick help for a python newby, please

2016-11-23 Thread Wildman via Python-list
On Wed, 23 Nov 2016 06:18:38 -0800, jones.dayton wrote:

> I'm just learning, so please excuse my ignorance for
> what I know is a simple issue...
> 
> I'm writing a "Hello, World" type of script to see how
> things work in python3.  I'm asking for input to get a
> person's birthday, then I want to compare that to
> "today" and see how many days have past.
> 
> --code--
> from datetime import datetime, date
> 
> person = input("Enter your name: ")
> bmonth = int(input("Enter the numerical month you were born: "))
> bday = int(input("Enter the numerical day of the month you were born: "))
> byear = int(input("Enter the year you were born: "))
> 
> today = date.today()
> -- end --
> 
> I know to get what I want, I need to do something like:
> d0 = date(2008, 8, 18)
> d1 = date(2008, 9, 26)
> delta = d0 - d1
> print(delta.days)
> 
> 
> but how do I replace the "2008, 8, 18" and "2008, 9, 26" with *my* values?  
> I've tried several things (which I can't remember all of) but usually end up 
> with an error like this:
> 
>...
> delta = (b - a)
> TypeError: unsupported operand type(s) for -: 'str' and 'str'

Try the code that is below:

import datetime
from datetime import date

today = date.today()
person = input("Enter your name: ")
byear = raw_input("Enter the four-digit year you were born: ")
bmonth = raw_input("Enter the month (1-12)you were born: ")
bday = raw_input("Enter the day (1-31) you were born: ")
try:
birthdate = date(int(byear), int(bmonth), int(bday))
dif = (today - birthdate).days
print person + "'s birthday was " + str(dif) + " days ago."
except ValueError:
print "The date you entered is not valid!"

-- 
 GNU/Linux user #557453
The cow died so I don't need your bull!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Reposting On Python-List PROHIBITED

2016-11-23 Thread mm0fmf

On 23/11/2016 23:28, Lawrence D’Oliveiro wrote:

To the controllers of Python-List:

I never asked to be on your list. I never consented to having my postings 
appear on your list. And I certainly didn’t agree to any conditions you might 
impose on members on your list.

Therefore, to see you take offence at something I said, and use that as an 
excuse to “ban” me from your list, is an act of breathtaking hypocrisy. As far 
as I am concerned, it is you lot who should be banned from comp.lang.python. 
You are reusing its content inappropriately and without authorization. What you 
are doing must be stopped.



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


Re: Quick help for a python newby, please

2016-11-23 Thread Chris Angelico
On Thu, Nov 24, 2016 at 10:02 AM, Wildman via Python-list
 wrote:
> Try the code that is below:
>
> import datetime
> from datetime import date
>
> today = date.today()
> person = input("Enter your name: ")
> byear = raw_input("Enter the four-digit year you were born: ")

Please take care of Python versions. The OP said Python 3, and you've
kept one input() call, but then you've used raw_input for the rest.
These should all be input() calls in Py3.

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


Re: Reposting On Python-List PROHIBITED

2016-11-23 Thread Michael Torrie
On 11/23/2016 04:31 PM, mm0fmf wrote:
> On 23/11/2016 23:28, Lawrence D’Oliveiro wrote:
>> Therefore, to see you take offence at something I said, and use
>> that as an excuse to “ban” me from your list, is an act of
>> breathtaking hypocrisy. As far as I am concerned, it is you lot who
>> should be banned from comp.lang.python. You are reusing its content
>> inappropriately and without authorization. What you are doing must
>> be stopped.

Oh wow.

Well the poor fellow can rest easy knowing that stuff he posts to the
newsgroup is indeed not going to the mailing list.

Personally it wouldn't hurt my feelings if comp.lang.python was cut
loose from the mailing list entirely, though I know many posters would
disagree and others would desire to drop the mailing list part.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Reposting On Python-List PROHIBITED

2016-11-23 Thread Steve D'Aprano
On Thu, 24 Nov 2016 10:28 am, Lawrence D’Oliveiro wrote:

> To the controllers of Python-List:
> 
> I never asked to be on your list. I never consented to having my postings
> appear on your list. And I certainly didn’t agree to any conditions you
> might impose on members on your list.

comp.lang.python is set up as a mirror of the mailing list. By posting to
comp.lang.python, you are mailing the python-list@python.org mailing list.


> Therefore, to see you take offence at something I said, and use that as an
> excuse to “ban” me from your list, is an act of breathtaking hypocrisy.

It really isn't. It is perhaps an act of ignorance on your part to fail to
realise that you are posting to the mailing list, although I believe you
have been told this before. Repeatedly.


> As 
> far as I am concerned, it is you lot who should be banned from
> comp.lang.python. You are reusing its content inappropriately and without
> authorization. What you are doing must be stopped.

This newsgroup is a mirror of the mailing list, not the other way around.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Is this pythonic?

2016-11-23 Thread Steve D'Aprano
On Wed, 23 Nov 2016 10:11 pm, Frank Millman wrote:

> Gah! The law of unintended consequences strikes again!
> 
> As I mentioned, the class in question represents a database column. 

Yes, you mentioned that.

> A 
> separate class represents a database row. I have a __str__() method on the
> 'row' class that prints a nicely formatted representation of the object
> with all of its column objects and their values.

You didn't mention that, but it shouldn't matter.

 
> With the above changes, I had to turn getval() into a coroutine.

You what?

I'm gobsmacked by this assertion. Nobody else seems to have commented on
this, so perhaps I'm missing something, but this strikes me as astonishing.
Nothing in your earlier post even hinted that you were using coroutines or
async, and as sure as the day is long memoisation doesn't force you to
start.

Even if the computation of the memoised value is done asynchronously, you
can easily split the computation off to a separate method (as you already
talked about doing!) and make getval() block until it returns.


[...]
> I can say 'print(await obj.__str__())', and it works, but I lose the
> ability to include it in a larger print statement.

Any time you find yourself directly calling dunder methods, you're probably
doing it wrong. This is one of those times.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


NameError

2016-11-23 Thread Cai Gengyang
>>> pygame.draw.rect(screen, BROWN, [60, 400, 30, 45])
Traceback (most recent call last):
File "", line 1, in 
pygame.draw.rect(screen, BROWN, [60, 400, 30, 45])
NameError: name 'pygame' is not defined

How to solve this error ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: NameError

2016-11-23 Thread Joel Goldstick
On Wed, Nov 23, 2016 at 9:44 PM, Cai Gengyang  wrote:
 pygame.draw.rect(screen, BROWN, [60, 400, 30, 45])
> Traceback (most recent call last):
> File "", line 1, in 
> pygame.draw.rect(screen, BROWN, [60, 400, 30, 45])
> NameError: name 'pygame' is not defined
>
> How to solve this error ?
> --
> https://mail.python.org/mailman/listinfo/python-list

have you imported pygame?

-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: NameError

2016-11-23 Thread Cai Gengyang
I tried to import pygame by using these commands 
https://www.google.com.sg/#q=how+to+import+pygame

but this is the error I got :

CaiGengYangs-MacBook-Pro:~ CaiGengYang$ sudo apt-get install python-pygame
sudo: apt-get: command not found



On Thursday, November 24, 2016 at 10:54:20 AM UTC+8, Joel Goldstick wrote:
> On Wed, Nov 23, 2016 at 9:44 PM, Cai Gengyang  wrote:
>  pygame.draw.rect(screen, BROWN, [60, 400, 30, 45])
> > Traceback (most recent call last):
> > File "", line 1, in 
> > pygame.draw.rect(screen, BROWN, [60, 400, 30, 45])
> > NameError: name 'pygame' is not defined
> >
> > How to solve this error ?
> > --
> > https://mail.python.org/mailman/listinfo/python-list
> 
> have you imported pygame?
> 
> -- 
> Joel Goldstick
> http://joelgoldstick.com/blog
> http://cc-baseballstats.info/stats/birthdays
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Quick help for a python newby, please

2016-11-23 Thread Wildman via Python-list
On Thu, 24 Nov 2016 11:59:17 +1100, Chris Angelico wrote:

> On Thu, Nov 24, 2016 at 10:02 AM, Wildman via Python-list
>  wrote:
>> Try the code that is below:
>>
>> import datetime
>> from datetime import date
>>
>> today = date.today()
>> person = input("Enter your name: ")
>> byear = raw_input("Enter the four-digit year you were born: ")
> 
> Please take care of Python versions. The OP said Python 3, and you've
> kept one input() call, but then you've used raw_input for the rest.
> These should all be input() calls in Py3.
> 
> ChrisA

Point taken.  I did miss the python3 part.

I switched to raw_input because it handles an empty
input.  An empty input would trigger the ValueError.
No doubt with the correct code the same or similar
could be done with input().  My lack of experience
caused me to look for simpler solution and perhaps
the wrong one.

-- 
 GNU/Linux user #557453
The cow died so I don't need your bull!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Quick help for a python newby, please

2016-11-23 Thread Chris Angelico
On Thu, Nov 24, 2016 at 2:41 PM, Wildman via Python-list
 wrote:
> Point taken.  I did miss the python3 part.
>
> I switched to raw_input because it handles an empty
> input.  An empty input would trigger the ValueError.
> No doubt with the correct code the same or similar
> could be done with input().  My lack of experience
> caused me to look for simpler solution and perhaps
> the wrong one.

The exact same thing is true of input() in Python 3. In Python 2,
input() is the same as eval(raw_input()), so don't use it ever [1].
You can happily use input() in Py3, even if you get empty input.

I like to put this at the top of cross-version scripts:

try: input = raw_input
except NameError: pass

Then you can proceed to use input() without worries.

ChrisA

[1] Yes, I'm aware there are times when evalling the user's input is
what you want. In those cases, be explicit and use eval.
-- 
https://mail.python.org/mailman/listinfo/python-list


generating list of files matching condition

2016-11-23 Thread Seb
Hello,

Given a list of files:

In [81]: ec_files[0:10]
Out[81]: 

[u'EC_20160604002000.csv',
 u'EC_2016060401.csv',
 u'EC_20160604012000.csv',
 u'EC_20160604014000.csv',
 u'EC_2016060402.csv']

where the numbers are are a timestamp with format %Y%m%d%H%M%S, I'd like
to generate a list of matching files for each 2-hr period in a 2-h
frequency time series.  Ultimately I'm using Pandas to read and handle
the data in each group of files.  For the task of generating the files
for each 2-hr period, I've done the following:

beg_tstamp = pd.to_datetime(ec_files[0][-18:-4],
format="%Y%m%d%H%M%S")
end_tstamp = pd.to_datetime(ec_files[-1][-18:-4],
format="%Y%m%d%H%M%S")
tstamp_win = pd.date_range(beg_tstamp, end_tstamp, freq="2H")

So tstamp_win is the 2-hr frequency time series spanning the timestamps
in the files in ec_files.

I've generated the list of matching files for each tstamp_win using a
comprehension:

win_files = []
for i, w in enumerate(tstamp_win):
nextw = w + pd.Timedelta(2, "h")
ifiles = [x for x in ec_files if
  pd.to_datetime(x[-18:-4], format="%Y%m%d%H%M%S") >= w and
  pd.to_datetime(x[-18:-4], format="%Y%m%d%H%M%S") < nextw]
win_files.append(ifiles)

However, this is proving very slow, and was wondering whether there's a
better/faster way to do this.  Any tips would be appreciated.


-- 
Seb

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


Re: NameError

2016-11-23 Thread Thomas Nyberg

On 11/23/2016 10:02 PM, Cai Gengyang wrote:

I tried to import pygame by using these commands 
https://www.google.com.sg/#q=how+to+import+pygame

but this is the error I got :

CaiGengYangs-MacBook-Pro:~ CaiGengYang$ sudo apt-get install python-pygame
sudo: apt-get: command not found

Judging by your prompt it looks like you're on a Mac. The apt-get 
program is installed on some Linux distributions (probably your 
instructions are for Ubuntu). Here are some istructions for installing 
pygame for a Macbook:


http://pygame.org/wiki/macintosh

http://florian-berger.de/en/articles/installing-pygame-for-python-3-on-os-x/
https://jamesfriend.com.au/installing-pygame-python-3-mac-os-yosemite

Here's some info about getting a package manager like apt for Mac:


http://unix.stackexchange.com/questions/80711/how-to-install-apt-get-or-yum-on-mac-os-x

Hopefully this helps.

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


Re: How to you convert list of tuples to string

2016-11-23 Thread Larry Hudson via Python-list

On 11/23/2016 03:09 AM, Ned Batchelder wrote:
[snip...]

Or using the new string formatting syntax:

msg = '{},{},{}:{}'.format(*item)

The *item in the format() unpacks the tuple.



"new" == "Introduced in 2.6, available since 2008" :)

--Ned.



Of course.  I probably should have said "newer" or "other".:-)

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


Re: NameError

2016-11-23 Thread Cai Gengyang
Yea, using Mac 

Following the instructions here for Mac 
---https://bitbucket.org/pygame/pygame/issues/82/homebrew-on-leopard-fails-to-install#comment-627494

GengYang Cai CaiGengYangs-MacBook-Pro:~ CaiGengYang$ brew install python
==> Installing dependencies for python: xz, pkg-config, readline, sqlite,
==> Installing python dependency: xz
==> Downloading https://homebrew.bintray.com/.../xz-5.2.2.yosemite.bottle.ta
 100.0%
==> Pouring xz-5.2.2.yosemite.bottle.tar.gz
🍺 /usr/local/Cellar/xz/5.2.2: 91 files, 1.4M
==> Installing python dependency: pkg-config
==> Downloading https://homebrew.bintray.com/.../pkg-config-0.29.1_1.yosemit
 100.0%
==> Pouring pkg-config-0.29.1_1.yosemite.bottle.tar.gz
🍺 /usr/local/Cellar/pkg-config/0.29.1_1: 10 files, 627.3K
==> Installing python dependency: readline
==> Downloading https://homebrew.bintray.com/.../readline-6.3.8.yosemite.bot
 100.0%
==> Pouring readline-6.3.8.yosemite.bottle.tar.gz
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local.

OS X provides the BSD libedit library, which shadows libreadline.
In order to prevent conflicts when programs look for libreadline we are
defaulting this GNU Readline installation to keg-only.

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

LDFLAGS: -L/usr/local/opt/readline/lib
CPPFLAGS: -I/usr/local/opt/readline/include

==> Summary
🍺 /usr/local/Cellar/readline/6.3.8: 46 files, 2M
==> Installing python dependency: sqlite
==> Downloading https://homebrew.bintray.com/.../sqlite-3.13.0.yosemite.bott
 100.0%
==> Pouring sqlite-3.13.0.yosemite.bottle.tar.gz
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local.

OS X provides an older sqlite3.

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

LDFLAGS: -L/usr/local/opt/sqlite/lib
CPPFLAGS: -I/usr/local/opt/sqlite/include

==> Summary
🍺 /usr/local/Cellar/sqlite/3.13.0: 10 files, 2.9M
==> Installing python dependency: gdbm
==> Downloading https://homebrew.bintray.com/.../gdbm-1.12.yosemite.bottle.t
 100.0%
==> Pouring gdbm-1.12.yosemite.bottle.tar.gz
🍺 /usr/local/Cellar/gdbm/1.12: 18 files, 490.8K
==> Installing python dependency: openssl
==> Downloading https://homebrew.bintray.com/.../openssl-1.0.2h_1.yosemite.b
 100.0%
==> Pouring openssl-1.0.2h_1.yosemite.bottle.tar.gz
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
/usr/local/etc/openssl/certs

and run
/usr/local/opt/openssl/bin/c_rehash

This formula is keg-only, which means it was not symlinked into /usr/local.

Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

LDFLAGS: -L/usr/local/opt/openssl/lib
CPPFLAGS: -I/usr/local/opt/openssl/include

==> Summary
🍺 /usr/local/Cellar/openssl/1.0.2h_1: 1,691 files, 12.0M
==> Installing python
Warning: Building python from source:
The bottle needs the Apple Command Line Tools to be installed.
You can install them, if desired, with:
xcode-select --install

==> Downloading https://www.python.org/.../2.7.12/Python-2.7.12.tar.xz
 100.0%
==> Downloading https://bugs.python.org/file30805/issue10910-workaround.txt
 100.0%
==> Patching
==> Applying issue10910-workaround.txt
patching file Include/pyport.h
Hunk #1 succeeded at 713 (offset 14 lines).
Hunk #2 succeeded at 736 (offset 14 lines).
==> ./configure --prefix=/usr/local/Cellar/python/2.7.12 --enable-ipv6 --dataroo
==> make
/usr/local/share/python/easy_install mecurial

brew install sdl
brew install sdl_mixer
brew install sdl_ttf
brew install sdl_image

hg clone https://bitbucket.org/pygame/pygame
cd pygame
/usr/local/bin/python setup.py install


Does this work ?







On Thursday, November 24, 2016 at 12:00:18 PM UTC+8, Thomas Nyberg wrote:
> On 11/23/2016 10:02 PM, Cai Gengyang wrote:
> > I tried to import pygame by using these commands 
> > https://www.google.com.sg/#q=how+to+import+pygame
> >
> > but this is the error I got :
> >
> > CaiGengYangs-MacBook-Pro:~ CaiGen

Re: Is this pythonic?

2016-11-23 Thread Frank Millman
"Steve D'Aprano"  wrote in message 
news:583653bb$0$1603$c3e8da3$54964...@news.astraweb.com...



Even if the computation of the memoised value is done asynchronously, you
can easily split the computation off to a separate method (as you already
talked about doing!) and make getval() block until it returns.


Surely that defeats the whole purpose of asyncio. Anything that blocks holds 
up the entire process. I strenuously try to avoid blocking in any shape or 
form.



> I can say 'print(await obj.__str__())', and it works, but I lose the
> ability to include it in a larger print statement.


Any time you find yourself directly calling dunder methods, you're 
probably

doing it wrong. This is one of those times.


Yes. Having slept on it, I realise I over-reacted.

The __str__() method is convenient for me, but I only use it for testing and 
debugging to see what is going on. It is not part of my app per se.


I now realise that the solution is -

1. Keep the __str__ method, but replace calls to getval() with a direct 
reference to the underlying attribute. It means that any 'computable' 
objects that have not already been computed will return None, but that is ok 
for my purposes.


2. Write a separate method, retaining the calls to getval(), to be called 
independently using 'await' if I ever need to see the full result after 
computation.


Frank


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


Re: NameError

2016-11-23 Thread Nathan Ernst
I don't see anything in that output resembling an error, just a few
warnings that some features may no be available.

Have you tried importing pygame after you did that? That's what'll prove
one way or another that it worked.

Regards,
Nate

On Wed, Nov 23, 2016 at 10:48 PM, Cai Gengyang 
wrote:

> Yea, using Mac
>
> Following the instructions here for Mac ---https://bitbucket.org/
> pygame/pygame/issues/82/homebrew-on-leopard-fails-to-
> install#comment-627494
>
> GengYang Cai CaiGengYangs-MacBook-Pro:~ CaiGengYang$ brew install python
> ==> Installing dependencies for python: xz, pkg-config, readline, sqlite,
> ==> Installing python dependency: xz
> ==> Downloading https://homebrew.bintray.com/.
> ../xz-5.2.2.yosemite.bottle.ta
> 
> 100.0%
> ==> Pouring xz-5.2.2.yosemite.bottle.tar.gz
> 🍺 /usr/local/Cellar/xz/5.2.2: 91 files, 1.4M
> ==> Installing python dependency: pkg-config
> ==> Downloading https://homebrew.bintray.com/.
> ../pkg-config-0.29.1_1.yosemit
> 
> 100.0%
> ==> Pouring pkg-config-0.29.1_1.yosemite.bottle.tar.gz
> 🍺 /usr/local/Cellar/pkg-config/0.29.1_1: 10 files, 627.3K
> ==> Installing python dependency: readline
> ==> Downloading https://homebrew.bintray.com/.
> ../readline-6.3.8.yosemite.bot
> 
> 100.0%
> ==> Pouring readline-6.3.8.yosemite.bottle.tar.gz
> ==> Caveats
> This formula is keg-only, which means it was not symlinked into /usr/local.
>
> OS X provides the BSD libedit library, which shadows libreadline.
> In order to prevent conflicts when programs look for libreadline we are
> defaulting this GNU Readline installation to keg-only.
>
> Generally there are no consequences of this for you. If you build your
> own software and it requires this formula, you'll need to add to your
> build variables:
>
> LDFLAGS: -L/usr/local/opt/readline/lib
> CPPFLAGS: -I/usr/local/opt/readline/include
>
> ==> Summary
> 🍺 /usr/local/Cellar/readline/6.3.8: 46 files, 2M
> ==> Installing python dependency: sqlite
> ==> Downloading https://homebrew.bintray.com/.
> ../sqlite-3.13.0.yosemite.bott
> 
> 100.0%
> ==> Pouring sqlite-3.13.0.yosemite.bottle.tar.gz
> ==> Caveats
> This formula is keg-only, which means it was not symlinked into /usr/local.
>
> OS X provides an older sqlite3.
>
> Generally there are no consequences of this for you. If you build your
> own software and it requires this formula, you'll need to add to your
> build variables:
>
> LDFLAGS: -L/usr/local/opt/sqlite/lib
> CPPFLAGS: -I/usr/local/opt/sqlite/include
>
> ==> Summary
> 🍺 /usr/local/Cellar/sqlite/3.13.0: 10 files, 2.9M
> ==> Installing python dependency: gdbm
> ==> Downloading https://homebrew.bintray.com/.
> ../gdbm-1.12.yosemite.bottle.t
> 
> 100.0%
> ==> Pouring gdbm-1.12.yosemite.bottle.tar.gz
> 🍺 /usr/local/Cellar/gdbm/1.12: 18 files, 490.8K
> ==> Installing python dependency: openssl
> ==> Downloading https://homebrew.bintray.com/.
> ../openssl-1.0.2h_1.yosemite.b
> 
> 100.0%
> ==> Pouring openssl-1.0.2h_1.yosemite.bottle.tar.gz
> ==> Caveats
> A CA file has been bootstrapped using certificates from the system
> keychain. To add additional certificates, place .pem files in
> /usr/local/etc/openssl/certs
>
> and run
> /usr/local/opt/openssl/bin/c_rehash
>
> This formula is keg-only, which means it was not symlinked into /usr/local.
>
> Apple has deprecated use of OpenSSL in favor of its own TLS and crypto
> libraries
>
> Generally there are no consequences of this for you. If you build your
> own software and it requires this formula, you'll need to add to your
> build variables:
>
> LDFLAGS: -L/usr/local/opt/openssl/lib
> CPPFLAGS: -I/usr/local/opt/openssl/include
>
> ==> Summary
> 🍺 /usr/local/Cellar/openssl/1.0.2h_1: 1,691 files, 12.0M
> ==> Installing python
> Warning: Building python from source:
> The bottle needs the Apple Command Line Tools to be installed.
> You can install them, if desired, with:
> xcode-select --install
>
> ==> Downloading https://www.python.org/.../2.7.12/Python-2.7.12.tar.xz
> 
> 100.0%
> ==> Downloading https://bugs.python.org/file30805/issue10910-
> workaround.txt
> 
> 100.0%
> ==> Patching
> ==> Applying issue10910-workaround.txt
> patching file Include/pyport.h
> Hunk #1 succeeded at 713 (offset 14 lines).
> Hunk #2 succeeded at 736 (offset 14 lines).
> ==> ./configure --prefix=/usr/local/Cellar/python/2.7.12 --enable-ipv6
> --dataroo
> ==> make
> /usr/local/share/python/easy_install mecurial
>
> brew install sdl
> brew ins

Re: Quick help for a python newby, please

2016-11-23 Thread Wildman via Python-list
On Thu, 24 Nov 2016 14:49:27 +1100, Chris Angelico wrote:

> On Thu, Nov 24, 2016 at 2:41 PM, Wildman via Python-list
>  wrote:
>> Point taken.  I did miss the python3 part.
>>
>> I switched to raw_input because it handles an empty
>> input.  An empty input would trigger the ValueError.
>> No doubt with the correct code the same or similar
>> could be done with input().  My lack of experience
>> caused me to look for simpler solution and perhaps
>> the wrong one.
> 
> The exact same thing is true of input() in Python 3. In Python 2,
> input() is the same as eval(raw_input()), so don't use it ever [1].
> You can happily use input() in Py3, even if you get empty input.
> 
> I like to put this at the top of cross-version scripts:
> 
> try: input = raw_input
> except NameError: pass
> 
> Then you can proceed to use input() without worries.
> 
> ChrisA
> 
> [1] Yes, I'm aware there are times when evalling the user's input is
> what you want. In those cases, be explicit and use eval.

Understood.  Thank you.

-- 
 GNU/Linux user #557453
The cow died so I don't need your bull!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Random number help

2016-11-23 Thread Larry Hudson via Python-list

On 11/23/2016 11:17 AM, Thomas Grops wrote:

I need a way of generating a random number but there is a catch:

I don't want to include certain numbers, is this possible?

random.randint(1,100) works as it will randomly pick numbers between 1 and 100 
but say i don't want 48 to come out is there a way of doing this. It needs to 
be an integer too so not a list unless there is a way to convert list to int

Many Thanks Tom



Here's a possible generic approach:

#  Come up with a better name for this function
def randx(lo, hi, nw):  #  nw is a list of not-wanted ints
while True:
n = random.randint(lo, hi)
if n not in nw:
return n

Use it the same way as randint(), plus a list of the not-wanted values.
Short example:

---
nw = [1, 3, 5, 7, 9]  #  Odd numbers out
for i in range(10):
print(randx(1, 10, nw), end=' ')
print()
---

Here's the results I got for 3 runs...

4 4 4 8 10 6 8 2 4 8
8 4 2 4 6 8 2 4 8 8
10 6 6 4 4 4 8 2 8 4

Of course, the not-wanted list can be a single int, or even empty.

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


Re: Is this pythonic?

2016-11-23 Thread Steven D'Aprano
On Thursday 24 November 2016 15:55, Frank Millman wrote:

> "Steve D'Aprano"  wrote in message
> news:583653bb$0$1603$c3e8da3$54964...@news.astraweb.com...
> 
>> Even if the computation of the memoised value is done asynchronously, you
>> can easily split the computation off to a separate method (as you already
>> talked about doing!) and make getval() block until it returns.
> 
> Surely that defeats the whole purpose of asyncio. Anything that blocks holds
> up the entire process. I strenuously try to avoid blocking in any shape or
> form.

Perhaps I'm not understanding your task correctly, but surely you have to wait 
for the computation to occur at some point? Even if that's just you hitting 
Refresh waiting for the value of the column to eventually show up.

I'm a newbie to asyncio, but if I were doing this using threads, I'd have 
getval() set the self._cached_value to "pending..." (say), start the 
computation thread running, and then return. The computation thread will 
eventually write the true value to _cached_value, and in the meantime the 
getval() method (and hence __str__ will happily use the "pending..." value. The 
only tricky part is to make sure you only start the thread once.



-- 
Steven
299792.458 km/s — not just a good idea, it’s the law!

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


Re: Is this pythonic?

2016-11-23 Thread Frank Millman
"Steven D'Aprano"  wrote in message 
news:58368358$0$1513$c3e8da3$54964...@news.astraweb.com...



On Thursday 24 November 2016 15:55, Frank Millman wrote:

> "Steve D'Aprano"  wrote in message
> news:583653bb$0$1603$c3e8da3$54964...@news.astraweb.com...
>
>> Even if the computation of the memoised value is done asynchronously, 
>> you
>> can easily split the computation off to a separate method (as you 
>> already

>> talked about doing!) and make getval() block until it returns.
>
> Surely that defeats the whole purpose of asyncio. Anything that blocks 
> holds
> up the entire process. I strenuously try to avoid blocking in any shape 
> or

> form.

Perhaps I'm not understanding your task correctly, but surely you have to 
wait
for the computation to occur at some point? Even if that's just you 
hitting

Refresh waiting for the value of the column to eventually show up.

I'm a newbie to asyncio, but if I were doing this using threads, I'd have
getval() set the self._cached_value to "pending..." (say), start the
computation thread running, and then return. The computation thread will
eventually write the true value to _cached_value, and in the meantime the
getval() method (and hence __str__ will happily use the "pending..." 
value. The

only tricky part is to make sure you only start the thread once.



I am not really qualified to answer this - I *use* asyncio, but I don’t 
really understand what goes on under the covers.


With that caveat, here goes.

To me, the beauty of asyncio (or I suppose async in general) is that I don't 
have to worry about any of what you describe above.


I just have to 'await' whatever I am waiting for. There could be a long 
chain of function calls (which I suppose I should call coroutine calls) but 
at some point one of them is actually going to wait for some I/O, and yield 
control back to the event loop.


At that point, the entire chain is suspended, pending return of the value. 
Once received, control passes back down the chain to the originating 
coroutine, which can then carry on exactly where it left off.


Frank


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


Re: Question about working with html entities in python 2 to use them as filenames

2016-11-23 Thread dieter
Steven Truppe  writes:

> type=  title =  Wizo - Anderster Full Album - YouTube
> type=  title =  Wizo - Bleib Tapfer / für'n Arsch Full
> Album - YouTube
> Traceback (most recent call last):
>   File "./music-fetcher.py", line 39, in 
> title = HTMLParser.HTMLParser().unescape(title)
>   File "/usr/lib/python2.7/HTMLParser.py", line 475, in unescape
> return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));",
> replaceEntities, s)
>   File "/usr/lib/python2.7/re.py", line 155, in sub
> return _compile(pattern, flags).sub(repl, string, count)
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position
> 23: ordinal not in range(128)

This looks like a bug with "HTMLParser" or a usage problem with its
"unescape" method.

I would use "lxml" in order to parse your HTML. It automatically converts
character references (like the above "&39;") and handles special
characters (like "ü") adequately. Under Python 2, "lxml" either returns text
data as "str" (if the result is fully ascii) or "unicode" (otherwise).

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


Re: K-means Python code analyse

2016-11-23 Thread dieter
Alex  writes:

> Can please anyone explaine me what do each of these code lines and how 
> k-means algorithm works?

How about searching "wikipedia"?
(--> "https://en.wikipedia.org/wiki/K-means_clustering";).

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