Re: Can Python function return multiple data?

2015-06-03 Thread Thomas Rachel

Am 03.06.2015 um 01:56 schrieb Chris Angelico:


and it's pretty convenient. In C, the nearest equivalent is passing a
number of pointers as parameters, and having the function fill out
values. Python's model is a lot closer to what you're saying than C's
model is :)


At least, C functions can return structs...

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


Re: subprocess.Popen zombie

2015-05-20 Thread Thomas Rachel

Am 20.05.2015 um 18:44 schrieb Robin Becker:


not really, it's just normal to keep event routines short; the routine
which beeps is after detection of the cat's entrance into the house and
various recognition schemes have pronounced intruder :)


You could add a timed "cleanup" routine which .wait()s after a certain 
time (250 ms or so).


Or even better, which .poll()s and re-schedules itself if the process 
still runs.



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


Re: Why does the first loop go wrong with Python3

2015-05-19 Thread Thomas Rachel

Am 19.05.2015 um 15:16 schrieb Oscar Benjamin:


However the normal way to do this is to iterate over stdout directly:


Depends. There may be differences when it comes to buffering etc...


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


Re: Rule of order for dot operators?

2015-05-18 Thread Thomas Rachel

Am 16.05.2015 um 21:20 schrieb C.D. Reimer:


Does python perform the dot operators from left to right or according to
a rule of order (i.e., multiplication/division before add/subtract)?


In this case, it does the only thing it can do:

title = slug.replace('-',' ').title()

is performed as

* take slug
* get its replace method
* call it and take the result
* get this result's title method
* call it and store its result into title.

OTOH,

title = slug.title().replace('-',' ')

is performed as

* take slug
* get its title method
* call it and take the result
* get this result's replace method
* call it and store its result into title.

Any other order would be unintuitive and just wrong.

The reason why the result is the same is because .title() title-cases 
letters after a space as well as after a '-'.


In other cases, it wouldn't do so, so you have to take care what you do.


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


Re: Basic misunderstanding on object creation

2015-05-13 Thread Thomas Rachel

Am 13.05.2015 um 15:25 schrieb andrew cooke:


class Foo:

... def __new__(cls, *args, **kargs):
... print('new', args, kargs)
... super().__new__(cls, *args, **kargs)



new (1,) {}
Traceback (most recent call last):
   File "", line 1, in 
   File "", line 4, in __new__
TypeError: object() takes no parameters


object's __new__() dosn't take any parameters. So call it without arguments:

class Foo:
def __new__(cls, *args, **kargs):
print('new', args, kargs)
super().__new__(cls)

(at least if we know that we inherit from object. Might be that this one 
doesn't work very good with multiple inheritance...)



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


Re: Python Worst Practices

2015-03-06 Thread Thomas Rachel

Am 26.02.2015 01:37 schrieb Chris Angelico:


My bad. I was talking in a context of Python programming, specifically
with APIs where you would use some kind of true/false flag as either a
function parameter or a return value.


Oh. Then take subprocess.Popen.wait()... :-P


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


Re: Md5 is different in Windows and Linux

2015-03-02 Thread Thomas Rachel

Am 02.03.2015 20:14 schrieb sohcahto...@gmail.com:

On Monday, March 2, 2015 at 12:43:59 AM UTC-8, Sarvagya Pant wrote:



f = open("somefile.txt")


This one is the problem. Under Windows, you have to open the file in 
binary to avoid that something "bad" happens with it.


So just do

f = open("somefile.txt", "rb")

and you should be fine.



I don't know which is worse, the fact that you're composing your message in 
HTML, or the fact that you're using Comic Sans as your font.


#2 wouldn't be possible without #1...


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


Re: why can't download file from linux server into local window disk c:

2014-12-09 Thread Thomas Rachel
Am 08.12.2014 19:11 schrieb Luuk:

> no, it's the ssh-server denying a log on from 'root'

You are repating yourself.

How could possibly

 with open(localpath, 'wb') as fl:
PermissionError: [Errno 13] Permission denied: 'c:'

be a problem with the SSH server?

--- SoupGate-Win32 v1.05
 * Origin: nntp.gatew...@.piz.noip.me> (1:249/999)
--- Synchronet 3.15b-Win32 NewsLink 1.92
SpaceSST BBS Usenet <> Fidonet Gateway
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why can't download file from linux server into local window disk c:

2014-12-09 Thread Thomas Rachel
Am 09.12.2014 09:14 schrieb pengsir:

> My vps ip is x.y.z.w ,i want to download /etc/passwd from linux server
> into my local window disk c: .

> localpath = 'c:'

[...]

>  with open(localpath, 'wb') as fl:
> PermissionError: [Errno 13] Permission denied: 'c:'

That's completely clear: you are not allowed to create a file named
'c:'. You should replace it with a full path name, such as

localpath = 'c:\\passwd'

or such.


Thomas

--- SoupGate-Win32 v1.05
 * Origin: nntp.gatew...@.piz.noip.me> (1:249/999)
--- Synchronet 3.15b-Win32 NewsLink 1.92
SpaceSST BBS Usenet <> Fidonet Gateway
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question on lambdas

2014-12-09 Thread Thomas Rachel

Am 09.12.2014 04:09 schrieb memilanuk:


so in the first example in my original post:

...
lambda: update_label2('A', 100)

would this work the same?  It looks as though it'd be passing the same
two parameters to the same function...

lambda: 'A', 100: update_label2()


No. Even if it would be allowed by syntax, how should 'A', 100 be passed 
to update_label2() if it is not written inside its ()s?



Also, in my second example:

class MyText(Text):
 def __init__(self, master, **kw):
 apply(Text.__init__, (self, master), kw)
 self.bind("", lambda e: "break")

I'm kind of missing what 'e' is and where its defined and what it's
supposed to be passing to "break"...?


Passing to "break"? A string cannot be passed anything.

What bind() expects is any callable which takes an event object (IIRC).

As you don't need any information from the event object here, you can 
ignore it (but it must be oresent, otherwise the call would fail).


What the function does is just return "break". What sense this should 
have is unclear to me; probably the return value is just ignored.




I was reading in 'Programming Python 4th ed' by Lutz and he talks about
something to do with default values vs. enclosing scopes...  that
something like:

lambda x=x: some_expr

when evaluated inside a function loop to create buttons, etc., causes
'x' to be evaluated as the default value at the function creation time,
vs. when the function is actually called.  Do I have that more or less
correct?


Yes. This one takes the current value of x inside the function.

Compare these:

x = 4
f1 = lambda: x
x = 5
f2 = lambda: x
x = 42
print f1(), f2()

What could one expect? "4 5", maybe. What does one get? "42 42". Why? 
Because the x is evaluated at the time it is indeed called.


We can work around this with

x = 4
f1 = lambda y=x: y
x = 5
f2 = lambda y=x: y
x = 42
print f1(), f2()

(you can take x for y here, but this one is better understandable)

Here each of the function gets the respective value "tattooed in"; we 
get "4 5" indeed as output.


Downside is that we have the possibility to do print f1(123) which 
indeed gives 123.


If we want to disallow this kind of calls, we could do

def create_const_function(val):
def inner_function():
return val

or just

create_const_function = lambda val: lambda: val

and then

f1 = create_const_function(4)
f2 = create_const_function(5)
print f1(), f2()

et voilà.


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


Re: why can't download file from linux server into local window disk c:?

2014-12-08 Thread Thomas Rachel

Am 08.12.2014 19:11 schrieb Luuk:


no, it's the ssh-server denying a log on from 'root'


You are repating yourself.

How could possibly

with open(localpath, 'wb') as fl:
PermissionError: [Errno 13] Permission denied: 'c:'

be a problem with the SSH server?
--
https://mail.python.org/mailman/listinfo/python-list


Re: why can't download file from linux server into local window disk c:?

2014-12-08 Thread Thomas Rachel

Am 09.12.2014 09:14 schrieb pengsir:


My vps ip is x.y.z.w ,i want to download /etc/passwd from linux server
into my local window disk c: .



localpath = 'c:'


[...]


 with open(localpath, 'wb') as fl:
PermissionError: [Errno 13] Permission denied: 'c:'


That's completely clear: you are not allowed to create a file named 
'c:'. You should replace it with a full path name, such as


localpath = 'c:\\passwd'

or such.


Thomas

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


Re: io.UnsupportedOperation: fileno

2014-11-14 Thread Thomas Rachel

Am 14.11.2014 00:42 schrieb satishmlm...@gmail.com:

fileno() in not supported. Is it only in 3.1? What is the workaround?


You have been asked many times about the details of your environment.

Especially, you have been told that it is important to know if you 
directly use the Python CLI or some GUI like IDLE.


I just tested the latter thing and found out that it indeed makes a 
difference, as it introduces a replacement for the std* stuff you are 
missing:


>>> sys.stdin

>>> sys.stdout

>>> sys.stderr


Calling .fileno() on such a Pseudo*File just raises an 
UnsupportedOperation exception.


This is in contrast to using the CLI directly.
--
https://mail.python.org/mailman/listinfo/python-list


Re: %%(%s)s mean in python

2014-10-29 Thread Thomas Rachel

Am 29.10.2014 07:02 schrieb satishmlm...@gmail.com:


What does %%(%s)s mean in Python?


Weird question, as this has nothing to do with the code you just posted.

In general, what comes up to my mind, is that it is a format string to 
build another format string.


Example:

metafmt = '%%(%s)s'
fieldname = 'myfield'
fmt = metafmt % fieldname
# Now we have a fmt as if it was assigned with '%(myfield)s':
# %% -> %, %s -> myfield.

d = {fieldname: 'my content'}

print fmt % d
# this now prints the given field - which is noted in fieldname -
# from the given dict d.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Iterator, modify data in loop body

2014-09-16 Thread Thomas Rachel

Am 13.09.2014 09:22 schrieb Chris Angelico:


In that case, don't iterate over the list at all. Do something like this:

while lst:
 element = lst.pop(0)
 # work with element
 lst.append(new_element)


And if you don't like that, define a

def iter_pop(lst):
while lst:
yield lst.pop(0)

and you can do

for element in iter_pop(lst):
# work with element
lst.append(new_element)


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


Re: Thread-ID - how much could be?

2014-09-16 Thread Thomas Rachel

Am 11.09.2014 23:32 schrieb Ervin Hegedüs:


There is no upper limit to the thread name other than that you will
eventually run out of memory ;)


thanks - I hope that the memory will not run out by these
threads... :)

Anyway, that means, on my system:


import sys
print sys.maxint

9223372036854775807

the couter could be 9223372036854775807?

And after? :)


After that, the couter magically turns into a long and it goes on.


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


Re: 'is not' or '!='

2014-08-21 Thread Thomas Rachel

Am 20.08.2014 13:17 schrieb Chris Angelico:


That's true, but how easy is it to annotate a file with each line's
author (or, at least, to figure out who wrote some particular line of
code)? It's easy enough with 'git blame' or 'hg blame', and it
wouldn't surprise me if bzr had a similar feature; but that's all the
current generation of version control systems. I don't think cvs or
svn offered that kind of feature.


$ LANG=C svn help blame
blame (praise, annotate, ann): Output the content of specified files or
URLs with revision and author information in-line.
usage: blame TARGET[@REV]...

$ cvs help
Unknown command: `help'

CVS commands are:
add  Add a new file/directory to the repository
adminAdministration front end for rcs
annotate Show last revision where each line was modified
[...]

IMHO annotate does the same what blame does on other VCS.


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


Re: 'is not' or '!='

2014-08-19 Thread Thomas Rachel

Am 18.08.2014 22:53 schrieb Marko Rauhamaa:


Frankly, I don't know of any other object that is "==" to the None
object except None itself, but such objects could possible exist.


class ImitatingNone(object):
def __eq__(self, other):
return True # is equal to everything else
return other is None # is equal only to None
return not(other) # is equal to everything which is falsey


Pick one.

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


Re: 'is not' or '!='

2014-08-19 Thread Thomas Rachel

Am 19.08.2014 00:04 schrieb Chris Kaynor:


In each of these cases, the behavior may be different in other
implementations or versions of Python.


And, the most important thing, in each of these cases, using "is" is 
semantically wrong, so no matter how different versions behave.


If you ask the wrong question, you might get a wrong answer.


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


Re: Iterating through set

2014-07-17 Thread Thomas Rachel

Am 15.07.2014 02:10 schrieb LJ:

Hi All.

I'm coding a Dynamic Programming algorithm to solve a network flow problem. At 
some point in the algorithm I have to iterate through a set of nodes, while 
adding and/or removing elements, until the set is empty. I know a regular set() 
object does not work in a case like this, so I wonder if anyone knows of an 
efficient pythonic way to handle this.

Thanks in advance!



This sounds like you want to avoid processing of an item as soon as it 
is removed.


Then I'd suggest the following:

add = set()
remove = set()

while myset or add:
for item in myset:
if item not in remove:
# process
myset -= remove
myset += add
remove.clear()
add.clear()

Adding happens via add.add(item), removing via remove.add(item).

If there is additionally the need to take care in which order to apply 
add/remove, or if it can happen that item X is added and removed in the 
same loop run, it gets a bit more complicated.


Then adding would be like

if item in remove:
remove.remove(item)
elif item not in myset and item not in add:
add.add(item)

and removing like

if item in add:
add.remove(item)
elif item in myset:
remove.add(item)


HTH,

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


Re: Python's re module and genealogy problem

2014-06-11 Thread Thomas Rachel

Am 11.06.2014 14:23 schrieb BrJohan:


Can it, for a pair of regular expressions be decided whether at least
one string matching both of those regular expressions, can be constructed?

If it is possible to make such a decision, then how? Anyone aware of an
algorithm for this?


Just a feeling-based statement: I don't think that is easily possible.

Every RE can potentially match an infinite number of statements.

Just have a look at

re1 = re.compile('A43.*')
re2 = re.compile('.*[0-9][A-F]')

It can easily seen that the area these REs work on is different; they 
are orthogonal.


So there is an infinite number of strings these REs match.


Thomas

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


Re: try/except/finally

2014-06-10 Thread Thomas Rachel

Am 08.06.2014 05:58 schrieb Rustom Mody:


Some people¹ think that gotos are a code-smell.
 ¹ I am not exactly those people.
A chap called E W Dijkstra made the statement: "Goto statement considered
harmful" and became famous.


And became widely misunderstood. If anybody would read the whole what he 
wrote, people would learn that he doesn't criticise the *use* of goto, 
but he wants the *replacement* of goto with something else (like 
exceptions).


As C doesn't have exceptions, goto is in many cases the simplest and 
easiest way of handling errors.


Essentially, you can write both good and bad code both with and without 
goto.



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


Re: Python 3 __bytes__ method

2014-01-15 Thread Thomas Rachel

Am 12.01.2014 01:24 schrieb Ethan Furman:


I must admit I'm not entirely clear how this should be used.  Is anyone
using this now?  If so, how?


I am not, as I currently am using Py2, but if I would, I would do it e. 
g. for serialization of objects in order to send them over the line or 
to save them into a file. IOW, the same purpose as we havd on __str__ in 
Py2.



Thomas

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


Re: 'Straße' ('Strasse') and Python 2

2014-01-13 Thread Thomas Rachel

Am 13.01.2014 10:54 schrieb wxjmfa...@gmail.com:


Not at all. I'm afraid I'm understanding Python (on this
aspect very well).


IBTD.


Do you belong to this group of people who are naively
writing wrong Python code (usually not properly working)
during more than a decade?


Why should I be?


'ß' is the the fourth character in that text "Straße"
(base index 0).


Character-wise, yes. But not byte-string-wise. In a byte string, this 
depends on the character set used.


On CP 437, 850, 12xx (whatever Windows uses) or latin1, you are right, 
but not on the widely used UTF8.



sys.version

'2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)]'

assert 'Straße'[4] == 'ß'
assert u'Straße'[4] == u'ß'


Linux box at home:

Python 2.7.3 (default, Apr 14 2012, 08:58:41) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> assert 'Straße'[4] == 'ß'
Traceback (most recent call last):
  File "", line 1, in 
AssertionError
>>> assert u'Straße'[4] == u'ß'

Python 3.3.0 (default, Oct 01 2012, 09:13:30) [GCC] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> assert 'Straße'[4] == 'ß'
>>> assert u'Straße'[4] == u'ß'

Windows box at work:

Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit 
(AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> assert 'Straße'[4] == 'ß'
>>> assert u'Straße'[4] == u'ß'


PS Nothing to do with Py2/Py3.


As bytes and unicode and str stuff is heavily changed between them, of 
course it has to do.


And I think you know that and try to confuse and FUD us all - with no avail.


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


Re: 'Straße' ('Strasse') and Python 2

2014-01-13 Thread Thomas Rachel

Am 12.01.2014 08:50 schrieb wxjmfa...@gmail.com:

sys.version

2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)]

s = 'Straße'
assert len(s) == 6
assert s[5] == 'e'



Wow. You just found one of the major differences between Python 2 and 3.

Your assertins are just wrong, as s = 'Straße' leads - provided you use 
UTF8 - to a representation of 'Stra\xc3\x9fe', obviously leading to a 
length of 7.



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


Re: New user's initial thoughts / criticisms of Python

2013-11-10 Thread Thomas Rachel

Am 09.11.2013 14:27 schrieb Joshua Landau:


`select` is quite an odd statement, in that in most cases it's just a
weaker variant of `if`. By the time you're at the point where a
`select` is actually more readable you're also at the point where a
different control flow is probably a better idea. Things like
dictionaries or a variables pointing to functions are really useful
and can be encapsulated in a class quite well. This is a bit more
advanced but largely more rigorous.


class Switch(object):
def __init__(self, value):
self.value = value
self.called = False
def case(self, other):
def wr(func):
if not self.called and self.value == other:
self.called = True
return func(self.value)
return wr
def default(self, func):
if not self.called:
self.called = True
return func(self.value)


if __name__ == '__main__':
import random

while 1:
n = random.randrange(0, 5)
sw = Switch (n)
@sw.case(1)
def _(n): print n, "is one"

@sw.case(2)
def _(n): print n, "is two"

@sw.default
def _(n): print n, "is something else"

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


Re: Is there a function that applies list of functions to a value?

2013-08-28 Thread Thomas Rachel

Am 2013-08-28 14:52 schrieb AdamKal:

Hi,

 From time to time I have to apply a series of functions to a value in such a 
way:

func4(func3(func2(func1(myval

I was wondering if there is a function in standard library that would take a 
list of functions and a initial value and do the above like this:

func_im_looking_for([func1, func2, func3, func4], myval)

I looked in itertools but nothing seamed to do the job. This seams like 
something vary obvious that was needed many times elsewhere so maybe you could 
help me?


reduce(lambda x, f: f(x), funcs, myval)

would do the job.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: A certainl part of an if() structure never gets executed.

2013-06-26 Thread Thomas Rachel

Am 12.06.2013 03:46 schrieb Rick Johnson:

On Tuesday, June 11, 2013 8:25:30 PM UTC-5, nagia@gmail.com wrote:


is there a shorter and more clear way to write this?
i didnt understood what Rick trie to told me.


My example included verbatim copies of interactive sessions within the Python 
command line. You might understand them better if you open the Python command 
line and type each command in one-by-one. Here is an algoritm that explains the 
process:

open_command_window()
whilst learning or debugging:
 type_command()
 press_enter()
 observe_output()
 if self.badder.is_full:
 take_potty_break()
close_command_window()


with command_window():
   whilst learning or debugging:
  type_command()
  press_enter()
  observe_output()
  if self.badder.is_full:
  take_potty_break()

looks nicer.

SCNR


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Piping processes works with 'shell = True' but not otherwise.

2013-05-29 Thread Thomas Rachel

Am 27.05.2013 02:14 schrieb Carlos Nepomuceno:

pipes usually consumes disk storage at '/tmp'.


Good that my pipes don't know about that.

Why should that happen?


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: object.enable() anti-pattern

2013-05-10 Thread Thomas Rachel

Am 10.05.2013 15:22 schrieb Roy Smith:


That's correct.  But, as described above, the system makes certain
guarantees which allow me to reason about the existence or non-existence
os such entries.


Nevertheless, your 37 is not a FD yet.

Let's take your program:


#include 
#include 
#include 
#include 

int main(int argc, char** argv) {
 int max_files = getdtablesize();
 assert(max_files >= 4);


Until here, the numbers 3 toll max_files may or may not be FDs.


 for (int i = 3; i < max_files; ++i) {
 close(i);
 }


Now they are closed; they are definitely no longer FDs even if they 
were. If you would use them in a file operation, you'd get a EBADF which 
means "fd is not a valid file descriptor".



 dup(2);



From now on, 3 is a FD and you can use it as such.


 char* message = "hello, fd world\n";
 write(3, message, strlen(message));
}




No, what I've done is taken advantage of behaviors which are guaranteed
by POSIX.


Maybe, but the integer numbers get or los their property as a file 
descriptor with open() and close() and not by assigning them to an int.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Style question -- plural of class name?

2013-05-09 Thread Thomas Rachel

Am 09.05.2013 02:38 schrieb Colin J. Williams:

On 08/05/2013 4:20 PM, Roy Smith wrote:


"A list of FooEntry's"  +1


Go back to school. Both of you...

That is NOT the way to build a plural form...


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: is "_io.py" missing from 2.7.4 ?

2013-04-08 Thread Thomas Rachel

Am 08.04.2013 15:42 schrieb dbv:

Ah, okay.  Then on Windows, _io.pyd should be in the /DLLs folder but it isn't 
there ?


It seems to be a built-in module:

>>> import _io
>>> _io


alike to

>>> import __builtin__
>>> __builtin__


as opposed to

>>> import win32ui
>>> win32ui
'C:\Python27\lib\site-packages\Pythonwin\win32ui.pyd'>


and

>>> import os
>>> os



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: del not working for (exhausted) dict iterable value (Python 3.3)

2013-03-12 Thread Thomas Rachel

Am 12.03.2013 06:52 schrieb alex23:


You're effectively doing this:


event = dict(Items=[1,2,3])
for e in event['Items']:

... del event['Items']
...
Traceback (most recent call last):
   File "", line 2, in 
KeyError: 'Items'

You want to move your del statement up an indentation level so it
happens after the iterator is actually exhausted, and not after the
first iteration.


Just to be clear: Exhausting the iterator is not the problem, as I 
thought as well at the first glance.


The problem is the fact that the loop body tuns multiple times - and so 
does the del statement. A


event = dict(Items=[1,2,3])
for e in event['Items']:
if 'Items' in event: del event['Items']

runs perfectly, as the iterable is transformed to an iterator at the 
very start of the loop.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: This mail never gets delivered. Any ideas why?

2013-03-11 Thread Thomas Rachel

Am 10.03.2013 19:39 schrieb Νίκος Γκρ33κ:

Hey man  this worked via Python!


[...]


if( os.system( 'echo "%s" | mail -s "%s" supp...@superhost.gr' 
% (MESSAGE, FROM) ) ):


[...]


Thank you! I beleive this is the simplest way of sending an email!


Until you get a MESSAGE which has a " sign in it, or a FROM.

(Sorry, didn't see this message before.)

In order to prevent trouble with this, it might be better to use 
subprocess and to do


sp = subprocess.Popen(['mail', '-f', FROM, '-s', SUBJECT,
'supp...@superhost.gr], stdin=subprocess.PIPE)
sp.communicate(MESSAGE)
res = sp.wait()
if res:
...
else:
...


If you do so, you can have FROMs, SUBJECTs and MESSAGEs conaining every 
character you want, including " and ', an no shell will complain about 
it or be confused.


(Note that I changed the arguments for mail a little bit, because -s 
prevedes the subject and -f the from.)



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: This mail never gets delivered. Any ideas why?

2013-03-11 Thread Thomas Rachel

Am 11.03.2013 10:15 schrieb nagia.rets...@gmail.com:

Thank you Thomas but that simple line as i have it now its capable of
sending mail successfully


Obviously not, otherwise you wouldn't ask, would you?


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: This mail never gets delivered. Any ideas why?

2013-03-10 Thread Thomas Rachel

Am 11.03.2013 06:47 schrieb Thomas Rachel:


# either
message.add_header('Subject', email.quoprimime.header_encode(SUBJECT))

# or
message.add_header('Subject', email.base64mime.header_encode(SUBJECT))


Sorry! These were completely wrong.

# either
message.add_header('Subject', email.quoprimime.header_encode(SUBJECT,
charset='utf8'))

# or
message.add_header('Subject', email.base64mime.header_encode(SUBJECT,
charset='utf8'))

should be correct, however.


But be aware that both seem to potentially break the UTF8 surrogates 
apart, which in turn confuses at least Thunderbird, so it might not be 
the ideal solution.


Maybe you transcode the subject into iso-8859-7 and declare it as such, 
if you only have greek characters.


Let's try:

[...]
# and then
# either
enc = email.base64mime.header_encode
# or
enc = email.quoprimime.header_encode

message.add_header('Subject', enc(
SUBJECT.decode('utf8').encode('iso-8859-7'),
charset='iso-8859-7'))

I tried both values for enc(), and both seem to work with the subject 
string you provided.



HTH,


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: This mail never gets delivered. Any ideas why?

2013-03-10 Thread Thomas Rachel

Am 11.03.2013 06:25 schrieb Thomas Rachel:


1. Your subject is not properly encoded.

All characters outside the ASCII area must be encoded in an appropriate
way if you send an email. It MIGHT be the case that sendmail handles
this for you, but probably not every version.


Mine not, at least.

So you should do this:

import email
message = email.message_from_string('')
message.add_header('From', FROM)
message.add_header('To', ", ".join(TO))
# and then

# either
message.add_header('Subject', email.quoprimime.header_encode(SUBJECT))

# or
message.add_header('Subject', email.base64mime.header_encode(SUBJECT))

# Here you should decide upon readability: for Greek text, base64 is
# probably better,  while for languages with Latin characters, quopri
# is better because bost characters remain readable.
#
# The difference is
#
# Subject: 
=?iso-8859-1?q?=CE=95=CF=80=CE=B9=CE=BA=CE=BF=CE=B9=CE=BD=CF=89=CE=BD=CE?=

#  =?iso-8859-1?q?=AF=CE=B1_=CF=80=CE=B9=CE=B8=CE=B1=CE=BD=CE=BF=CF=8D_=CF?=
#  =?iso-8859-1?q?=80=CE=B5=CE=BB=CE=AC=CF=84=CE=B7!?=
#
# vs.
#
# Subject: 
=?iso-8859-1?b?zpXPgM65zrrOv865zr3Pic69zq/OsSDPgM65zrjOsc69zr/PjSDPgM61zrs=?=

#  =?iso-8859-1?b?zqzPhM63IQ==?=
#
#
# If your sender or your recipients have names outside the ASCII area,
# you should quote them as well.


# These are for the text.
message.add_header('MIME-Version', '1.0')
message.add_header('Content-Type', 'text/plain; charset=utf8')
message.add_header('Content-Transfer-Encoding', '8bit')

message.set_payload(TEXT)

# now transform the object into a string:

message = message.as_string()

print message


This message string now can be used for sending.


HTH,

Thomas

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


Re: This mail never gets delivered. Any ideas why?

2013-03-10 Thread Thomas Rachel

Am 09.03.2013 22:20 schrieb Νίκος Γκρ33κ:

SENDMAIL = '/usr/sbin/sendmail'

FROM = mail
TO = ['supp...@superhost.gr']
SUBJECT = "Επικοινωνία πιθανού πελάτη!"
TEXT = comment

message = """\
  From: %s
  To: %s
  Subject: %s

  %s
  """ % (FROM, ", ".join(TO), SUBJECT, TEXT)

p = os.popen("%s -t -i" % SENDMAIL, "w")
p.write(message)
status = p.close()
if status != 256:
print( "Ευχαριστώ πολύ για το ενδιαφέρον! Θα 
επικοινωνήσω μαζί σου άμεσα :-)" )
else:
print( "Δυστυχώς δεν μπόρεσε να 
αποσταλεί το e-mail :-(" )

===

Do you see somehtign wrong in the above code?



I see some things here:

1. Your subject is not properly encoded.

All characters outside the ASCII area must be encoded in an appropriate 
way if you send an email. It MIGHT be the case that sendmail handles 
this for you, but probably not every version.


But that should not prevent sending the mail at all; probably some 
garbage would result.


2. You failed to tell us what "never gets delivered" means: do you get 
an error message?


3. You failed to give us a SSCCE : in order to test 
the code, I had to add several variable definitions and imports.


4., an I thik this is the point: you are indenting your message string.
If you put a print(message) somewhere into the code, you'll see that the 
email header lines don't start with the header names, but with spaces. 
That is something which sendmail cannot and won't handle. Likewise, the 
header-body-separator is probably broken as well.


Just write, even if your code is indented in some way:

message = """\
From: %s
To: %s
Subject: %s

%s""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

or maybe, just to be sure,

message = "From: %s\nTo: %s\nSubject: %s\n\n%s" % \
(FROM, ", ".join(TO), SUBJECT, TEXT)

in order to get a useful result.


And, as you are working on it, don't use os.popen - it is deprecated. 
Better use subprocess:


replace

p = os.popen("%s -t -i" % SENDMAIL, "w")
p.write(message)
status = p.close()

with

import subprocess
sp = subprocess.Popen([SENDMAIL, '-t', '-i'], stdin=subprocess.PIPE)
sp.communicate(message)
status = sp.wait()

giving more flexibility.


HTH,

Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: "The urlopen() and urlretrieve() functions can cause arbitrarily long delays"

2013-02-24 Thread Thomas Rachel

Am 24.02.2013 20:27 schrieb 7segment:


When in doubt, check some other way, such as with a browser.


Thank you Ian. Browser is not a good idea, because I need this tool to
work automatically. I don't have time to check and compare the response
times manually and put them into the database.


Of course not for the long term. But you could check e.g. if MSN needs 
60 s as well from the browser. If not, there could be something else wrong.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: improving performance of writing into a pipe

2013-02-18 Thread Thomas Rachel

Am 18.02.2013 17:31 schrieb mikp...@gmail.com:


However I get an exception while trying to open the queue:
fout = open('/tmp/mypipe', 'w')


I don't see an exception in your answer. Where did you put it for us?



I have tried it in a command line and the call doesn't return until in another 
terminal I open the same queue for reading (???)


That's normal. An open call to a pipe blocks until someone reads from it.

But it's the same with your popen() version.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: inheritance and how to use it

2013-02-15 Thread Thomas Rachel

Am 15.02.2013 17:59 schrieb Bob Brusa:

Hi,
I use a module downloaded from the net. Now I want to build my own
class, based on the class SerialInstrument offered in this module - and
in my class I would like to initialize a few things, using e. g. the
method clear() offered by SerialInstrument. Hence I type:

class myClass(SerialInstrument)
 self.clear(self)
 def f1(self, str1, str2)
 ...do something etc.

I then get the message "self not know" from the statement
self.clear(self).


Which is absolutely correct. Besides, I would have expected some syntax 
errors.


You try to execute the clear() method during the definition of the 
class, not during the instantiation.


Instantiation happens in the __init__() method.

You'll have to do it like this:

class myClass(SerialInstrument):
def __init__(self, *a, **k): # accept all parameters
super(myClass, self).__init__(*a, **k)
self.clear() # I don't think that self is to be given twice here...
def f1(self, str1, str2):
pass

I have tried many other notations - none worked. What

works is however the following code - specifying myClass without the
self.clear(self) in it:

x = myClass("argument")
x.clear()


Here the clear() is called on the object which has been created, so 
after calling the __init__() above (which is, roughly, equivalent to 
calling it at the bottom of __init__()).



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2013-02-10 Thread Thomas Rachel

Am 10.02.2013 12:37 schrieb Steven D'Aprano:


So, in Python 4000, my vote is for set literals { } to create frozensets,
and if you want a mutable set, you have to use the set() type directly.


4000 sounds about long future.

In the meanwhile, a new syntax element could be introduced fpr 
frozensets, such as {{ }} or something. (Although that might clutter 
with a set containing a set.)



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2013-02-08 Thread Thomas Rachel

Am 08.02.2013 07:29 schrieb Rick Johnson:


Consider this:

 if connect("my:db") as db:
 

No need to make a call and then test for the validity of the call when you can 
do both simultaneously AND intuitively.


Would be great, but can be emulated with

def ifiter(x):
if x: yield x

for db in ifiter(connect("my:db")):


Is not very intuitive, however, but does its job.


Thomas

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


Re: i can't understand decorator

2013-01-15 Thread Thomas Rachel

Am 15.01.2013 15:20 schrieb contro opinion:


 >>> def deco(func):
...  def kdeco():
...  print("before myfunc() called.")
...  func()
...  print("  after myfunc() called.")
...  return kdeco
...
 >>> @deco
... def myfunc():
...  print(" myfunc() called.")
...
 >>> myfunc()
before myfunc() called.
  myfunc() called.
   after myfunc() called.
 >>> deco(myfunc)()
before myfunc() called.
before myfunc() called.
  myfunc() called.
   after myfunc() called.
   after myfunc() called.


Wrapping works this way:

The function is defined, and the wrapper replaces the function with a 
different one which (in this case) calls the original one.


Try print(myfunc) here and you see that myfunc is only a name for 
another function called kdeco. It is the one returned by the decorator.




1.
why there are two lines :before myfunc() called.and tow lines :after
myfunc() called. in the output?


This is because the "before" line is printed, then the modified "myfunc" 
is called, which in turn prints another "before" line and then calls the 
"really original" function. After it returns, the "after" line is called 
by the inner placement function (the one which sticks at the myfunc 
identifier). This function returns and the function instance which 
called the first "before" line is printed then.



2.why the result is not
before myfunc() called.
  myfunc() called.
   after myfunc() called.
before myfunc() called.
  myfunc() called.
   after myfunc() called.


Because the function calls are wrapped and not repeated.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: please i need explanation

2013-01-11 Thread Thomas Rachel

Am 11.01.2013 17:33 schrieb kwakukwat...@gmail.com:


def factorial(n):
 if n<2:
  return 1
 f = 1
 while n>= 2:
 f *= n
 f -= 1
 return f




please it works.


I doubt this.

If you give n = 4, you run into an endless loop.



but don’t get why the return 1 and the code below.


The "if n < 2: return 1" serves to shorten the calculation process 
below. It is redundant, as you have a "f = 1" and a "return f" for n < 2.


The code below first sets f, which holds the result, to 1 and then 
multiplies it by n in each step. As the loop should contain a 'n -= 1', 
n decreases by 1 every step, turning it into f = n * (n-1) * (n-2) * ... 
* 2 and then, as n is not >= 2 any longer, stops the loop, returning f.


HTH,

Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to modify this script?

2013-01-08 Thread Thomas Rachel

Am 07.01.2013 18:56 schrieb Gertjan Klein:


(Watch out for line wraps! I don't know how to stop Thunderbird from
inserting them.)


Do "insert as quotation" (in German Thunderbird: "Als Zitat einfügen"), 
or Strg-Shift-O. Then it gets inserted with a ">" before and in blue.


Just remove the > and the space after it; the "non-breaking property" is 
kept.


Example:

columns = line.split("\t");
if len(columns) == 1:
output += ('' % max_columns) + line + 
'\n'

continue

without and

columns = line.split("\t");
if len(columns) == 1:
output += ('' % max_columns) + line + 
'\n'

continue

with this feature.

HTH,

Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to modify this script?

2013-01-08 Thread Thomas Rachel

Am 06.01.2013 15:30 schrieb Kurt Hansen:

Den 06/01/13 15.20, Chris Angelico wrote:

On Mon, Jan 7, 2013 at 1:03 AM, Kurt Hansen  wrote:

I'm sorry to bother you, Chris, but applying the snippet with your
code in
Gedit still just deletes the marked, tab-separated text in the editor.



Ah, whoops. That would be because I had a bug in the code (that's why
I commented that it was untested). Sorry about that! Here's a fixed
version:


[cut]>

Note that it's a single line:

output += '' + item +
' '

If your newsreader (or my poster) wraps it, you'll need to unwrap that
line, otherwise you'll get an IndentError.


Ahhh, I did'nt realize that. Now it works :-)


That version should work.


It certainly does. I'll keep it and use it until at better solution is
found.


That would be simple:

Replace

output += '' + item +
' '

with

if len(columns) >= 3:
output += ''
else:
output += ''
output += item + ' '

(untested as well; keep the indentation in mind!)


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: what’s the difference between socket.send() and socket.sendall() ?

2013-01-07 Thread Thomas Rachel

Am 07.01.2013 11:35 schrieb iMath:

what’s the difference between socket.send() and socket.sendall() ?

It is so hard for me to tell the difference between them from the python doc

so what is the difference between them ?

and each one is suitable for which case ?



The docs are your friend. See

http://docs.python.org/2/library/socket.html#socket.socket.sendall

| [...] Unlike send(), this method continues to send data from string
| until either all data has been sent or an error occurs.

HTH,

Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: forking and avoiding zombies!

2012-12-11 Thread Thomas Rachel

Am 11.12.2012 14:34 schrieb peter:

On 12/11/2012 10:25 AM, andrea crotti wrote:

Ah sure that makes sense!

But actually why do I need to move away from the current directory of
the parent process?
In my case it's actually useful to be in the same directory, so maybe
I can skip that part,
or otherwise I need another chdir after..

You don't need to move away from the current directory. You cant use os
to get the current work directory

stderrfile = '%s/error.log' % os.getcwd()
stdoutfile = '%s/out.log' % os.getcwd()


ITYM

os.path.join(os.getcwd(), 'error.log')

resp.

os.path.join(os.getcwd(), 'out.log')


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Confused compare function :)

2012-12-06 Thread Thomas Rachel

Am 06.12.2012 09:49 schrieb Bruno Dupuis:


The point is Exceptions are made for error handling, not for normal
workflow. I hate when i read that for example:

 try:
 do_stuff(mydict[k])
 except KeyError:
 pass


I as well, but for other reasons (see below). But basically this is EAFP.



(loads of them in many libraries and frameworks)
instead of:

 if k in mydict:
 do_stuff(mydict[k])


This is LBYL, C-style, not Pythonic.

I would do

try:
value = mydict[k]
except KeyError:
pass
else:
do_stuff(k)

Why? Because do_stuff() might raise a KeyError, which should not go 
undetected.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: os.popen and the subprocess module

2012-11-29 Thread Thomas Rachel

Am 27.11.2012 19:00 schrieb Andrew:


I'm looking into os.popen and the subprocess module, implementing
os.popen is easy but i hear it is depreciating however I'm finding the
implemantation of subprocess daunting can anyone help


This is only the first impression.

subprocess is much more powerful, but you don't need to use the full power.

For just executing and reading the data, you do not need much.

First step: create your object and performing the call:

sp = subprocess.Popen(['program', 'arg1', 'arg2'], stdout=subprocess.PIPE)

or

sp = subprocess.Popen('program arg1 arg2', shell=True, 
stdout=subprocess.PIPE)



The variant with shell=True is more os.popen()-like, but has security 
flaws (e.g., what happens if there are spaces or, even worse, ";"s in 
the command string?



Second step: Obtain output.

Here you either can do

stdout, stderr = sp.communicate()

can be used if the whole output fits into memory at once or you really 
have to deal with stderr or stdin additionally.


In other, simpler cases, it is possible to read from sp.stdout like from 
a file (with a for loop, with .read() or whatever you like).



Third step: Getting the status, terminating the process.

And if you have read the whole output, you do status = sp.wait() in 
order not to have a zombie process in your process table and to obtain 
the process status.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python garbage collector/memory manager behaving strangely

2012-11-15 Thread Thomas Rachel

Am 17.09.2012 04:28 schrieb Jadhav, Alok:

Thanks Dave for clean explanation. I clearly understand what is going on
now. I still need some suggestions from you on this.

There are 2 reasons why I was using  self.rawfile.read().split('|\n')
instead of self.rawfile.readlines()

- As you have seen, the line separator is not '\n' but its '|\n'.
Sometimes the data itself has '\n' characters in the middle of the line
and only way to find true end of the line is that previous character
should be a bar '|'. I was not able specify end of line using
readlines() function, but I could do it using split() function.
(One hack would be to readlines and combine them until I find '|\n'. is
there a cleaner way to do this?)
- Reading whole file at once and processing line by line was must
faster. Though speed is not of very important issue here but I think the
tie it took to parse complete file was reduced to one third of original
time.


With

def itersep(f, sep='\0', buffering=1024, keepsep=True):
if keepsep:
keepsep=sep
else:   keepsep=''
data = f.read(buffering)
next_line = data # empty? -> end.
while next_line: # -> data is empty as well.
lines = data.split(sep)
for line in lines[:-1]:
yield line+keepsep
next_line = f.read(buffering)
data = lines[-1] + next_line
# keepsep: only if we have something.
if (not keepsep) or data:
yield data

you can iterate over everything you want without needing too much 
memory. Using a larger "buffering" might improve speed a little bit.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to simulate tar filename substitution across piped subprocess.Popen() calls?

2012-11-13 Thread Thomas Rachel

Am 12.11.2012 19:30 schrieb Hans Mulder:


This will break if there are spaces in the file name, or other
characters meaningful to the shell.  If you change if to

 xargsproc.append("test -f '%s/{}'&&  md5sum '%s/{}'"
  % (mydir, mydir))

, then it will only break if there are single quotes in the file name.


And if you do mydir_q = mydir.replace("'", "'\\''") and use mydir_q, you 
should be safe...



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to simulate tar filename substitution across piped subprocess.Popen() calls?

2012-11-13 Thread Thomas Rachel

Am 09.11.2012 02:12 schrieb Hans Mulder:


That's what 'xargs' will do for you.  All you need to do, is invoke
xargs with arguments containing '{}'.  I.e., something like:

cmd1 = ['tar', '-czvf', 'myfile.tgz', '-c', mydir, 'mysubdir']
first_process = subprocess.Popen(cmd1, stdout=subprocess.PIPE)

cmd2 = ['xargs', '-I', '{}', 'sh', '-c', "test -f %s/'{}'" % mydir]
second_process = subprocess.Popen(cmd2, stdin=first_process.stdout)


After launching second_process, it might be useful to 
firstprocess.stdout.close(). If you fail to do so, your process is a 
second reader which might break things apart.


At least, I once hat issues with it; I currently cannot recapitulate 
what these were nor how they could arise; maybe there was just the open 
file descriptor which annoyed me.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: stackoverflow quote on Python

2012-11-13 Thread Thomas Rachel

Am 13.11.2012 14:21 schrieb wxjmfa...@gmail.com:


* strings are now proper text strings (Unicode), not byte strings;


Let me laugh.


Do so.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Printing characters outside of the ASCII range

2012-11-11 Thread Thomas Rachel

Am 09.11.2012 18:17 schrieb danielk:


I'm using this character as a delimiter in my application.


Then you probably use the *byte* 254 as opposed to the *character* 254.

So it might be better to either switch to byte strings, or output the 
representation of the string instead of itself.


So do print(repr(chr(254))) or, for byte strings, print(bytes([254])).


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Obnoxious postings from Google Groups

2012-11-09 Thread Thomas Rachel

Am 31.10.2012 06:39 schrieb Robert Miles:


For those of you running Linux:  You may want to look into whether
NoCeM is compatible with your newsreader and your version of Linux.


This sounds as if it was intrinsically impossible to evaluate NoCeMs in 
Windows.


If someone writes a software for it, it can be run wherever desired.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Immutability and Python

2012-11-07 Thread Thomas Rachel

Am 29.10.2012 16:20 schrieb andrea crotti:


Now on one hand I would love to use only immutable data in my code, but
on the other hand I wonder if it makes so much sense in Python.


You can have both. Many mutable types distinguish between them with 
their operators.


To pick up your example,


class NumWrapper(object):
def __init__(self, number):
self.number = number
def __iadd__(self, x):
self.number += x
return self
def __add__(self, x):
return NumWrapper(self.number + x)

So with

number += 1

you keep the same object and modify it, while with

number = number + 1

or

new_number = number + 1

you create a new object.



But more importantly normally classes are way more complicated than my
stupid example, so recreating a new object with the modified state might
be quite complex.

Any comments about this? What do you prefer and why?


That's why I generally prefer mutable objects, but it can depend.


Thomas

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


Re: better way for ' '.join(args) + '\n'?

2012-10-27 Thread Thomas Rachel

Am 26.10.2012 09:49 schrieb Ulrich Eckhardt:

Hi!

General advise when assembling strings is to not concatenate them
repeatedly but instead use string's join() function, because it avoids
repeated reallocations and is at least as expressive as any alternative.

What I have now is a case where I'm assembling lines of text for driving
a program with a commandline interface.


Stop.

In this case, you think too complicated.

Just do

subprocess.Popen(['prog', 'foo', 'bar', 'baz'])

-  is the most safest thing for this use case.

If it should not be possible for any reason, you should be aware of any 
traps you could catch - e.g., if you want to feed your string to a 
Bourne shell, you should escape the strings properly.


In such cases, I use


def shellquote(*strs):
	r"""Input: file names, output: ''-enclosed strings where every ' is 
replaced with '\''. Intended for usage with the shell."""

# just take over everything except ';
# replace ' with '\''
# The shell sees ''' as ''\'''\'''\'''. Ugly, but works.
return " ".join([
"'"+st.replace("'","'\\''")+"'"
for st in strs
])


so I can use

shellquote('program name', 'argu"ment 1', '$arg 2',
"even args containing a ' are ok")

For Windows, you'll have to modify this somehow.


HTH,

Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: a.index(float('nan')) fails

2012-10-27 Thread Thomas Rachel

Am 27.10.2012 06:48 schrieb Dennis Lee Bieber:


I don't know about the more modern calculators, but at least up
through my HP-41CX, HP calculators didn't do (binary) "floating
point"... They did a form of BCD with a fixed number of significant
/decimal/ digits


Then, what about sqrt(x)**2 or arcsin(sin(x))? Did that always return 
the original x?


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: while expression feature proposal

2012-10-25 Thread Thomas Rachel

Am 25.10.2012 18:36 schrieb Ian Kelly:

On Thu, Oct 25, 2012 at 1:21 AM, Thomas Rachel

wrote:

j = next(j for j in iter(partial(randrange, n), None) if j not in
selected)



This generator never ends. If it meets a non-matching value, it just skips
it and goes on.


next() only returns one value.  After it is returned, the generator is
discarded, whether it has ended or not.  If there were no valid values
for randrange to select, then it would descend into an infinite loop.
But then, so would the dropwhile and the original while loop.


You are completely right. My solution was right as well, but didn't 
match the problem...


Yours does indeed return one random value which is guaranteed not to be 
in selected.


Mine returns random values until the value is not in selected. I just 
misread the intention behind the while loop...



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: while expression feature proposal

2012-10-25 Thread Thomas Rachel

Am 25.10.2012 16:15 schrieb Grant Edwards:


I guess that depends on what sort of programs you write.  In my
experience, EXPR is usually a read from a file/socket/pipe that
returns '' on EOF. If VAR is not '', then you process, then you
process it inside the loop.


Right. The same as in

if regex.search(string) as match:
process it

But with

def if_true(expr):
if expr: yield expr

you can do

for match in if_true(regex.search(string)):
process it

But the proposed if ... as ...: statment woulkd be more beautiful by far.

Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: while expression feature proposal

2012-10-25 Thread Thomas Rachel

Am 25.10.2012 12:50 schrieb Steven D'Aprano:


Then I think you have misunderstood the purpose of "yield from".


Seems so. As I have not yet switched to 3.x, I haven't used it till now.


[quote]
However, if the subgenerator is to interact properly with the caller in
the case of calls to send(), throw() and close(), things become
considerably more difficult. As will be seen later, the necessary code is
very complicated, and it is tricky to handle all the corner cases
correctly.


Ok, thanks.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: while expression feature proposal

2012-10-25 Thread Thomas Rachel

Am 25.10.2012 09:21 schrieb Thomas Rachel:


I think

# iterate ad inf., because partial never returns None:
i1 = iter(partial(randrange, n), None)
# take the next value, make it None for breaking:
i2 = (j if j in selected else None for j in i1)
# and now, break on None:
i3 = iter(lambda: next(i2), None)

would do the job.


But, as I read it now again, it might be cleaner to create an own 
generator function, such as


def rand_values(randrange, n, selected):
# maybe: selected = set(selected) for the "not in"
while True:
val = partial(randrange, n)
if val not in selected: break
yield val

for value in rand_values(...):

or, for the general case proposed some posings ago:

def while_values(func, *a, **k):
while True:
val = func(*a, **k):
if not val: break
yield val

Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: while expression feature proposal

2012-10-25 Thread Thomas Rachel

Am 25.10.2012 06:50 schrieb Terry Reedy:


Keep in mind that any new syntax has to be a substantial improvement in
some sense or make something new possible. There was no new syntax in
3.2 and very little in 3.3.


I would consinder this at least as new substantial than

yield_from it

as opposed to

for i in it: yield i

- although I think that was a good idea as well.

Although there are quite easy ways to do so, I would appreciate 
something like the proposed


   while EXPR as VAR: use VAR
   if EXPR as VAR: use VAR

Of course it is possible to construct a respective workaround such as

def maybe_do_that():
if moon == full:
with something as val:
yield val

for val in maybe_do_that():
bla

but I would consider this as an abuse of the generator concept.

Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: while expression feature proposal

2012-10-25 Thread Thomas Rachel

Am 25.10.2012 00:26 schrieb Cameron Simpson:


If I could write this as:

   if re_FUNKYPATTERN.match(test_string) as m:
 do stuff with the results of the match, using "m"

then some cascading parse decisions would feel a bit cleaner. Where I
current have this:

   m = re_CONSTRUCT1.match(line)
   if m:
 ... handle construct 1 ...
   else:
 m = re_CONSTRUCT2.match(line)
 if m:
   ... handle construct 2 ...
 else:
   m = re_CONSTRUCT3.match(line)

I could have this:

   if re_CONSTRUCT1.match(line) as m:
 ... handle construct 1 ...
   elif re_CONSTRUCT2.match(line) as m:
 ... handle construct 2 ...
   elif re_CONSTRUCT3.match(line) as m:


I would do

for r in re_CONSTRUCT1, re_CONSTRUCT2, re_CONSTRUCT3:
m = r.match(line)
if m: handle_construct

or maybe

actions = {re_CONSTRUCT1: action1, ...}

def matching(line, *rr):
for r in rr:
m = r.match(line)
if m: yield r; return

for r in matching(line, *actions.keys()):
actions[r]()
break
else:
raise NoActionMatched() # or something like that

Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: while expression feature proposal

2012-10-25 Thread Thomas Rachel

Am 25.10.2012 01:39 schrieb Ian Kelly:

On Wed, Oct 24, 2012 at 5:08 PM, Paul Rubin  wrote:

from itertools import dropwhile

j = dropwhile(lambda j: j in selected,
  iter(lambda: int(random() * n), object()))
  .next()

kind of ugly, makes me wish for a few more itertools primitives, but I
think it expresses reasonably directly what you are trying to do.


Nice, although a bit opaque.  I think I prefer it as a generator expression:

j = next(j for j in iter(partial(randrange, n), None) if j not in selected)


This generator never ends. If it meets a non-matching value, it just 
skips it and goes on.


The dropwhile expression, however, stops as soon as the value is found.

I think

# iterate ad inf., because partial never returns None:
i1 = iter(partial(randrange, n), None)
# take the next value, make it None for breaking:
i2 = (j if j in selected else None for j in i1)
# and now, break on None:
i3 = iter(lambda: next(i2), None)

would do the job.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python does not take up available physical memory

2012-10-19 Thread Thomas Rachel

Am 19.10.2012 21:03 schrieb Pradipto Banerjee:


Thanks, I tried that.


What is "that"? It would be helpful to quote in a reasonable way. Look
how others do it.



Still got MemoryError, but at least this time python tried to use the
physical memory. What I noticed is that before it gave me the error
it used up to 1.5GB (of the 2.23 GB originally showed as available) -
so in general, python takes up more memory than the size of the file
itself.


Of course - the file is not the only thing to be held by the process.

I see several approaches here:

* Process the file part by part - as the others already suggested, 
line-wise, but if you have e.g. a binary file format, other partings may 
be suitable as well - e.g. fixed block size, or parts given by the file 
format.


* If you absolutely have to keep the whole file data in memory, split it 
up in several strings. Why? Well, the free space in virtual memory is 
not necessarily contiguous. So even if you have 1.5G free, you might not 
be able to read 1.5G at once, but you might succeed in reading 3*0.5G.




Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: overriding equals operation

2012-10-16 Thread Thomas Rachel

Am 16.10.2012 15:51 schrieb Pradipto Banerjee:


I am trying to define class, where if I use a statement a = b, then instead of "a" pointing to the 
same instance as "b", it should point to a copy of "b", but I can't get it right.


This is not possible.



Currently, I have the following:



class myclass(object):


Myclass or MyClass, see http://www.python.org/dev/peps/pep-0008/.


 def __eq__(self, other):
 if instance(other, myclass):
 return self == other.copy()
 return NotImplemented


This redefines the == operator, not the = operator.

It is not possible to redefine =.

One way could be to override assignment of a class attribute. But this 
won't be enough, I think.


Let me explain:

class MyContainer(object):
@property
def content(self):
return self._content
@content.setter
def content(self, new):
self._content = new.copy()

Then you can do:

a = MyClass()
b = MyContainer()
b.content = a
print b.content is a # should print False; untested...

But something like

a = MyClass()
b = a

will always lead to "b is a".


This communication is for informational purposes only. It is not
intended to be, nor should it be construed or used as, financial,
legal, tax or investment advice or an offer to sell, or a
solicitation of any offer to buy, an interest in any fund advised by
Ada Investment Management LP, the Investment advisor.


What?


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: fastest data structure for retrieving objects identified by (x, y) tuple?

2012-10-04 Thread Thomas Rachel

Am 04.10.2012 03:58 schrieb Steven D'Aprano:

alist = [[None]*2400 for i in range(2400)]
from random import randrange
for i in range(1000):
 x = randrange(2400)
 y = randrange(2400)
 adict[(x, y)] = "something"
 alist[x][y] = "something"



The actual sizes printed will depend on how sparse the matrices are, but
for the same above (approximately half full),


I wouldn't consider 1000 of 576 "half full"...


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: data attributes override method attributes?

2012-09-25 Thread Thomas Rachel

Am 25.09.2012 16:08 schrieb Peter Otten:

Jayden wrote:


In the Python Tutorial, Section 9.4, it is said that

"Data attributes override method attributes with the same name."


The tutorial is wrong here. That should be

"Instance attributes override class attributes with the same name."


I jump in here:

THere is one point to consider: if you work with descriptors, it makes a 
difference if they are "data descriptors" (define __set__ and/or 
__delete__) or "non-data descriptors" (define neither).


As http://docs.python.org/reference/datamodel.html#invoking-descriptors 
tells us, methods are non-data descriptors, so they can be overridden by 
instances.


OTOH, properties are data descriptors which cannot  be overridden by the 
instance.


So, to stick to the original example:

class TestDesc(object):
def a(self): pass
@property
def b(self): print "trying to get value - return None"; return None
@b.setter
def b(self, v): print "value", v, "ignored."
@b.deleter
def b(self): print "delete called and ignored"


and now

>>> t=TestDesc()
>>> t.a
>
>>> t.b
trying to get value - return None
>>> t.a=12
>>> t.b=12
value 12 ignored.
>>> t.a
12
>>> t.b
trying to get value - return None
>>> del t.a
>>> del t.b
delete called and ignored
>>> t.a
>
>>> t.b
trying to get value - return None


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: python file API

2012-09-25 Thread Thomas Rachel

Am 25.09.2012 09:28 schrieb Steven D'Aprano:


The whole concept is incomplete at one place: self.seek(10, 2) seeks
beyond EOF, potentially creating a sparse file. This is a thing you
cannot achieve.


On the contrary, since the pos attribute is just a wrapper around seek,
you can seek beyond EOF easily:

f.pos = None
f.pos += 10


Yes, from a syscall perspective, it is different: it is a tell() 
combined with a seek set instead of a relative seek. As someone 
mentionned, e. g. in the case of a streamer tape this might make a big 
difference.




But for anything but the most trivial usage, I would recommend sticking
to the seek method.


ACK. This should be kept as a fallback.



... or we need multiple attributes, one for each mode ...


Yes. That's what I would favourize: 3 attributes which each take a value 
to be passed to seek.



So all up, I'm -1 on trying to replace the tell/seek API, and -0 on
adding a second, redundant API.


ACK.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: python file API

2012-09-25 Thread Thomas Rachel

Am 25.09.2012 10:13 schrieb Dennis Lee Bieber:

Or some bit setting registers, like on ATxmega: OUT = 0x10 sets bit 7
and clears all others, OUTSET = 0x10 only sets bit 7, OUTTGL = 0x10
toggles it and OUTCLR = 0x10 clears it.


Umpfzg. s/bit 7/bit 4/.


I don't think I'd want to work with any device where 0x10 (0001
binary) modifies bit SEVEN. 0x40, OTOH, would fit my mental impression
of bit 7.


Of course. My fault.

It can as well be a bit mask, with OUTTGL = 0x11 toggling bit 4 and bit 
0. Very handy sometimes.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: For Counter Variable

2012-09-24 Thread Thomas Rachel

Am 25.09.2012 01:39 schrieb Dwight Hutto:


It's not the simpler solution I'm referring to, it's the fact that if
you're learning, then you should be able to design the built-in, not
just use it.


In some simpler cases you are right here. But the fact that you are able 
to design it doesn't necessarily mean that you should actually use your 
self-designed version.


But what you post suggests is important as well: if using the neat fancy 
built-in simplifications, you should always be aware what overhead they 
imply.


An example:

Let l be a big, big list.

for i in :
if i in l: 

This looks neat and simple and doesn't look as expensive as it really is.

If l is converted to a set beforehand, it nearly looks the same, but it 
is simpler.


So even if you use builtins, be aware what they do.



You don't always know all the built-ins, so the builtin is simpler,
but knowing how to code it yourself is the priority of learning to
code in a higher level language, which should be simpler to the user
of python.


When learning Python, it often happend me to re-inven the wheel. But as 
soon as I saw the presence of something I re-wrote, I skipped my 
re-written version and used the built-in.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: which a is used?

2012-09-24 Thread Thomas Rachel

Am 25.09.2012 07:22 schrieb Dwight Hutto:


No, not really. If you wanna talk shit, I can reflect that, and if you
wanna talk politely I can reflect that. I go t attacked first.,


But not in this thread.

Some people read only selectively and see only your verbal assaults, 
without noticing that they refer to.


If you was really insulted, you should answer to these insults in their 
thread and not in a different one.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: python file API

2012-09-24 Thread Thomas Rachel

Am 25.09.2012 00:37 schrieb Ian Kelly:

On Mon, Sep 24, 2012 at 4:14 PM, Chris Angelico  wrote:

file.pos = 42 # Okay, you're at position 42
file.pos -= 10 # That should put you at position 32
foo = file.pos # Presumably foo is the integer 32
file.pos -= 100 # What should this do?


Since ints are immutable, the language specifies that it should be the
equivalent of "file.pos = file.pos - 100", so it should set the file
pointer to 68 bytes before EOF.


But this is not a "real int", it has a special use. So I don't think it 
is absolutely required to behave like an int.


This reminds me of some special purpose registers in embedded 
programming, where bits can only be set by hardware and are cleared by 
the application by writing 1 to them.


Or some bit setting registers, like on ATxmega: OUT = 0x10 sets bit 7 
and clears all others, OUTSET = 0x10 only sets bit 7, OUTTGL = 0x10 
toggles it and OUTCLR = 0x10 clears it.


If this behaviour is documented properly enough, it is quite OK, IMHO.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: python file API

2012-09-24 Thread Thomas Rachel

Am 25.09.2012 04:28 schrieb Steven D'Aprano:


By the way, the implementation of this is probably trivial in Python 2.x.
Untested:

class MyFile(file):
 @property
 def pos(self):
 return self.tell()
 @pos.setter
 def pos(self, p):
 if p<  0:
 self.seek(p, 2)
 else:
 self.seek(p)

You could even use a magic sentinel to mean "see to EOF", say, None.

 if p is None:
 self.seek(0, 2)

although I don't know if I like that.


The whole concept is incomplete at one place: self.seek(10, 2) seeks 
beyond EOF, potentially creating a sparse file. This is a thing you 
cannot achieve.


But the idea is great. I'd suggest to have another property:

  [...]
  @pos.setter
  def pos(self, p):
  self.seek(p)
  @property
  def eofpos(self): # to be consistent
  return self.tell()
  @eofpos.setter
  def eofpos(self, p):
  self.seek(p, 2)

Another option could be a special descriptor which can be used as well 
for relative seeking:


class FilePositionDesc(object):
def __init__(self):
pass
def __get__(self, instance, owner):
return FilePosition(self)
def __set__(self, value):
self.seek(value)

class FilePosition(object):
def __init__(self, file):
self.file = file
def __iadd__(self, offset):
self.file.seek(offset, 1)
def __isub__(self, offset):
self.file.seek(-offset, 1)

class MyFile(file):
pos = FilePositionDesc()
[...]

Stop.

This could be handled with a property as well.

Besides, this breaks some other expectations to the pos. So let's 
introduce a 3rd property named relpos:


class FilePosition(object):
def __init__(self, file):
self.file = file
self.seekoffset = 0
def __iadd__(self, offset):
self.seekoffset += offset
def __isub__(self, offset):
self.seekoffset -= offset
def __int__(self):
return self.file.tell() + self.seekoffset

class MyFile(file):
  @property
  def relpos(self):
  return FilePosition(self) # from above
  @relpos.setter
  def relpos(self, ofs):
  try:
  o = ofs.seekoffset # is it a FilePosition?
  except AttributeError:
  self.seek(ofs, 1) # no, but ofs can be an int as well
  else:
  self.seek(o, 1) # yes, it is


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: which a is used?

2012-09-24 Thread Thomas Rachel

Am 25.09.2012 04:37 schrieb Dwight Hutto:

I honestly could not care less what you think about me, but don't use
that term. This isn't a boys' club and we don't need your hurt ego
driving people away from here.


OH. stirrin up shit and can't stand the smell.


Where did he so?


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: which a is used?

2012-09-24 Thread Thomas Rachel

Am 25.09.2012 03:47 schrieb Dwight Hutto:


But within a class this is could be defined as self.x within the
functions and changed, correct?


class a():
def __init__(self,a):
self.a = a

def f(self):
print self.a

def g(self):
self.a = 20
print self.a


a = a(1)
a.f()
a.g()


Yes - this is a different situation. Here, the "self" referred to is the 
same in all cases (the "a" from top level), and so self.a can be used 
consistently as well.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using dict as object

2012-09-19 Thread Thomas Rachel

Am 19.09.2012 12:24 schrieb Pierre Tardy:


One thing that is cooler with java-script than in python is that dictionaries 
and objects are the same thing. It allows browsing of complex hierarchical data 
syntactically easy.

For manipulating complex jsonable data, one will always prefer writing:
buildrequest.properties.myprop
rather than
brdict['properties']['myprop']


This is quite easy to achieve (but not so easy to understand):

class JsObject(dict):
def __init__(self, *args, **kwargs):
super(JsObject, self).__init__(*args, **kwargs)
self.__dict__ = self

(Google for JSObject; this is not my courtesy).

What does it do? Well, an object's attributes are stored in a dict. If I 
subclass dict, the resulting class can be used for this as well.


In this case, a subclass of a dict gets itself as its __dict__. What 
happens now is


d = JsObject()

d.a = 1
print d['a']

# This results in d.__dict__['a'] = 1.
# As d.__dict__ is d, this is equivalent to d['a'] = 1.

# Now the other way:

d['b'] = 42
print d.b

# here as well: d.b reads d.__dict__['b'], which is essentially d['b'].


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'indent'ing Python in windows bat

2012-09-19 Thread Thomas Rachel

Am 18.09.2012 15:03 schrieb David Smith:


I COULD break down each batch file and write dozens of mini python
scripts to be called. I already have a few, too. Efficiency? Speed is
bad, but these are bat files, after all. The cost of trying to work with
a multitude of small files is high, though, and I realized I had better
go to a mix.


In order to achieve this, it might be very useful to either have a 
module for each (bigger) part to be achieved which you can call with


python -m modulename arg1 arg2 arg3

and putting the Python code into modulename.py.

Or you have one big "interpreter" which works this way:

class Cmd(object):
"""
Command collector
"""
def __init__(self):
self.cmds = {}
def cmd(self, f):
# register a function
self.cmds[f.__name__] = f
return f
def main(self):
import sys
sys.exit(self.cmds[sys.argv[1]](*sys.argv[2:]))

cmd = Cmd()

@cmd.cmd
def cmd1(arg1, arg2):
do_stuff()
...
return 1 # error -> exit()

@cmd.cmd
def cmd2():
...

if __name__ == '__main__':
cmd.main()


This is suitable for many small things and can be used this way:

bat cmds
python -m thismodule cmd1 a b
other bat cmds
python -m thismodule cmd2
...

HTH,

Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Decorators not worth the effort

2012-09-18 Thread Thomas Rachel

Am 15.09.2012 16:18 schrieb 8 Dihedral:


The concept of decorators is just a mapping from a function


... or class ...

> to another function

... or any other object ...

> with the same name in python.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: using text file to get ip address from hostname

2012-09-17 Thread Thomas Rachel

Am 15.09.2012 18:20 schrieb Dan Katorza:


hello again friends,
thanks for everyone help on this.
i guess i figured it out in two ways.
the second one i prefer the most.

i will appreciate if someone can give me some tips.
thanks again

so...
-
First
-
#!/usr/bin/env python
#Get the IP Address


print("hello, please enter file name here>"),
import socket
for line in open(raw_input()):
 hostname = line.strip()
 print("IP address for {0} is 
{1}.".format(hostname,socket.gethostbyname(hostname)))


second

#!/usr/bin/env python
#Get the IP Address

import os

print("Hello, please enter file name here>"),
FILENAME = raw_input()
if os.path.isfile(FILENAME):
 print("\nFile Exist!")
 print("\nGetting ip from host name")
 print("\n")
 import socket
 for line in open (FILENAME):
 hostname = line.strip()
 print("IP address for {0} is 
{1}.".format(hostname,socket.gethostbyname(hostname)))
 else:
 print ("\nFinished the operation")
else:
 print ("\nFIle is missing or is not reasable"),
~


Comparing these, the first one wins if you catch and process exceptions. 
It is easier to ask for forgiveness than to get permission (EAFP, 
http://en.wikipedia.org/wiki/EAFP).


Bit I wonder that no one has mentionned that 
socket.gethostbyname(hostname) is quite old-age because it only returns 
IPv4 addresses (resp. only one of them).


OTOH, socket.getaddrinfo(hostname, 0, 0, socket.SOCK_STREAM) gives you a 
list of parameter tuples for connecting.


So which way you go above, you should change the respective lines to

for line in ...:
hostname = line.strip()
for target in socket.getaddrinfo(hostname, 0, socket.AF_UNSPEC,
socket.SOCK_STREAM):
print("IP address for {0} is {1}.".format(hostname,
target[4][0]))


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Decorators not worth the effort

2012-09-15 Thread Thomas Rachel

[Sorry, my Firefox destroyed the indent...

Am 14.09.2012 22:29 schrieb Terry Reedy:


In other words

def make_wrapper(func, param):
def wrapper(*args, **kwds):
for i in range(param):
func(*args, **kwds)
return wrapper

def f(x): print(x)
f = make_wrapper(f, 2)
f('simple')

# is simpler, at least for some people, than the following
# which does essentially the same thing.

def make_outer(param):
def make_inner(func):
def wrapper(*args, **kwds):
for i in range(param):
func(*args, **kwds)
return wrapper
return make_inner

@make_outer(2)
def f(x): print(x)
f('complex')


For this case, my mydeco.py which I use quite often contains a

def indirdeco(ind):
# Update both the outer as well as the inner wrapper.
# If we knew the inner one was to be updated with something
# from *a, **k, we could do it. But not this way...
@functools.wraps(ind)
def outer(*a, **k):
@functools.wraps(ind)
def inner(f):
return ind(f, *a, **k)
return inner
return outer

so I can do

@indirdeco
def make_wrapper(func, param):
@functools.wraps(func)
def wrapper(*args, **kwds):
for i in range(param):
func(*args, **kwds)
return wrapper

and then nevertheless

@make_wrapper(2)
def f(x): print(x)

BTW, I also have a "meta-decorator" for the other direction:

def wrapfunction(mighty):
"""Wrap a function taking (f, *a, **k) and replace it with a
function taking (f) and returning a function taking (*a, **k) which
calls our decorated function.
Other direction than indirdeco."""
@functools.wraps(mighty)
def wrapped_outer(inner):
@functools.wraps(inner)
def wrapped_inner(*a, **k):
return mighty(inner, *a, **k)
wrapped_inner.func = inner # keep the wrapped function
wrapped_inner.wrapper = mighty # and the replacement
return wrapped_inner
wrapped_outer.func = mighty # keep this as well
return wrapped_outer

With this, a

@wrapfunction
def twice(func, *a, **k):
return func(*a, **k), func(*a, **k)

can be used with

@twice
def f(x): print (x); return x

very nicely.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get os.py to use an ./ntpath.py instead of Lib/ntpath.py

2012-09-11 Thread Thomas Rachel

Am 11.09.2012 05:46 schrieb Steven D'Aprano:


Good for you. (Sorry, that comes across as more condescending than it is
intended as.) Monkey-patching often gets used for quick scripts and tiny
pieces of code because it works.

Just beware that if you extend that technique to larger bodies of code,
say when using a large framework, or multiple libraries, your experience
may not be quite so good. Especially if *they* are monkey-patching too,
as some very large frameworks sometimes do. (Or so I am lead to believe.)


This sonds like a good use case for a context manager, like the one in 
decimal.Context.get_manager().


First shot:

@contextlib.contextmanager
def changed_os_path(**k):
old = {}
try:
for i in k.items():
old[i] = getattr(os.path, i)
setattr(os.path, i, k[i])
yield None
finally:
for i in k.items():
setattr(os.path, i, old[i])

and so for your code you can use

print 'os.walk(\'goo\') with modified isdir()'
with changed_os_path(isdir=my_isdir):
for root, dirs, files in os.walk('goo'):
print root, dirs, files

so the change is only effective as long as you are in the relevant code 
part and is reverted as soon as you leave it.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: generators as decorators simple issue

2012-09-11 Thread Thomas Rachel

Am 12.09.2012 04:28 schrieb j.m.dagenh...@gmail.com:

I'm trying to call SetName on an object to prevent me from ever having to call 
it explictly again on that object. Best explained by example.


def setname(cls):
 '''this is the proposed generator to call SetName on the object'''
 try:
 cls.SetName(cls.__name__)
 finally:
 yield cls


class Trial:
 '''class to demonstrate with'''
 def SetName(self, name):
 print 1, 1

@setname
class Test(Trial):
 '''i want SetName to be called by using setname as a decorator'''
 def __init__(self):

 print 'Yay! or Invalid.'

if __name__ == '__main__':
 test = Test()


How can i fix this?


I am not sure what exactly you want to achieve, but I see 2 problems here:

1. Your setname operates on a class, but your SetName() is an instance 
function.


2. I don't really understand the try...finally yield stuff. As others 
already said, you probably just want to return. I don't see what a 
generator would be useful for here...


def setname(cls):
 '''this is the proposed generator to call SetName on the object'''
 try:
 cls.SetName(cls.__name__)
 finally:
 return cls

and

class Trial(object):
'''class to demonstrate with'''
@classmethod
def SetName(cls, name):
print 1, 1

should solve your problems.
--
http://mail.python.org/mailman/listinfo/python-list


Re: set and dict iteration

2012-09-08 Thread Thomas Rachel

Am 19.08.2012 00:14 schrieb MRAB:


Can someone who is more familiar with the cycle detector and cycle
breaker, help prove or disprove the above?


In simple terms, when you create an immutable object it can contain
only references to pre-existing objects, but in order to create a cycle
you need to make an object refer to another which is created later, so
it's not possible to create a cycle out of immutable objects.


Yes, but if I add a list in-between, I can create a refcycle:

a = []
b = (a,)
a.append(b)

So b is a tuple consisting of one list which in turn contains b.

It is not a direct cycle, but an indirect one.

Or would that be detected via the list?


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: On-topic: alternate Python implementations

2012-08-04 Thread Thomas Rachel

Am 04.08.2012 11:10 schrieb Stefan Behnel:


As long as you don't use any features of the Cython language, it's plain
Python. That makes it a Python compiler in my eyes.


Tell that the C++ guys. C++ is mainly a superset of C. But nevertheless, 
C and C++ are distinct languages and so are Python and Cython.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's wrong with this code?

2012-07-24 Thread Thomas Rachel

Am 24.07.2012 09:47 schrieb Ulrich Eckhardt:


[0] Note that in almost all cases, when referring to a tag, Python
implicitly operates on the object attached to it. One case (the only
one?) where it doesn't is the "del" statement.


The del and the =, concerning the left side.

But even those don't do that under all circumstances. Think about 
__setitem__, __setattr__, __set__, __delitem__, __delattr__, __delete__.



Thomas



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


Re: the meaning of r`.......`

2012-07-24 Thread Thomas Rachel

Am 23.07.2012 17:59 schrieb Steven D'Aprano:

>> Before you

get a language that uses full Unicode, you'll need to have fairly
generally available keyboards that have those keys.


Or at least keys or key combinations for the stuff you need, which might 
differ e. g. with the country you live in. There are countries which 
have keyboards with äöüß, others with èàéî, and so on.




Or sensible, easy to remember mnemonics for additional characters. Back
in 1984, Apple Macs made it trivial to enter useful non-ASCII characters
from the keyboard. E.g.:

Shift-4 gave $
Option-4 gave ¢
Option-c gave ©
Option-r gave ®


So what? If I type Shift-3 here, I get a § (U+00A7). And the ° (U+00B0) 
comes with Shift-^, the µ (U+00B5) with AltGr-M and the € sign with AltGr+E.



Dead-keys made accented characters easy too:

Option-u o gave ö
Option-u e gave ë



And if I had a useful OS here at work, I even could use the compose key 
to produce many other non-ASCII characters. To be able to create each 
and every of them is not needed in order to have support for them in a 
language, just the needed ones.


Useful editors use them as well, although you have not all of them on 
your keyboard.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's wrong with this code?

2012-07-24 Thread Thomas Rachel

Am 23.07.2012 16:50 schrieb Stone Li:

I'm totally confused by this code:

Code:

a = None
b = None
c = None
d = None
x = [[a,b],
  [c,d]]
e,f = x[1]
print e,f
c = 1
d = 2
print e,f
e = 1
f = 2
print c,d

Output:

None None
None None
1 2


I'm expecting the code as:

None None
1 2
1 2


What's wrong?


Your expectation :-)

With c = 1 and d = 2 you do not change the respective objects, but you 
assign other objects to the same names.


The old content is still contained in x[1].

If you would only modify these objects (not possible as ints are 
immutable), you would notice the changes here and there.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generator vs functools.partial?

2012-06-21 Thread Thomas Rachel

Am 21.06.2012 13:25 schrieb John O'Hagan:


But what about a generator?


Yes, but...


def some_func():
 arg = big_calculation()
 while 1:
 i = yield
 (do_something with arg and i)

some_gen = some_func()
some_gen.send(None)
for i in lots_of_items:
 some_gen.send(i)


rather

def some_func(it):
arg = big_calculation()
for i in it:
do_something(arg, i)

some_func(lots_of_items)


HTH,

Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is that safe to use ramdom.random() for key to encrypt?

2012-06-19 Thread Thomas Rachel

Am 18.06.2012 01:48 schrieb Paul Rubin:

Steven D'Aprano  writes:

/dev/urandom isn't actually cryptographically secure; it promises not to
block, even if it has insufficient entropy. But in your instance...


Correct. /dev/random is meant to be used for long-lasting
cryptographically-significant uses, such as keys. urandom is not.


They are both ill-advised if you're doing anything really serious.


Hm?


> In practice if enough entropy has been in the system to make a key with

/dev/random, then urandom should also be ok.


Right.


> Unfortunately the sensible

interface is missing: block until there's enough entropy, then generate
data cryptographically, folding in new entropy when it's available.


What am I missing? You exactly describe /dev/random's interface.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: post init call

2012-06-18 Thread Thomas Rachel

Am 18.06.2012 09:10 schrieb Prashant:

class Shape(object):
 def __init__(self, shapename):
 self.shapename = shapename
 def update(self):
 print "update"

class ColoredShape(Shape):
 def __init__(self, color):
 Shape.__init__(self, color)
 self.color = color
 print 1
 print 2
 print 3
 self.update()

User can sub-class 'Shape' and create custom shapes. How ever user must call 
'self.update()' as the last argument when ever he is sub-classing 'Shape'.
I would like to know if it's possible to call 'self.update()' automatically 
after the __init__ of sub-class is done?

Cheers


I would construct it this way:

class Shape(object):
def __init__(self, *args):
self.args = args
self.init()
self.update()
# or: if self.init(): self.update()
def init(self):
return False # don't call update
def update(self):
print "update"
@propery
def shapename(self): return self.args[0]

class ColoredShape(Shape):
 def init(self):
 print 1, 2, 3
 self.update()
 return True
 @property
 def color(self): return self.args[1]


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: python3 raw strings and \u escapes

2012-05-30 Thread Thomas Rachel

Am 30.05.2012 08:52 schrieb ru...@yahoo.com:


This breaks a lot of my code because in python 2
   re.split (ur'[\u3000]', u'A\u3000A') ==>  [u'A', u'A']
but in python 3 (the result of running 2to3),
   re.split (r'[\u3000]', 'A\u3000A' ) ==>  ['A\u3000A']

I can remove the "r" prefix from the regex string but then
if I have other regex backslash symbols in it, I have to
double all the other backslashes -- the very thing that
the r-prefix was invented to avoid.

Or I can leave the "r" prefix and replace something like
r'[ \u3000]' with r'[  ]'.  But that is confusing because
one can't distinguish between the space character and
the ideographic space character.  It also a problem if a
reader of the code doesn't have a font that can display
the character.

Was there a reason for dropping the lexical processing of
\u escapes in strings in python3 (other than to add another
annoyance in a long list of python3 annoyances?)


Probably it is more consequent. Alas, it makes the whole stuff 
incompatible to Py2.


But if you think about it: why allow for \u if \r, \n etc. are 
disallowed as well?




And is there no choice for me but to choose between the two
poor choices I mention above to deal with this problem?


There is a 3rd one: use   r'[ ' + '\u3000' + ']'. Not very nice to read, 
but should do the trick...



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-25 Thread Thomas Rachel

Am 24.04.2012 15:25 schrieb rusi:


Identity, sameness, equality and the verb to be are all about the same
concept(s) and their definitions are *intrinsically* circular; see
http://plato.stanford.edu/entries/identity/#2


Mybe in real life language. In programming and mathematics there are 
several forms of equality, where identity (≡) is stronger than equality (=).


Two objects can be equal (=) without being identical (≡), but not the 
other way.


As the ≡ is quite hard to type, programming languages tend to use other 
operators for this.


E.g., in C, you can have

int a;
int b;
a = 4;
b = 4;

Here a and b are equal, but not identical. One can be changed without 
changing the other.


With

int x;
int *a=&x, *b=&x;

*a and *b are identical, as they point to the same location.

*a = 4 results in *b becoming 4 as well.


In Python, you can have the situations described here as well.

You can have a list and bind it to 2 names, or you can take 2 lists and 
bind them to that name.


a = [3]
b = [3]

Here a == b is True, while a is b results in False.


Thomas




And the seeming simplicity of the circular definitions hide the actual
complexity of 'to be'
for python:  http://docs.python.org/reference/expressions.html#id26
(footnote 7)
for math/philosophy: 
http://www.math.harvard.edu/~mazur/preprints/when_is_one.pdf


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


Re: why () is () and [] is [] work in other way?

2012-04-24 Thread Thomas Rachel

Am 24.04.2012 08:02 schrieb rusi:

On Apr 23, 9:34 am, Steven D'Aprano  wrote:


"is" is never ill-defined. "is" always, without exception, returns True
if the two operands are the same object, and False if they are not. This
is literally the simplest operator in Python.


Circular definition: In case you did not notice, 'is' and 'are' are
(or is it is?) the same verb.


Steven's definition tries not to define the "verb" "is", but it defines 
the meanung of the *operator* 'is'.


He says that 'a is b' iff a and be are *the same objects*. We don't need 
to define the verb "to be", but the target of the definition is the 
entity "object" and its identity.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: python module

2012-04-16 Thread Thomas Rachel

Am 16.04.2012 12:23 schrieb Kiuhnm:

I'd like to share a module of mine with the Python community. I'd like
to encourage bug reports, suggestions, etc...
Where should I upload it to?

Kiuhnm


There are several ways to do this. One of them would be bitbucket.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: ordering with duck typing in 3.1

2012-04-07 Thread Thomas Rachel

Am 07.04.2012 14:23 schrieb andrew cooke:


class IntVar(object):

 def __init__(self, value=None):
 if value is not None: value = int(value)
 self.value = value

 def setter(self):
 def wrapper(stream_in, thunk):
 self.value = thunk()
 return self.value
 return wrapper

 def __int__(self):
 return self.value

 def __lt__(self, other):
 return self.value<  other

 def __eq__(self, other):
 return self.value == other

 def __hash__(self):
 return hash(self.value)



so what am i missing?


If I don't confuse things, I think you are missing a __gt__() in your 
IntVar() class.


This is because first, a '2 < three' is tried with 2.__lt__(three). As 
this fails due to the used types, it is reversed: 'three > 2' is 
equivalent. As your three doesn't have a __gt__(), three.__gt__(2) fails 
as well.



Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: No os.copy()? Why not?

2012-04-04 Thread Thomas Rachel

Am 03.04.2012 11:34 schrieb John Ladasky:

I use subprocess.call() for quite a few other things.

I just figured that I should use the tidier modules whenever I can.


Of course. I only wanted to point out that os.system() is an even worse 
approach. shutils.copy() is by far better, of course.

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


  1   2   3   >