Re: Can you use self in __str__

2014-11-28 Thread Steven D'Aprano
Seymore4Head wrote:

> def __str__(self):
> s = "Hand contains "
> for x in self.hand:
> s = s + str(x) + " "
> return s
> 
> This is part of a Hand class.  I need a hand for the dealer and a hand
> for the player.
> dealer=Hand()
> player=Hand()
> This prints out 'Hand contains " foo bar
> for both the dealer's hand and the player's hand.
> 
> Is there a way to include "self" in the __string__ so it reads
> Dealer hand contains foo bar
> Player hand contains foo bar

Not unless you tell the instance what name you want it to use.

Instances (objects) have no way of knowing the name of the variable you
attach them to. Or even if there is such a variable -- there could be one,
or none, or a thousand.

Consider:

# one variable, one instance
dealer = Hand()

# three variables, one instance
player1 = player2 = player3 = Hand()

# make that four variables
player4 = player2

# no variable, one instance
print Hand()

some_list = [1, 2, 3, Hand(), 5]


If you ask each instance what their name is, how would they know?


The only way is to give them a name when you create them:

class Hand:
def __init__(self, name):
self.name = name


dealer = Hand("dealer")
player1 = Hand("Bert")
player2 = Hand("Ernie")
player3 = Hand("Scarface")


Now the instances know what their name is, since you've told them, and can
use them any way you like:

def __str__(self):
template = "%s's hand contains: "
return (template % self.name) + "King of Spades"



-- 
Steven

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


Re: Can you use self in __str__

2014-11-28 Thread Dave Angel

On 11/27/2014 10:31 PM, Seymore4Head wrote:

On Thu, 27 Nov 2014 21:49:29 -0500, Dave Angel 
wrote:

class Hand:
 def __init__(self):
 self.hand = []
 # create Hand object

 def __str__(self):
 s = 'Hand contains '
 for x in self.hand:
 s = s + str(x) + " "
 return s

I am using 2.7 (Codeskulptor).  This is working code.  It starts with
an empty list that gets appended from a full deck of shuffled cards.
dealer=Hand()
player=Hand()
I don't really know how to post working code without posting a lot.  I
am not being too successful in trying to post enough code to have it
work without posting the entire code.
Here is the link if you want to run it.
http://www.codeskulptor.org/#user38_Kka7mh2v9u_9.py
The print out looks like this:
Hand contains H4 DQ.

I can (and am) currently printing the hand like this:
print "Player's",player
print "Dealer's",dealer

My question is can you add (self) in the __str__ so when you issue the
command "print player" the "player" part is included in the __str__.



You've already got self in the __str__ method, or you wouldn't have 
access to self.hand.  But there's no characteristic of 'self' that has 
any idea of a name like "dealer" or "player".  You have to add that if 
you want it, as I suggested in my first guess.  Steven has shown you as 
well, along with a better explanation.


An object does NOT know the name or names that may be bound to it, any 
more than I know what page of the county register has my birth 
certificate recorded.  If I want to know my own name, I'd better 
remember it.  Along with any nicknames I want to respond to.  The way to 
do it is the same way to know the hand that I hold, make an instance 
attribute.  And the place to do that is in the __init__() method.



class Hand:
def __init__(self, myname):
self.hand = []
# create Hand object
self.name = myname

def __str__(self):
s = self.name + ' contains '
for x in self.hand:
s = s + str(x) + " "
return s


dealer=Hand("Dealer")
player=Hand("Player")



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


localization virt-manager

2014-11-28 Thread Беляев Игорь
Hello!
I can't install localization for Virt-manager (virt-manager launched on 
python2.7 (Windows XP)).
How do I correctly install location? 
How can I change the value of the environment variable LANG?


-- 
С уважением,
 Беляев Игорь
+79168341810
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can you use self in __str__

2014-11-28 Thread Chris Angelico
On Fri, Nov 28, 2014 at 12:26 PM, Seymore4Head
 wrote:
> dealer=Hand()
> player=Hand()
> This prints out 'Hand contains " foo bar
> for both the dealer's hand and the player's hand.
>
> Is there a way to include "self" in the __string__ so it reads
> Dealer hand contains foo bar
> Player hand contains foo bar

No, you can't. You're assuming that the name bound to an object is
somehow part of that object, but it isn't. What would happen if you
did this:

print(Hand())

There's no name, so you can't get that information. The only way to do
it would be to pass that to the Hand object, but you may as well
simply print it out separately.

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


Re: Can you use self in __str__

2014-11-28 Thread Dave Angel

On 11/27/2014 08:43 PM, Chris Angelico wrote:

On Fri, Nov 28, 2014 at 12:26 PM, Seymore4Head
 wrote:

dealer=Hand()
player=Hand()
This prints out 'Hand contains " foo bar
for both the dealer's hand and the player's hand.

Is there a way to include "self" in the __string__ so it reads
Dealer hand contains foo bar
Player hand contains foo bar


No, you can't. You're assuming that the name bound to an object is
somehow part of that object, but it isn't. What would happen if you
did this:

print(Hand())

There's no name, so you can't get that information. The only way to do
it would be to pass that to the Hand object, but you may as well
simply print it out separately.


It is very useful for a Hand instance to know its "name".

Lots of game strategies treat a collection of such objects identically, 
and then after the fact want to tell them apart.  Printing is one 
example.  But if you've just concluded that object 174fa44 is the 
winner, it'd be nice to be able to tell the user in his own terms.


As you say you shouldn't attempt to guess it, but should pass it into 
the initializer.

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


Re: Asyncio problem, looking for advice.

2014-11-28 Thread Akira Li
Benjamin Risher  writes:

> Hello all,
>
> I'm working on a project to learn asyncio and network programming.  What I'm 
> trying to do is forward a connection from myself to another machine.  Kind of 
> like an asynchronous python implementation of fpipe.
>
> In a nutshell:
>
> 1 --> start a server listening on localhost
> 2 --> connect to server
> 3 --> server connects to a listening service (ssh for instance)
> 4 --> server handles both connections to pass traffic back and forth through 
> each
>
> What I have now *kind of* works.  It sends data back and forth, but when I 
> ssh to localhost -p 12345, i never get the password prompt.  It looks like 
> one packet hangs out and doesn't get sent from what I saw in tcpdump.
>
> Any help would be greatly appreciated.

Do you want to emulate `ssh -L 12345:localhost:22 `?

> Here's a link to the same code as below, just with syntax highlighting etc...
> http://pastebin.com/iLE4GZH3

There are several issue e.g., unnecessary async(), deprecated Task()
calls but the main issue is that _handle_client() doesn't read
concurrently from the server while client writes to it.

You could use asyncio.wait() to run several tasks in parallel
[1]. Here's a forward-port.py example [2]:

  #!/usr/bin/env python3
  """Forward a local tcp port to host:port.
  
  Usage: %(prog)s local_port:host:port
  
  Example:
  
$ python3 forward-port.py 26992:icanhazip.com:80 # start server
  
  and in another window:
  
$ curl localhost:26992 # connect to it
  """
  import asyncio
  import logging
  import sys
  
  info = logging.getLogger('forward-port').info
  
  @asyncio.coroutine
  def copy_stream(reader, writer, bufsize=1<<16):
  while True:
  data = yield from reader.read(bufsize)
  if not data:
  break
  writer.write(data)
  yield from writer.drain()
  writer.close()
  
  def port_forwarder(host, port, *, loop):
  @asyncio.coroutine
  def forward(local_reader, local_writer):
  client = local_writer.get_extra_info('peername')
  info('connected client %s %s', *client)
  remote_reader, remote_writer = yield from 
asyncio.open_connection(host, port, loop=loop)
  yield from asyncio.wait([copy_stream(local_reader, remote_writer),
   copy_stream(remote_reader, local_writer)],
  loop=loop)
  info('disconnected client %s %s', *client)
  
  return forward
  
  # main
  logging.basicConfig(level=logging.INFO,
  format="%(asctime)-15s %(message)s", datefmt="%F %T")
  if len(sys.argv) != 2:
  sys.exit(__doc__)
  local_port, host, port = sys.argv[1].split(':') # e.g., 12345:localhost:22
  
  loop = asyncio.get_event_loop()
  server = loop.run_until_complete(asyncio.start_server(port_forwarder(host, 
int(port), loop=loop),
'localhost', 
int(local_port), loop=loop))
  info('listening on: %s %s', *server.sockets[0].getsockname())
  for closing in range(2):
  try:
  loop.run_until_complete(server.wait_closed())
  except KeyboardInterrupt:
  if not closing:
  server.close()
  info('closing server')
  else:
  break
  info('done')
  loop.close()

[1]
https://docs.python.org/3/library/asyncio-task.html#example-parallel-execution-of-tasks

[2] http://pastebin.com/g08YaJyz


--
Akira

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


Re: Fwd: Python Signal/Slot + QThred code analysis

2014-11-28 Thread Juan Christian
On Fri Nov 28 2014 at 2:07:32 AM Michael Torrie  wrote:
Okay, here's a reworking of the code that invokes a new QThread instance
each time. Note the QThread instance has to be bound to the MainWindow
so that it won't be destroyed when it goes out of scope. Also the
Worker thread sends a signal with the data, so there's no need to check
worker.trades and risk it being invalid data.

Perhaps this would be more what you had in mind.

You may want to look into asynchronous I/O as well. That does not
require threads at all. Fire off a request to load a url, and then get
a callback when it's done.


Now it's working like a charm without any freezes. I'll reproduce this
'Worker' for other stuffs that I need to call the web, but first I have a
question.

Which one would be better in performance, having a single 'Worker' to call
all URLs, having inside this worker functions for each stuff, or having 3~5
different workers doing different stuff. In the end I'll only print the
data when I have them all.

The problem is that I would have a long new_value = Signal(QThread, str,
str), with more then 10 values, is it possible to pass objects here
like new_value = Signal(QThread, ObjA, ObjB, ...) so that in the
'create_topic' I would get the objects and call methods in order to get all
the data?

This approach would be better, because I may be adding more stuff and I
wouldn't need to add tons and tons of new stuff in my signal, only one
object.

You don't need to redo the code, I just need to know if it's a 'good
approach' and if it's possible, from here I can work my way.
-- 
https://mail.python.org/mailman/listinfo/python-list


manipulating an existing plot !

2014-11-28 Thread ram rokr
Hello,
 I already have a script that plots a polygon. But now I'm trying to script 
a python class that would enable me to import the previous plot , make 
instances and control it too(like specifying parameters like spacing , width, 
height or the like). My approach was, to create a new layout and try to import 
the exisiting plot and then try to make instances and manipulate it. 

class DerivedClass(BaseClass):
 
  def __init__(self, layout,topcell):
  self.layout = pya.Layout()
  self.layout.dbu = 0.001
  self.topcell = self.layout.create_cell("TOP")
  l1 = layout.layer(1, 0)
  topcell.shapes(l1).insert(pya.Box(0, 0, 1000, 2000))
  
  self.path = []
  def add_new(self,path):
  self.path.append(path)

  
 
How could I use layer mapping or any other method to accomplish this? Looking 
forward to your advise. Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: localization virt-manager

2014-11-28 Thread Akira Li
Беляев Игорь  writes:

> I can't install localization for Virt-manager (virt-manager launched on 
> python2.7 (Windows XP)).

virt-manager is a GUI for KVM, Xen, LXC virtual machines. It is a Linux
application.

> How do I correctly install location? 

Do you mean *locale*?

> How can I change the value of the environment variable LANG?

On Windows, you could use *setx* command to set an environment variable.

LANG envvar defines a default value for LC_* envvars on POSIX systems [1]
that define application's locale (after setlocale() call) e.g., in bash:

  $ LANG=en_US.UTF-8 some-program

I don't know whether LANG has any meaning on Windows.

[1] http://pubs.opengroup.org/onlinepubs/007908799/xbd/envvar.html


--
Akira


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


Re: Can you use self in __str__

2014-11-28 Thread Rustom Mody
On Friday, November 28, 2014 6:57:23 AM UTC+5:30, Seymore4Head wrote:
> def __str__(self):
> s = "Hand contains "
> for x in self.hand:
> s = s + str(x) + " "
> return s
> 
> This is part of a Hand class.  I need a hand for the dealer and a hand
> for the player.
> dealer=Hand()
> player=Hand()
> This prints out 'Hand contains " foo bar 
> for both the dealer's hand and the player's hand.
> 
> Is there a way to include "self" in the __string__ so it reads
> Dealer hand contains foo bar
> Player hand contains foo bar

And what do you think should be printed if instead of your code

dealer = Hand()
player = Hand()

we have the following

dealer = Hand()
player = dealer

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


Iterate over text file, discarding some lines via context manager

2014-11-28 Thread fetchinson .
Hi all,

I have a feeling that I should solve this by a context manager but
since I've never used them I'm not sure what the optimal (in the
python sense) solution is. So basically what I do all the time is
this:

for line in open( 'myfile' ):
if not line:
# discard empty lines
continue
if line.startswith( '#' ):
# discard lines starting with #
continue
items = line.split( )
if not items:
# discard lines with only spaces, tabs, etc
continue

process( items )

You see I'd like to ignore lines which are empty, start with a #, or
are only white space. How would I write a context manager so that the
above simply becomes

with some_tricky_stuff( 'myfile' ) as items:
process( items )

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
https://mail.python.org/mailman/listinfo/python-list


tabs with tkinter

2014-11-28 Thread ast

Hi

I have been using tkinter for few weeks now and I didn't found
how to make some tabs on a window.

see this picture for a window with tabs
http://www.computerhope.com/jargon/t/tabs.gif

Isn't it feasible with tkinter ?

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


Re: Iterate over text file, discarding some lines via context manager

2014-11-28 Thread Dave Angel

On 11/28/2014 10:04 AM, fetchinson . wrote:

Hi all,

I have a feeling that I should solve this by a context manager but
since I've never used them I'm not sure what the optimal (in the
python sense) solution is. So basically what I do all the time is
this:

for line in open( 'myfile' ):
 if not line:
 # discard empty lines
 continue
 if line.startswith( '#' ):
 # discard lines starting with #
 continue
 items = line.split( )
 if not items:
 # discard lines with only spaces, tabs, etc
 continue

 process( items )

You see I'd like to ignore lines which are empty, start with a #, or
are only white space. How would I write a context manager so that the
above simply becomes

with some_tricky_stuff( 'myfile' ) as items:
 process( items )



I see what you're getting at, but a context manager is the wrong 
paradigm.  What you want is a generator.   (untested)


def mygenerator(filename):
with open(filename) as f:
for line in f:
if not line: continue
if line.startswith('#'): continue
items = line.split()
if not items: continue
yield items

Now your caller simply does:

for items in mygenerator(filename):
  process(items)


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


Re: Iterate over text file, discarding some lines via context manager

2014-11-28 Thread fetchinson .
On 11/28/14, Dave Angel  wrote:
> On 11/28/2014 10:04 AM, fetchinson . wrote:
>> Hi all,
>>
>> I have a feeling that I should solve this by a context manager but
>> since I've never used them I'm not sure what the optimal (in the
>> python sense) solution is. So basically what I do all the time is
>> this:
>>
>> for line in open( 'myfile' ):
>>  if not line:
>>  # discard empty lines
>>  continue
>>  if line.startswith( '#' ):
>>  # discard lines starting with #
>>  continue
>>  items = line.split( )
>>  if not items:
>>  # discard lines with only spaces, tabs, etc
>>  continue
>>
>>  process( items )
>>
>> You see I'd like to ignore lines which are empty, start with a #, or
>> are only white space. How would I write a context manager so that the
>> above simply becomes
>>
>> with some_tricky_stuff( 'myfile' ) as items:
>>  process( items )
>>
>
> I see what you're getting at, but a context manager is the wrong
> paradigm.  What you want is a generator.   (untested)
>
> def mygenerator(filename):
>  with open(filename) as f:
>  for line in f:
>  if not line: continue
>  if line.startswith('#'): continue
>  items = line.split()
>  if not items: continue
>  yield items
>
> Now your caller simply does:
>
> for items in mygenerator(filename):
>process(items)

Great, thanks a lot!

Cheers,
Daniel


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


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Db transactions and locking

2014-11-28 Thread Ian Kelly
On Nov 27, 2014 4:39 PM, "Chris Angelico"  wrote:
>
> On Fri, Nov 28, 2014 at 5:02 AM, Ian Kelly  wrote:
> > On Nov 27, 2014 4:26 AM, "Frank Millman"  wrote:
> >> All Python database adaptors that I have used start a transaction when
you
> >> open a cursor. I have just re-read DB-API 2.0, and I cannot see
anything
> >> that specifies this behaviour, but AFAICT this is what happens.
> >
> > I don't know how others work, but cx_Oracle starts a transaction when
you
> > execute a statement, not when you open a cursor.
>
> Is there any material difference here? I mean, sure, you have a
> transaction, it'll show up in logs and stuff, but without any locks,
> it's unlikely to have much impact on the system. Unless you're
> creating and destroying a bunch of unnecessary cursors all the time,
> of course, but that'd be wasteful for other reasons.

Sure. If you commit the transaction and then execute another statement,
you'll get a new transaction.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: tabs with tkinter

2014-11-28 Thread Peter Otten
ast wrote:

> I have been using tkinter for few weeks now and I didn't found
> how to make some tabs on a window.
> 
> see this picture for a window with tabs
> http://www.computerhope.com/jargon/t/tabs.gif
> 
> Isn't it feasible with tkinter ?

See 

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


Re: Asyncio problem, looking for advice.

2014-11-28 Thread Benjamin Risher
On Friday, November 28, 2014 6:12:20 AM UTC-6, Akira Li wrote:
> Benjamin Risher writes:
> 
> > Hello all,
> >
> > I'm working on a project to learn asyncio and network programming.  What 
> > I'm trying to do is forward a connection from myself to another machine.  
> > Kind of like an asynchronous python implementation of fpipe.
> >
> > In a nutshell:
> >
> > 1 --> start a server listening on localhost
> > 2 --> connect to server
> > 3 --> server connects to a listening service (ssh for instance)
> > 4 --> server handles both connections to pass traffic back and forth 
> > through each
> >
> > What I have now *kind of* works.  It sends data back and forth, but when I 
> > ssh to localhost -p 12345, i never get the password prompt.  It looks like 
> > one packet hangs out and doesn't get sent from what I saw in tcpdump.
> >
> > Any help would be greatly appreciated.
> 
> Do you want to emulate `ssh -L 12345:localhost:22 `?
> 
> > Here's a link to the same code as below, just with syntax highlighting 
> > etc...
> > http://pastebin.com/iLE4GZH3
> 
> There are several issue e.g., unnecessary async(), deprecated Task()
> calls but the main issue is that _handle_client() doesn't read
> concurrently from the server while client writes to it.
> 
> You could use asyncio.wait() to run several tasks in parallel

> [1]
> https://docs.python.org/3/library/asyncio-task.html#example-parallel-execution-of-tasks
> 
> [2] http://pastebin.com/g08YaJyz
> 
> 
> --
> Akira


Akira, 

First, thank you very much for your response.  It helps tremendously.  I have a 
question or two though, if you don't mind.  

You said Task() is deprecated, but it's not listed as such in the docs.  Is it 
just that it's preferred to use other methods instead of using Task() directly, 
or am I missing something?  

Also, just so I can wrap my head around things, I was trying to mix concurrent 
and procedural programming in the code I provided, correct?  Do you have any 
advice on how to avoid mixing types again in the future? 

Thank you again,
Ben
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iterate over text file, discarding some lines via context manager

2014-11-28 Thread Ned Batchelder

On 11/28/14 10:22 AM, Dave Angel wrote:

On 11/28/2014 10:04 AM, fetchinson . wrote:

Hi all,

I have a feeling that I should solve this by a context manager but
since I've never used them I'm not sure what the optimal (in the
python sense) solution is. So basically what I do all the time is
this:

for line in open( 'myfile' ):
 if not line:
 # discard empty lines
 continue
 if line.startswith( '#' ):
 # discard lines starting with #
 continue
 items = line.split( )
 if not items:
 # discard lines with only spaces, tabs, etc
 continue

 process( items )

You see I'd like to ignore lines which are empty, start with a #, or
are only white space. How would I write a context manager so that the
above simply becomes

with some_tricky_stuff( 'myfile' ) as items:
 process( items )



I see what you're getting at, but a context manager is the wrong
paradigm.  What you want is a generator.   (untested)

def mygenerator(filename):
 with open(filename) as f:
 for line in f:
 if not line: continue
 if line.startswith('#'): continue
 items = line.split()
 if not items: continue
 yield items

Now your caller simply does:

for items in mygenerator(filename):
   process(items)




I think it's slightly better to leave the open outside the generator:

def interesting_lines(f):
for line in f:
line = line.strip()
if line.startswith('#'):
continue
if not line:
continue
yield line

with open("my_config.ini") as f:
for line in interesting_lines(f):
do_something(line)

This makes interesting_lines a pure filter, and doesn't care what sort 
of sequence of strings it's operating on.  This makes it easier to test, 
and more flexible.  The caller's code is also clearer in my opinion.


BTW: this example is taken verbatim from my PyCon presentation on 
iteration, it you are interested: http://nedbatchelder.com/text/iter.html


--
Ned Batchelder, http://nedbatchelder.com

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


Re: Iterate over text file, discarding some lines via context manager

2014-11-28 Thread Dave Angel

On 11/28/2014 11:01 AM, Ned Batchelder wrote:

On 11/28/14 10:22 AM, Dave Angel wrote:

On 11/28/2014 10:04 AM, fetchinson . wrote:

Hi all,

I have a feeling that I should solve this by a context manager but
since I've never used them I'm not sure what the optimal (in the
python sense) solution is. So basically what I do all the time is
this:

for line in open( 'myfile' ):
 if not line:
 # discard empty lines
 continue
 if line.startswith( '#' ):
 # discard lines starting with #
 continue
 items = line.split( )
 if not items:
 # discard lines with only spaces, tabs, etc
 continue

 process( items )

You see I'd like to ignore lines which are empty, start with a #, or
are only white space. How would I write a context manager so that the
above simply becomes

with some_tricky_stuff( 'myfile' ) as items:
 process( items )



I see what you're getting at, but a context manager is the wrong
paradigm.  What you want is a generator.   (untested)

def mygenerator(filename):
 with open(filename) as f:
 for line in f:
 if not line: continue
 if line.startswith('#'): continue
 items = line.split()
 if not items: continue
 yield items

Now your caller simply does:

for items in mygenerator(filename):
   process(items)




I think it's slightly better to leave the open outside the generator:

def interesting_lines(f):
 for line in f:
 line = line.strip()
 if line.startswith('#'):
 continue
 if not line:
 continue
 yield line

with open("my_config.ini") as f:
 for line in interesting_lines(f):
 do_something(line)

This makes interesting_lines a pure filter, and doesn't care what sort
of sequence of strings it's operating on.  This makes it easier to test,
and more flexible.  The caller's code is also clearer in my opinion.

Thank you, I agree.  I was trying to preserve the factoring that the OP 
had implied.  I notice you also factored out the split.



BTW: this example is taken verbatim from my PyCon presentation on
iteration, it you are interested: http://nedbatchelder.com/text/iter.html



Thanks for the link.  I've started reading it, and I'll definitely read 
the whole thing.


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


Re: Fwd: Python Signal/Slot + QThred code analysis

2014-11-28 Thread Michael Torrie
On 11/28/2014 06:06 AM, Juan Christian wrote:
> Which one would be better in performance, having a single 'Worker' to call
> all URLs, having inside this worker functions for each stuff, or having 3~5
> different workers doing different stuff. In the end I'll only print the
> data when I have them all.
> 
> The problem is that I would have a long new_value = Signal(QThread, str,
> str), with more then 10 values, is it possible to pass objects here
> like new_value = Signal(QThread, ObjA, ObjB, ...) so that in the
> 'create_topic' I would get the objects and call methods in order to get all
> the data?

Yes you can pass objects through signals.  You could pass a dict, or an
instance of one of your own classes.  You could also go back to your
first architecture and pass in an Outpost class instance to the worker
thread when instantiating it, and then the worker could use the outpost
instance to perform the work, then pass it back to your handler through
the signal.

> This approach would be better, because I may be adding more stuff and I
> wouldn't need to add tons and tons of new stuff in my signal, only one
> object.
> 
> You don't need to redo the code, I just need to know if it's a 'good
> approach' and if it's possible, from here I can work my way.

Yeah sounds alright. I'm sure there are multiple ways of doing this that
would work.

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


Re: Can you use self in __str__

2014-11-28 Thread Rustom Mody
On Friday, November 28, 2014 7:51:40 PM UTC+5:30, Rustom Mody wrote:
> On Friday, November 28, 2014 6:57:23 AM UTC+5:30, Seymore4Head wrote:
> > def __str__(self):
> > s = "Hand contains "
> > for x in self.hand:
> > s = s + str(x) + " "
> > return s
> > 
> > This is part of a Hand class.  I need a hand for the dealer and a hand
> > for the player.
> > dealer=Hand()
> > player=Hand()
> > This prints out 'Hand contains " foo bar 
> > for both the dealer's hand and the player's hand.
> > 
> > Is there a way to include "self" in the __string__ so it reads
> > Dealer hand contains foo bar
> > Player hand contains foo bar
> 
> And what do you think should be printed if instead of your code
> 
> dealer = Hand()
> player = Hand()
> 
> we have the following
> 
> dealer = Hand()
> player = dealer
> 
> ??

Sorry for repeating -- I see Steven said the same
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Iterate over text file, discarding some lines via context manager

2014-11-28 Thread ast

Hi

Here is a solution with a custom iterator which operate on files.
I tested it with a small file. Just a remark, there are no empty line
on a file, there is at least '\n' at the end of each lines but maybe the 
last one. If readline() got an emptyline, then the end of file has been 
reached.



class MyFileItr:
   
   def __init__(self, f):

   self.f = f
   self.line = ""

   def __next__(self):

   while True:
   
   self.line = self.f.readline()


   if (self.line == ''):
   raise StopIteration
  
   if not(self.line.startswith('#') or self.line.isspace() or self.line == '\n'):
   
   return self.line


   def __iter__(self):
   return self


   
f = open('test.txt', 'r')


for L in MyFileItr(f):
   print(L, end="")

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


Re: tabs with tkinter

2014-11-28 Thread ast


"Peter Otten" <[email protected]> a écrit dans le message de 
news:[email protected]...




See 



thx 


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


Re: Iterate over text file, discarding some lines via context manager

2014-11-28 Thread Dave Angel
Please don't start a new thread when responding to an existing topic. 
Just reply-List to the message you're responding to, and include some 
context from that message.


On 11/28/2014 12:06 PM, ast wrote:

Hi

Here is a solution with a custom iterator which operate on files.
I tested it with a small file. Just a remark, there are no empty line
on a file, there is at least '\n' at the end of each lines but maybe the
last one. If readline() got an emptyline, then the end of file has been
reached.


class MyFileItr:
def __init__(self, f):
self.f = f
self.line = ""

def __next__(self):

while True:
self.line = self.f.readline()

if (self.line == ''):
raise StopIteration
if not(self.line.startswith('#') or self.line.isspace() or
self.line == '\n'):
return self.line

def __iter__(self):
return self


f = open('test.txt', 'r')

for L in MyFileItr(f):
print(L, end="")



Why would you prefer that over a generator function, as given earlier in 
the thread?  See for example Ned's message.  By using 'yield', you get 
Python to generate all the class boilerplate for you.




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


Re: Iterate over text file, discarding some lines via context manager

2014-11-28 Thread Marko Rauhamaa
Dave Angel :

> Why would you prefer that over a generator function, as given earlier
> in the thread? See for example Ned's message. By using 'yield', you
> get Python to generate all the class boilerplate for you.

I think the OP can learn from the comparison. One question, many
lessons:

 * Here's how you write a generator.

 * Here's how you write a context manager class. You run into those
   quite often as well.

 * See how much more suitable a generator is in this case.

No need to shoot down those who only try to be helpful.


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


Re: Iterate over text file, discarding some lines via context manager

2014-11-28 Thread Chris Angelico
On Sat, Nov 29, 2014 at 4:55 AM, Marko Rauhamaa  wrote:
> I think the OP can learn from the comparison. One question, many
> lessons:
>
>  * Here's how you write a generator.
>
>  * Here's how you write a context manager class. You run into those
>quite often as well.
>
>  * See how much more suitable a generator is in this case.
>
> No need to shoot down those who only try to be helpful.

Since we're so good at it on this list, I will nit-pick: that's not a
context manager class, that's an iterator class. A context manager has
__enter__ and __exit__, an iterator has __iter__ (returning self) and
__next__ (returning or raising StopIteration).

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


Re: Iterate over text file, discarding some lines via context manager

2014-11-28 Thread Marko Rauhamaa
Chris Angelico :

> Since we're so good at it on this list, I will nit-pick: that's not a
> context manager class, that's an iterator class. A context manager has
> __enter__ and __exit__, an iterator has __iter__ (returning self) and
> __next__ (returning or raising StopIteration).

Excellent. Learnings will never end.


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


Re: Iterate over text file, discarding some lines via context manager

2014-11-28 Thread Michael Torrie
On 11/28/2014 08:04 AM, fetchinson . wrote:
> Hi all,
> 
> I have a feeling that I should solve this by a context manager but
> since I've never used them I'm not sure what the optimal (in the
> python sense) solution is. So basically what I do all the time is
> this:

I'd personally do it with a generator function.

def filter(input):
for line in input:
if not line:
# discard empty lines
continue
if line.startswith( '#' ):
# discard lines starting with #
continue
items = line.split( )
if not items:
# discard lines with only spaces, tabs, etc
continue
yield items

for line_items in filter(open( 'myfile' )):
process( items )

For an excellent presentation on this sort of thing, see:
http://www.dabeaz.com/generators/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Asyncio problem, looking for advice.

2014-11-28 Thread Akira Li
Benjamin Risher  writes:

> On Friday, November 28, 2014 6:12:20 AM UTC-6, Akira Li wrote:
>> Benjamin Risher writes:
>> 
>> > Hello all,
>> >
>> > I'm working on a project to learn asyncio and network programming.
>> > What I'm trying to do is forward a connection from myself to
>> > another machine.  Kind of like an asynchronous python
>> > implementation of fpipe.
>> >
>> > In a nutshell:
>> >
>> > 1 --> start a server listening on localhost
>> > 2 --> connect to server
>> > 3 --> server connects to a listening service (ssh for instance)
>> > 4 --> server handles both connections to pass traffic back and forth 
>> > through each
>> >
>> > What I have now *kind of* works.  It sends data back and forth,
>> > but when I ssh to localhost -p 12345, i never get the password
>> > prompt.  It looks like one packet hangs out and doesn't get sent
>> > from what I saw in tcpdump.
>> >
>> > Any help would be greatly appreciated.
>> 
>> Do you want to emulate `ssh -L 12345:localhost:22 `?
>> 
>> > Here's a link to the same code as below, just with syntax highlighting 
>> > etc...
>> > http://pastebin.com/iLE4GZH3
>> 
>> There are several issue e.g., unnecessary async(), deprecated Task()
>> calls but the main issue is that _handle_client() doesn't read
>> concurrently from the server while client writes to it.
>> 
>> You could use asyncio.wait() to run several tasks in parallel
>
>> [1]
>> https://docs.python.org/3/library/asyncio-task.html#example-parallel-execution-of-tasks
>> 
>> [2] http://pastebin.com/g08YaJyz
>> 


> Akira, 
>
> First, thank you very much for your response.  It helps tremendously.
> I have a question or two though, if you don't mind.
>
> You said Task() is deprecated, but it's not listed as such in the
> docs.  Is it just that it's preferred to use other methods instead of
> using Task() directly, or am I missing something?

asyncio is a provisional API [3], it may change without notice (though
it shouldn't without a reason). From asyncio docs [4]:

  Don’t directly create Task instances: use the async() function or the
  BaseEventLoop.create_task() method.

The reason is probably to support Trollius (asyncio for Python 2) [5].

> Also, just so I can wrap my head around things, I was trying to mix
> concurrent and procedural programming in the code I provided, correct?
> Do you have any advice on how to avoid mixing types again in the
> future?

In short, the main issue was that your code executed some parts
sequentially e.g., A then B:

  yield from A
  yield from B # this is not reached until A finishes

that needed to be run concurrently:

  yield from asyncio.wait([A, B])

or in general, if you don't need to wait the results:

  asyncio.async(A)
  asyncio.async(B) 

  # ... yield later, to pass the control to the event loop
(Task._step/_fut_waiter dance ☯)

Ask, if you have any specific questions about the code
http://pastebin.com/g08YaJyz 

There is a bug at the end. info('done') should be outside the loop
(improper indent).

[3] https://www.python.org/dev/peps/pep-0411
[4] https://docs.python.org/3/library/asyncio-task.html#asyncio.Task
[5] https://code.google.com/p/tulip/issues/detail?id=185


--
Akira

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


Re: Iterate over text file, discarding some lines via context manager

2014-11-28 Thread Akira Li
Ned Batchelder  writes:

> On 11/28/14 10:22 AM, Dave Angel wrote:
>> On 11/28/2014 10:04 AM, fetchinson . wrote:
>>> Hi all,
>>>
>>> I have a feeling that I should solve this by a context manager but
>>> since I've never used them I'm not sure what the optimal (in the
>>> python sense) solution is. So basically what I do all the time is
>>> this:
>>>
>>> for line in open( 'myfile' ):
>>>  if not line:
>>>  # discard empty lines
>>>  continue
>>>  if line.startswith( '#' ):
>>>  # discard lines starting with #
>>>  continue
>>>  items = line.split( )
>>>  if not items:
>>>  # discard lines with only spaces, tabs, etc
>>>  continue
>>>
>>>  process( items )
>>>
>>> You see I'd like to ignore lines which are empty, start with a #, or
>>> are only white space. How would I write a context manager so that the
>>> above simply becomes
>>>
>>> with some_tricky_stuff( 'myfile' ) as items:
>>>  process( items )
>>>
>>
>> I see what you're getting at, but a context manager is the wrong
>> paradigm.  What you want is a generator.   (untested)
>>
>> def mygenerator(filename):
>>  with open(filename) as f:
>>  for line in f:
>>  if not line: continue
>>  if line.startswith('#'): continue
>>  items = line.split()
>>  if not items: continue
>>  yield items
>>
>> Now your caller simply does:
>>
>> for items in mygenerator(filename):
>>process(items)
>>
>>
>
> I think it's slightly better to leave the open outside the generator:
>
> def interesting_lines(f):
> for line in f:
> line = line.strip()
> if line.startswith('#'):
> continue
> if not line:
> continue
> yield line
>
> with open("my_config.ini") as f:
> for line in interesting_lines(f):
> do_something(line)
>
> This makes interesting_lines a pure filter, and doesn't care what sort
> of sequence of strings it's operating on.  This makes it easier to
> test, and more flexible.  The caller's code is also clearer in my
> opinion.
>
> BTW: this example is taken verbatim from my PyCon presentation on
> iteration, it you are interested:
> http://nedbatchelder.com/text/iter.html

The conditions could be combined in this case:

  def iter_rows(lines):
  for line in lines:
  items = line.split()
  if items and not items[0].startswith('#'):
 yield items # space-separated non-emtpy non-comment items
  
  with open(filename):
  for items in iter_rows(file):
  process(items)


--
Akira

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


Re: tabs with tkinter

2014-11-28 Thread Terry Reedy

On 11/28/2014 10:52 AM, Peter Otten wrote:

ast wrote:


I have been using tkinter for few weeks now and I didn't found
how to make some tabs on a window.

see this picture for a window with tabs
http://www.computerhope.com/jargon/t/tabs.gif

Isn't it feasible with tkinter ?


See 


Notebook is one of the newer, ttk-only widgets.

--
Terry Jan Reedy

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


Re: I love assert

2014-11-28 Thread Steven D'Aprano
alister wrote:

> And as may wiser people than me have already highlighted Assertions can
> be switched off in python which means they cannot be relied upon in
> production code invalidating the authors suggestion that they can
> automate bug reports & "Extend testing into the lifetime of the product"

I'm afraid that you appear to have missed the point of assertions as tests.
Since they should never be used to *enforce* correct behaviour, but only to
*verify* behaviour is correct (i.e. as a form of testing), it doesn't
matter if you disable them. If I turn them off, all that happens is that
the tests won't run *for me*. The software will still be just as correct,
or just as buggy, regardless of the assertions.

But not everyone will turn them off. Even if *everybody else* turns them
off, you, the developer of the software, surely won't[1] since you're not
an idiot. (Why write assertions only to never use them?) That means that
whenever you run your software during the process of development, your
assertions will run.

In a complex, rich software application, you may not have unit tests for
every possible path through the software. But if you put assertions at the
intersections of paths (e.g. at the top of each loop, or the entry and exit
of each function), then even if you don't have a unit test for a particular
path, at least the assertions will be there to provide limited testing. In
other words, correctly written assertions can provide simple but effective
test coverage of 100% of your application.

I stress that assertions aren't a replacement for unit testing, but they
compliment unit testing: assertions can help cover code missed by your unit
tests, and check that your unit tests are correct.

If the user of your application disables assertions, they will be no worse
off than if you didn't write those assertions at all. And if they enable
assertions, then they get extended testing throughout the lifetime of the
product *for free*.

(Well, perhaps not *quite* for free, since assertions do have some
performance cost. But very cheaply.)




[1] Thanks to Python defaulting to __debug__ = True, the problem is getting
people to remember to test their software with assertions disabled, not to
get them to enable them.


-- 
Steven

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


Re: I love assert

2014-11-28 Thread MRAB

On 2014-11-29 01:30, Steven D'Aprano wrote:
[snip]

I stress that assertions aren't a replacement for unit testing, but they
compliment unit testing: assertions can help cover code missed by your unit
tests, and check that your unit tests are correct.


[snip]

I think you meant "complement". :-)

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


Re: I love assert

2014-11-28 Thread Chris Angelico
On Sat, Nov 29, 2014 at 1:56 PM, MRAB  wrote:
> On 2014-11-29 01:30, Steven D'Aprano wrote:
> [snip]
>>
>> I stress that assertions aren't a replacement for unit testing, but they
>> compliment unit testing: assertions can help cover code missed by your
>> unit
>> tests, and check that your unit tests are correct.
>>
> [snip]
>
> I think you meant "complement". :-)

assert "Unit tests are soo clever"

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


Re: Can you use self in __str__

2014-11-28 Thread Shiyao Ma
2014-11-28 13:00 GMT+08:00 Chris Angelico :
> On Fri, Nov 28, 2014 at 2:04 PM, Shiyao Ma  wrote:
>> What if it's in the local namespace of a function or method? IDK, try
>> to get that thing first.
>
Sure enough. I will even avoid using "id" as it's dependent on CPython
implementation. :)

> What if it's in multiple namespaces? What if it's not in any at all?
> Your solution is not going to work in the general case, AND it's a bad
> idea.
> Please don't do this in any code that I'll ever have to
> maintain.
No way. You will never get my project code in such a form. I am way
more peculiar about readability and robustness than most of my other
ppl.
The point is, the bpate is just for demonstration to show there is a
*possible* way to find the name even you didn't specify it at first
hand.




-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can you use self in __str__

2014-11-28 Thread Chris Angelico
On Sat, Nov 29, 2014 at 2:16 PM, Shiyao Ma  wrote:
> 2014-11-28 13:00 GMT+08:00 Chris Angelico :
>> On Fri, Nov 28, 2014 at 2:04 PM, Shiyao Ma  wrote:
>>> What if it's in the local namespace of a function or method? IDK, try
>>> to get that thing first.
>>
> Sure enough. I will even avoid using "id" as it's dependent on CPython
> implementation. :)

You can use id() on any object. You are guaranteed to get back an
integer which is both stable and unique among all ids of objects that
exist at the same time as the one you called it on. For as long as the
object continues to exist, that number *will* stay the same. Sometimes
that's all you need; for instance, imagine a simple mail server which
produces logs like this:

[142857] Beginning processing of message
[142857] Parsing headers
[314159] Beginning processing of message
[314159] Parsing headers
[142857] Storing in destination mailbox
[314159] Connecting to destination server
[142857] Finished processing of message
[314159] Message accepted by destination
[271871] Beginning processing of message
[314159] Finished processing of message

You can easily see, from the initial numbers, what log lines are
associated with what messages. (Note that emails have their own IDs,
which could in theory be used, but the id() of an internal dict can be
used even before the email's ID has been read - as you see from the
example, a log entry for "Parsing headers" has to be made prior to
info from the headers being used.) It's not a problem if another
142857 comes up later on; there's a very clear begin and end to the
message, and you're guaranteed that nothing can possibly be
interspersed with a colliding ID.

In other implementations of Python, these numbers might look less
arbitrary (Jython, I believe, allocates them sequentially); but the
code will work just as well on any compliant implementation of the
language, because everything I've said above is a language guarantee,
not a CPython implementation detail.

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


Re: Can you use self in __str__

2014-11-28 Thread Shiyao Ma
2014-11-29 11:36 GMT+08:00 Chris Angelico :
> You can use id() on any object. You are guaranteed to get back an
> integer which is both stable and unique among all ids of objects that
> exist at the same time as the one you called it on. For as long as the
> object continues to exist, that number *will* stay the same. Sometimes
> that's all you need; for instance, imagine a simple mail server which
> produces logs like this:
>
> [142857] Beginning processing of message
> [142857] Parsing headers
> [314159] Beginning processing of message
> [314159] Parsing headers
> [142857] Storing in destination mailbox
> [314159] Connecting to destination server
> [142857] Finished processing of message
> [314159] Message accepted by destination
> [271871] Beginning processing of message
> [314159] Finished processing of message
>
> You can easily see, from the initial numbers, what log lines are
> associated with what messages. (Note that emails have their own IDs,
> which could in theory be used, but the id() of an internal dict can be
> used even before the email's ID has been read - as you see from the
> example, a log entry for "Parsing headers" has to be made prior to
> info from the headers being used.) It's not a problem if another
> 142857 comes up later on; there's a very clear begin and end to the
> message, and you're guaranteed that nothing can possibly be
> interspersed with a colliding ID.
>
> In other implementations of Python, these numbers might look less
> arbitrary (Jython, I believe, allocates them sequentially); but the
> code will work just as well on any compliant implementation of the
> language, because everything I've said above is a language guarantee,
> not a CPython implementation detail.
>
> ChrisA


Thanks. Informed.
The implementation dependent thing is "id(obj)" == virtual mem addr
(which caused my bad feeling).
Apparently have nothing to do with it here, though.

And 'id' is seemingly great to differentiate each obj.



--

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: tabs with tkinter

2014-11-28 Thread Peter Otten
Terry Reedy wrote:

> On 11/28/2014 10:52 AM, Peter Otten wrote:
>> ast wrote:
>>
>>> I have been using tkinter for few weeks now and I didn't found
>>> how to make some tabs on a window.
>>>
>>> see this picture for a window with tabs
>>> http://www.computerhope.com/jargon/t/tabs.gif
>>>
>>> Isn't it feasible with tkinter ?
>>
>> See 
> 
> Notebook is one of the newer, ttk-only widgets.

There is also an old "Python megawidgets" project that offers a notebook:

http://pmw.sourceforge.net/doc/NoteBook.html

To my surprise Python 3 is supported:

https://pypi.python.org/pypi/Pmw

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