accents in windows

2014-10-30 Thread C@rlos
i cant print any accent(á é í ó ú) or ñ in console when i use windows OS with 
python, the console showme an error or extrangers characters in some cases, i 
need help 

III Escuela Internacional de Invierno en la UCI del 17 al 28 de febrero del 
2014. Ver www.uci.cu

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


testfixtures 4.1.1 Released!

2014-10-30 Thread Chris Withers

Hi All,

I'm pleased to announce the release of testfixtures 4.1.1. This is a 
bugfix release that fixes the following:


- Fix bug that prevented logger propagation to be controlled by the
  log_capture decorator.

Thanks to John Kristensen for the fix.

It looks like I also forgot to send out the 4.1.0 release announcement, 
which was a bug and feature release containing the following:


- Fix compare() bug when dict instances with tuple keys were not equal.

- Allow logger propagation to be controlled by LogCapture.

- Enabled disabled loggers if a LogCapture is attached to them.

Thanks to Daniel Fortunov for the compare() fix.

The package is on PyPI and a full list of all the links to docs, issue 
trackers and the like can be found here:


http://www.simplistix.co.uk/software/python/testfixtures

Any questions, please do ask on the Testing in Python list or on the 
Simplistix open source mailing list...


cheers,

Chris

--
Simplistix - Content Management, Batch Processing & Python Consulting
   - http://www.simplistix.co.uk
--
https://mail.python.org/mailman/listinfo/python-list


Re: accents in windows

2014-10-30 Thread Chris Angelico
On Thu, Oct 30, 2014 at 11:03 AM, C@rlos  wrote:
> i cant print any accent(á é í ó ú) or ñ in console  when i use windows OS
> with python, the console showme an error or extrangers characters in some
> cases, i need help

What version of Python? What is your code page set to?

Windows and Unicode don't play very nicely together. You may find it
better to use Idle (which has a GUI for this kind of display), and you
will almost certainly find things easier on Linux.

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


Re: Python Style Question

2014-10-30 Thread Steven D'Aprano
Anton wrote:

> Let's say I have an incoming list of values *l*. Every element of *l* can
> be one of the following options: 
> 1) an integer value 
> 2) a string in form of '', e.g. '7'
> 3) a string with a json serialization of an integer value, e.g. '"7"'
> 4) something else that should be ignored
> 
> I need to transform this list into another list with values from options
> 1)-3) coerced to int. The code below should do this.

I don't particularly like either version. I prefer this:

def load_int(obj):
if isinstance(obj, int):
# Case 1), an int, e.g. 7
return obj
elif isinstance(obj, str):
# Case 2) and 3), a str or JSON serialised int.
# E.g. '7' or '"7"'.
try:
return int(obj)
except ValueError:
return int(json.loads(obj))
raise TypeError('require int or str, got %s' % type(obj).__name__)

load_int() covers the three cases you mention, and raises either ValueError
for malformed strings (e.g. 'x') or TypeError for things which aren't ints
(e.g. floats, dicts, etc.). Any other exception is probably a bug that
needs to be fixed.

Then, to cover case 4), ignoring everything else, you have a choice between
a procedural form:

values = []
for obj in l:
try:
values.append(load_int(obj))
except (ValueError, TypeError):
pass


or a functional form:

def tolerant_load_int(obj, default=None):
try:
return load_int(obj)
except (ValueError, TypeError):
return default

values = [n for n in map(tolerant_load_int, l) if n is not None]

# alternative to using map
values = [n for n in (tolerant_load_int(obj) for obj in l) if n is not None]



-- 
Steven

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


Has color "Green" changed from Python 33 to 34 ?

2014-10-30 Thread ast

Hi

I just updated this morning my Python from a 3.3rc to 3.4 
(Windows) and I noticed that the 'Green' color in tkinter 
GUI is not the same at all.


'Green' in 3.4 is very dark. I had to replace it with 'Lime' to
get back a nice 'Green'.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Has color "Green" changed from Python 33 to 34 ?

2014-10-30 Thread Peter Otten
ast wrote:

> I just updated this morning my Python from a 3.3rc to 3.4
> (Windows) and I noticed that the 'Green' color in tkinter
> GUI is not the same at all.
> 
> 'Green' in 3.4 is very dark. I had to replace it with 'Lime' to
> get back a nice 'Green'.

More likely the color is defined by tcl/tk rather than Python, and your 
Python installations use different versions of tcl. Searching for 'tcl/tk 
color definitions' finds  with the following 
statement

"""From Tcl/Tk 8.6 on, Tk uses Web colours instead of X11 ones, where they 
conflict.
"""

and according to 

 
"green" is indeed one of the affected colors.


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


Re: Python Style Question

2014-10-30 Thread MRAB

On 2014-10-30 11:10, Steven D'Aprano wrote:

Anton wrote:


Let's say I have an incoming list of values *l*. Every element of *l* can
be one of the following options:
1) an integer value
2) a string in form of '', e.g. '7'
3) a string with a json serialization of an integer value, e.g. '"7"'
4) something else that should be ignored

I need to transform this list into another list with values from options
1)-3) coerced to int. The code below should do this.


I don't particularly like either version. I prefer this:

def load_int(obj):
 if isinstance(obj, int):
 # Case 1), an int, e.g. 7
 return obj
 elif isinstance(obj, str):
 # Case 2) and 3), a str or JSON serialised int.
 # E.g. '7' or '"7"'.
 try:
 return int(obj)
 except ValueError:
 return int(json.loads(obj))
 raise TypeError('require int or str, got %s' % type(obj).__name__)


[snip]

How about:

int(str(obj).strip('"'))

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


Re: accents in windows

2014-10-30 Thread C@rlos
thanks U, but the real problem is:

i have a path C:\Users\yanet\Desktop\áaaéeeíiiióooúuuñnn 
this path is correct, áaaéeeíiiióooúuuñnn is the name of a directory
but when i try to use os.walk() usin this path, dont work, for os this path 
dont exist, i try every things but nothing works.

some help???


- Mensaje original -
De: "Chris Angelico" 
CC: [email protected]
Enviados: Jueves, 30 de Octubre 2014 4:42:49
Asunto: Re: accents in windows

On Thu, Oct 30, 2014 at 11:03 AM, C@rlos  wrote:
> i cant print any accent(á é í ó ú) or ñ in console  when i use windows OS
> with python, the console showme an error or extrangers characters in some
> cases, i need help

What version of Python? What is your code page set to?

Windows and Unicode don't play very nicely together. You may find it
better to use Idle (which has a GUI for this kind of display), and you
will almost certainly find things easier on Linux.

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

-- 
Conserva lo que tienes...Olvida lo que te duele...Lucha por lo que quieres... 
Valora lo que posees...Perdona a los que te hieren y disfruta a los que te 
aman. Nos pasamos la vida esperando que pase algo... y lo único que pasa es la 
vida. No entendemos el valor de los momentos, hasta que se han convertido en 
recuerdos. Por eso... Haz lo que quieras hacer, antes de que se convierta en lo 
que te "gustaría" haber hecho.. No hagas de tu vida un borrador, tal vez no 
tengas tiempo de pasarlo en limpio !! 

.C@rlos 

III Escuela Internacional de Invierno en la UCI del 17 al 28 de febrero del 
2014. Ver www.uci.cu
-- 
https://mail.python.org/mailman/listinfo/python-list


When using a decorator exceptions raised reference the decorator not the function

2014-10-30 Thread Néstor Boscán
Hi

I'm using Python 2.7 and I'm creating a class decorator that extract
information from exceptions for logging purposes.

Everytime an exception is raised from the original function and I extract
the origin of the exception with sys.exc_info() I get a reference to the
line in the decorator where the function is called, not the line of the
original function where the exception was raised.

Any ideas?

Regards,

Néstor
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: accents in windows

2014-10-30 Thread Peter Otten
C@rlos wrote:

> thanks U, but the real problem is:
> 
> i have a path C:\Users\yanet\Desktop\áaaéeeíiiióooúuuñnn
> this path is correct, áaaéeeíiiióooúuuñnn is the name of a directory
> but when i try to use os.walk() usin this path, dont work, for os this
> path dont exist, i try every things but nothing works.
> 
> some help???

"nothing works" is not a good problem description to get help to fix a bug.

Can you post a small script that demonstrates the problem? 

Run the script and post its output including the error message and the 
traceback. Don't retype the output, use copy-and-paste.

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


Re: When using a decorator exceptions raised reference the decorator not the function

2014-10-30 Thread Peter Otten
Néstor Boscán wrote:

> I'm using Python 2.7 and I'm creating a class decorator that extract
> information from exceptions for logging purposes.
> 
> Everytime an exception is raised from the original function and I extract
> the origin of the exception with sys.exc_info() I get a reference to the
> line in the decorator where the function is called, not the line of the
> original function where the exception was raised.
> 
> Any ideas?

Please show us the code, preferably as a small self-contained example. Thank 
you.

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


Re: When using a decorator exceptions raised reference the decorator not the function

2014-10-30 Thread Jean-Michel Pichavant
- Original Message -
> From: "Peter Otten" <[email protected]>
> To: [email protected]
> Sent: Thursday, 30 October, 2014 1:45:42 PM
> Subject: Re: When using a decorator exceptions raised reference the decorator 
> not the function
> 
> Néstor Boscán wrote:
> 
> > I'm using Python 2.7 and I'm creating a class decorator that
> > extract
> > information from exceptions for logging purposes.
> > 
> > Everytime an exception is raised from the original function and I
> > extract
> > the origin of the exception with sys.exc_info() I get a reference
> > to the
> > line in the decorator where the function is called, not the line of
> > the
> > original function where the exception was raised.
> > 
> > Any ideas?
> 
> Please show us the code, preferably as a small self-contained
> example. Thank
> you.

+1 show us your decorator.

if you did something like:

try:

except Exception, e:
  # do something
  raise e


Then replace "raise e" by a bare "raise"


JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Finding way around ABCs (was What for -- for? (was A bug?))

2014-10-30 Thread Rustom Mody
On Wednesday, October 29, 2014 11:49:27 AM UTC+5:30, Zachary Ware wrote:
> On Wed, Oct 29, 2014 at 1:11 AM, Rustom Mody wrote:
> > On Wednesday, October 29, 2014 11:10:06 AM UTC+5:30, Zachary Ware wrote:
> >> Of course, that's 3 (progressively shorter) loops to get the names of
> >> the ABCs of a class compared to 1 (fairly short in the first place)
> >> loop for a map of relationships to all available ABCs, but optimizing
> >> such a toy as this would just be an exercise in futility :)
> >
> > Not so.
> >
> > The charm of introspection is that the introspection
> > itself can be introspected.
> > For that to be convincing there needs to be a good combo
> > of clarity and succinctness.  In particular why not reduce
> > the two functions to one?
> >
> > def get_abc_names(cls):
> > return [abc.__name__ for abc in abcs if issubclass(cls,abc)]
> 
> Well, it depends on what you actually want, the spec has been a bit fuzzy ;)

Thanks for this much -- its helpful.
Regarding ABCs -- is there a central documentation for them:

"What exactly is a sequence or iterable or etc protocol?"

This information seems to be strewn all over the place but systematically.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Finding way around ABCs (was What for -- for? (was A bug?))

2014-10-30 Thread Ian Kelly
On Thu, Oct 30, 2014 at 11:01 AM, Rustom Mody  wrote:
> On Wednesday, October 29, 2014 11:49:27 AM UTC+5:30, Zachary Ware wrote:
>> On Wed, Oct 29, 2014 at 1:11 AM, Rustom Mody wrote:
>> > On Wednesday, October 29, 2014 11:10:06 AM UTC+5:30, Zachary Ware wrote:
>> >> Of course, that's 3 (progressively shorter) loops to get the names of
>> >> the ABCs of a class compared to 1 (fairly short in the first place)
>> >> loop for a map of relationships to all available ABCs, but optimizing
>> >> such a toy as this would just be an exercise in futility :)
>> >
>> > Not so.
>> >
>> > The charm of introspection is that the introspection
>> > itself can be introspected.
>> > For that to be convincing there needs to be a good combo
>> > of clarity and succinctness.  In particular why not reduce
>> > the two functions to one?
>> >
>> > def get_abc_names(cls):
>> > return [abc.__name__ for abc in abcs if issubclass(cls,abc)]
>>
>> Well, it depends on what you actually want, the spec has been a bit fuzzy ;)
>
> Thanks for this much -- its helpful.
> Regarding ABCs -- is there a central documentation for them:
>
> "What exactly is a sequence or iterable or etc protocol?"
>
> This information seems to be strewn all over the place but systematically.

Maybe the glossary?

https://docs.python.org/3/glossary.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Finding way around ABCs (was What for -- for? (was A bug?))

2014-10-30 Thread Ian Kelly
On Thu, Oct 30, 2014 at 11:09 AM, Ian Kelly  wrote:
> On Thu, Oct 30, 2014 at 11:01 AM, Rustom Mody  wrote:
>> On Wednesday, October 29, 2014 11:49:27 AM UTC+5:30, Zachary Ware wrote:
>>> On Wed, Oct 29, 2014 at 1:11 AM, Rustom Mody wrote:
>>> > On Wednesday, October 29, 2014 11:10:06 AM UTC+5:30, Zachary Ware wrote:
>>> >> Of course, that's 3 (progressively shorter) loops to get the names of
>>> >> the ABCs of a class compared to 1 (fairly short in the first place)
>>> >> loop for a map of relationships to all available ABCs, but optimizing
>>> >> such a toy as this would just be an exercise in futility :)
>>> >
>>> > Not so.
>>> >
>>> > The charm of introspection is that the introspection
>>> > itself can be introspected.
>>> > For that to be convincing there needs to be a good combo
>>> > of clarity and succinctness.  In particular why not reduce
>>> > the two functions to one?
>>> >
>>> > def get_abc_names(cls):
>>> > return [abc.__name__ for abc in abcs if issubclass(cls,abc)]
>>>
>>> Well, it depends on what you actually want, the spec has been a bit fuzzy ;)
>>
>> Thanks for this much -- its helpful.
>> Regarding ABCs -- is there a central documentation for them:
>>
>> "What exactly is a sequence or iterable or etc protocol?"
>>
>> This information seems to be strewn all over the place but systematically.
>
> Maybe the glossary?

Also the documentation for the collections.abc and numbers modules:

https://docs.python.org/3/library/collections.abc.html
https://docs.python.org/3/library/numbers.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Finding way around ABCs (was What for -- for? (was A bug?))

2014-10-30 Thread Rustom Mody
On Thursday, October 30, 2014 10:40:42 PM UTC+5:30, Ian wrote:
> On Thu, Oct 30, 2014 at 11:01 AM, Rustom Mody wrote:
> > On Wednesday, October 29, 2014 11:49:27 AM UTC+5:30, Zachary Ware wrote:
> >> On Wed, Oct 29, 2014 at 1:11 AM, Rustom Mody wrote:
> >> > On Wednesday, October 29, 2014 11:10:06 AM UTC+5:30, Zachary Ware wrote:
> >> >> Of course, that's 3 (progressively shorter) loops to get the names of
> >> >> the ABCs of a class compared to 1 (fairly short in the first place)
> >> >> loop for a map of relationships to all available ABCs, but optimizing
> >> >> such a toy as this would just be an exercise in futility :)
> >> >
> >> > Not so.
> >> >
> >> > The charm of introspection is that the introspection
> >> > itself can be introspected.
> >> > For that to be convincing there needs to be a good combo
> >> > of clarity and succinctness.  In particular why not reduce
> >> > the two functions to one?
> >> >
> >> > def get_abc_names(cls):
> >> > return [abc.__name__ for abc in abcs if issubclass(cls,abc)]
> >>
> >> Well, it depends on what you actually want, the spec has been a bit fuzzy 
> >> ;)
> >
> > Thanks for this much -- its helpful.
> > Regarding ABCs -- is there a central documentation for them:
> >
> > "What exactly is a sequence or iterable or etc protocol?"
> >
> > This information seems to be strewn all over the place but systematically.
> 
> Maybe the glossary?
> 
> https://docs.python.org/3/glossary.html

Ummm...

I was looking for something more reference-ish, ie
More prolix for ABCs
And not containing random bits of unconnected data like
- What is CPython
- What is EAFP

Maybe there's something in the bowels of the C(Python)-code?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What for -- for? (was A bug?)

2014-10-30 Thread Joshua Landau
On 29 October 2014 03:22, Rustom Mody  wrote:
> Yesterday I was trying to introduce python to some senior computer scientists.
>
> Tried showing a comprehension-based dir-walker vs a for-loop based one:
>
> def dw(p):
>if isfile(p):
>   return [p]
>else:
>   return [p] + [c for f in listdir(p) for c in dw(p+'/'+f)]
>
...
>
> Comment to me : "Well this is neat and compact, but it does not add
> anything fundamental (over usual index based for-loops)"
>
> I tried to say that 'for' over general sequences is quite different
> and significantly more powerful than C/Pascal for over indexes +
> explicit indexing.

If you really want to show the generality of iteration, I suggest you
start with iterators:

def walk(path):
yield path

if isdir(path):
for name in iterdir(path):
for file in walk(path + "/" + name):
yield file

This is fundementally inexpressable with indexes. It also lends itself
to expressing delegation (eg. "yield from walk(path + "/" + name)").
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What for -- for? (was A bug?)

2014-10-30 Thread Rustom Mody
On Thursday, October 30, 2014 10:53:13 PM UTC+5:30, Joshua Landau wrote:
> On 29 October 2014 03:22, Rustom Mody  wrote:
> > Yesterday I was trying to introduce python to some senior computer 
> > scientists.
> >
> > Tried showing a comprehension-based dir-walker vs a for-loop based one:
> >
> > def dw(p):
> >if isfile(p):
> >   return [p]
> >else:
> >   return [p] + [c for f in listdir(p) for c in dw(p+'/'+f)]
> >
> ...
> >
> > Comment to me : "Well this is neat and compact, but it does not add
> > anything fundamental (over usual index based for-loops)"
> >
> > I tried to say that 'for' over general sequences is quite different
> > and significantly more powerful than C/Pascal for over indexes +
> > explicit indexing.
> 
> If you really want to show the generality of iteration, I suggest you
> start with iterators:
> 
> def walk(path):
> yield path
> 
> if isdir(path):
> for name in iterdir(path):
> for file in walk(path + "/" + name):
> yield file

heh!
That was my next version -- almost word-for-word
[Not on that laptop now; will check later]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Has color "Green" changed from Python 33 to 34 ?

2014-10-30 Thread Terry Reedy

On 10/30/2014 8:20 AM, Peter Otten wrote:

ast wrote:


I just updated this morning my Python from a 3.3rc to 3.4
(Windows) and I noticed that the 'Green' color in tkinter
GUI is not the same at all.

'Green' in 3.4 is very dark. I had to replace it with 'Lime' to
get back a nice 'Green'.


More likely the color is defined by tcl/tk rather than Python, and your
Python installations use different versions of tcl.

> Searching for 'tcl/tk

color definitions' finds  with the following
statement

"""From Tcl/Tk 8.6 on, Tk uses Web colours instead of X11 ones, where they
conflict.
"""


3.4 switched from 8.5 to 8.6


and according to

"green" is indeed one of the affected colors.


--
Terry Jan Reedy

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


Re: accents in windows

2014-10-30 Thread Terry Reedy

On 10/30/2014 8:30 AM, C@rlos wrote:

thanks U, but the real problem is:

i have a path C:\Users\yanet\Desktop\áaaéeeíiiióooúuuñnn
this path is correct, áaaéeeíiiióooúuuñnn is the name of a directory
but when i try to use os.walk() usin this path, dont work, for os this

> path dont exist, i try every things but nothing works.


some help???


Using Python 3.4 should solve this problem.



- Mensaje original -
De: "Chris Angelico" 
CC: [email protected]
Enviados: Jueves, 30 de Octubre 2014 4:42:49
Asunto: Re: accents in windows

On Thu, Oct 30, 2014 at 11:03 AM, C@rlos  wrote:

i cant print any accent(á é í ó ú) or ñ in console  when i use windows OS
with python, the console showme an error or extrangers characters in some
cases, i need help


Using Idle and a font with accented chars should solve this problem.


What version of Python? What is your code page set to?

Windows and Unicode don't play very nicely together. You may find it
better to use Idle (which has a GUI for this kind of display), and you
will almost certainly find things easier on Linux.


--
Terry Jan Reedy


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


Re: When using a decorator exceptions raised reference the decorator not the function

2014-10-30 Thread Terry Reedy

On 10/30/2014 8:33 AM, Néstor Boscán wrote:


I'm using Python 2.7 and I'm creating a class decorator that extract
information from exceptions for logging purposes.

Everytime an exception is raised from the original function and I
extract the origin of the exception with sys.exc_info() I get a
reference to the line in the decorator where the function is called, not
the line of the original function where the exception was raised.


I expect that both lines should be in the traceback.  Post an example 
where you do not intercept the exception.


--
Terry Jan Reedy


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


pySerial works in miniterm but not in my app

2014-10-30 Thread Dario
Python 2.7.6 on Mint, pySerial 2.6

I'm trying to write a console app to control a certain device via a usb com 
port.

In miniterm (-p /dev/ttyUSB0 -e -b 19200), I can communicate correctly with 
this configuration:

--- Settings: /dev/ttyUSB0  19200,8,N,1
--- RTS: inactive  DTR: inactive  BREAK: inactive
--- CTS: inactive  DSR: inactive  RI: inactive  CD: inactive
--- software flow control: inactive
--- hardware flow control: inactive
--- data escaping: raw  linefeed: CR

sw o01 + <--- I send this
sw o01 + Command OK <--- device does what it should *and* I receive this


Now my code:


import serial

s = serial.serial_for_url(
'/dev/ttyUSB0',
19200,
bytesize = 8,
parity   = 'N',
stopbits = 1,
rtscts   = False,
dsrdtr   = False,
xonxoff  = False,
timeout  = 1 # tried without
)
s.close() # tried without
s.open()
s.write('sw o01 +\r')
s.flush() # tried without
s.close() # tried with a sleep before close


With this I don't receive anything (tried with readline etc, omitted for 
readability), and the device doesn't react. Also, if I connect again with 
miniterm and issue the command, I first receive a "wrong command" message, as 
if some garbage was actually sent by my app, then it works again.

Isn't my config equivalent to the one in miniterm? Anything missing?

Thanks

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


Classes

2014-10-30 Thread Seymore4Head
class pet: 
def set_age(self,age):
self.age=age
def get_age(self):
return self.age
pax=pet
pax.set_age(4)

Traceback (most recent call last):
  File "C:\Functions\test.py", line 18, in 
pax.set_age(4)
TypeError: set_age() missing 1 required positional argument: 'age'

I am trying to pass 4 as the age.  Obviously I am doing it wrong.

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


Re: Classes

2014-10-30 Thread Rob Gaddi
On Thu, 30 Oct 2014 16:16:51 -0400
Seymore4Head  wrote:

> class pet: 
> def set_age(self,age):
> self.age=age
> def get_age(self):
> return self.age
> pax=pet
> pax.set_age(4)
> 
> Traceback (most recent call last):
>   File "C:\Functions\test.py", line 18, in 
> pax.set_age(4)
> TypeError: set_age() missing 1 required positional argument: 'age'
> 
> I am trying to pass 4 as the age.  Obviously I am doing it wrong.
> 

The reason your call is missing the positional argument is that 4 is
being assigned to self, rather than to age, so there is no age.  This is
because you are trying to call a function of the class object, rather
than a function of an instance of the class.

pax=pet()

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


Re: Classes

2014-10-30 Thread sohcahtoa82
On Thursday, October 30, 2014 1:19:57 PM UTC-7, Seymore4Head wrote:
> class pet: 
> def set_age(self,age):
> self.age=age
> def get_age(self):
> return self.age
> pax=pet
> pax.set_age(4)
> 
> Traceback (most recent call last):
>   File "C:\Functions\test.py", line 18, in 
> pax.set_age(4)
> TypeError: set_age() missing 1 required positional argument: 'age'
> 
> I am trying to pass 4 as the age.  Obviously I am doing it wrong.

The line `pax=pet` doesn't create an instance of your pet class, it creates 
essentially a copy of the class definition.

You need `pax=pet()`

Or preferably, `pax = pet()`.  The spaces are optional, but they make it more 
readable.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Classes

2014-10-30 Thread Seymore4Head
On Thu, 30 Oct 2014 13:34:04 -0700, Rob Gaddi
 wrote:

>On Thu, 30 Oct 2014 16:16:51 -0400
>Seymore4Head  wrote:
>
>> class pet: 
>> def set_age(self,age):
>> self.age=age
>> def get_age(self):
>> return self.age
>> pax=pet
>> pax.set_age(4)
>> 
>> Traceback (most recent call last):
>>   File "C:\Functions\test.py", line 18, in 
>> pax.set_age(4)
>> TypeError: set_age() missing 1 required positional argument: 'age'
>> 
>> I am trying to pass 4 as the age.  Obviously I am doing it wrong.
>> 
>
>The reason your call is missing the positional argument is that 4 is
>being assigned to self, rather than to age, so there is no age.  This is
>because you are trying to call a function of the class object, rather
>than a function of an instance of the class.
>
>pax=pet()
Thanks
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Classes

2014-10-30 Thread Seymore4Head
On Thu, 30 Oct 2014 13:33:01 -0700 (PDT), [email protected] wrote:

>On Thursday, October 30, 2014 1:19:57 PM UTC-7, Seymore4Head wrote:
>> class pet: 
>> def set_age(self,age):
>> self.age=age
>> def get_age(self):
>> return self.age
>> pax=pet
>> pax.set_age(4)
>> 
>> Traceback (most recent call last):
>>   File "C:\Functions\test.py", line 18, in 
>> pax.set_age(4)
>> TypeError: set_age() missing 1 required positional argument: 'age'
>> 
>> I am trying to pass 4 as the age.  Obviously I am doing it wrong.
>
>The line `pax=pet` doesn't create an instance of your pet class, it creates 
>essentially a copy of the class definition.
>
>You need `pax=pet()`
>
>Or preferably, `pax = pet()`.  The spaces are optional, but they make it more 
>readable.

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


Re: Classes

2014-10-30 Thread Larry Hudson

On 10/30/2014 01:16 PM, Seymore4Head wrote:

class pet:
 def set_age(self,age):
 self.age=age
 def get_age(self):
 return self.age
pax=pet
pax.set_age(4)

Traceback (most recent call last):
   File "C:\Functions\test.py", line 18, in 
 pax.set_age(4)
TypeError: set_age() missing 1 required positional argument: 'age'

I am trying to pass 4 as the age.  Obviously I am doing it wrong.

You have already received the answer -- pax=pet should be pax=pet(), but I have a simple 
side-comment about style.  It is common Python convention to capitalize class names, IOW make 
this class Pet instead of class pet.  This is convention not a requirement, but it does help 
distinguish class names from ordinary variable names -- especially to others reading your code 
(as well as yourself a few days later).   ;-)


 -=- Larry -=-

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


Re: Classes

2014-10-30 Thread Seymore4Head
On Thu, 30 Oct 2014 14:28:19 -0700, Larry Hudson 
wrote:

>On 10/30/2014 01:16 PM, Seymore4Head wrote:
>> class pet:
>>  def set_age(self,age):
>>  self.age=age
>>  def get_age(self):
>>  return self.age
>> pax=pet
>> pax.set_age(4)
>>
>> Traceback (most recent call last):
>>File "C:\Functions\test.py", line 18, in 
>>  pax.set_age(4)
>> TypeError: set_age() missing 1 required positional argument: 'age'
>>
>> I am trying to pass 4 as the age.  Obviously I am doing it wrong.
>>
>You have already received the answer -- pax=pet should be pax=pet(), but I 
>have a simple 
>side-comment about style.  It is common Python convention to capitalize class 
>names, IOW make 
>this class Pet instead of class pet.  This is convention not a requirement, 
>but it does help 
>distinguish class names from ordinary variable names -- especially to others 
>reading your code 
>(as well as yourself a few days later).   ;-)
>
>  -=- Larry -=-

I try to take typing shortcuts and it bites me in the behind.
Good suggestion
Thanks
-- 
https://mail.python.org/mailman/listinfo/python-list


Saving a file "in the background" -- How?

2014-10-30 Thread Virgil Stokes
While running a python program I need to save some of the data that is 
being created. I would like to save the data to a file on a disk 
according to a periodical schedule  (e.g. every 10 minutes). Initially, 
the amount of data is small (< 1 MB) but after sometime the amount of 
data can be >10MB. If a problem occurs during data creation, then the 
user should be able to start over from the last successfully saved data.


For my particular application, no other file is being saved and the data 
should always replace (not be appended to) the previous data saved. It 
is important that  the data be saved without any obvious distraction to 
the user who is busy creating more data. That is, I would like to save 
the data "in the background".


What is a good method to perform this task using Python 2.7.8 on a Win32 
platform?

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


Re: When using a decorator exceptions raised reference the decorator not the function

2014-10-30 Thread Néstor Boscán
Thanks Terry

Yes both lines where in the traceback using tb_next I got what I needed.

Regards,

Néstor

On Thu, Oct 30, 2014 at 1:36 PM, Terry Reedy  wrote:

> On 10/30/2014 8:33 AM, Néstor Boscán wrote:
>
>  I'm using Python 2.7 and I'm creating a class decorator that extract
>> information from exceptions for logging purposes.
>>
>> Everytime an exception is raised from the original function and I
>> extract the origin of the exception with sys.exc_info() I get a
>> reference to the line in the decorator where the function is called, not
>> the line of the original function where the exception was raised.
>>
>
> I expect that both lines should be in the traceback.  Post an example
> where you do not intercept the exception.
>
> --
> Terry Jan Reedy
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Saving a file "in the background" -- How?

2014-10-30 Thread Joel Goldstick
On Thu, Oct 30, 2014 at 5:30 PM, Virgil Stokes  wrote:
> While running a python program I need to save some of the data that is being
> created. I would like to save the data to a file on a disk according to a
> periodical schedule  (e.g. every 10 minutes). Initially, the amount of data
> is small (< 1 MB) but after sometime the amount of data can be >10MB. If a
> problem occurs during data creation, then the user should be able to start
> over from the last successfully saved data.
>
> For my particular application, no other file is being saved and the data
> should always replace (not be appended to) the previous data saved. It is
> important that  the data be saved without any obvious distraction to the
> user who is busy creating more data. That is, I would like to save the data
> "in the background".
>
> What is a good method to perform this task using Python 2.7.8 on a Win32
> platform?
> --
> https://mail.python.org/mailman/listinfo/python-list

I've not tried this, but stackoverflow has a solution that looks like
it could work for you:
http://stackoverflow.com/questions/16214736/write-data-to-disk-in-python-as-a-background-process

-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python Style Question

2014-10-30 Thread Steven D'Aprano
MRAB wrote:

> On 2014-10-30 11:10, Steven D'Aprano wrote:
>> Anton wrote:
>>
>>> Let's say I have an incoming list of values *l*. Every element of *l*
>>> can be one of the following options:
>>> 1) an integer value
>>> 2) a string in form of '', e.g. '7'
>>> 3) a string with a json serialization of an integer value, e.g. '"7"'
>>> 4) something else that should be ignored
>>>
>>> I need to transform this list into another list with values from options
>>> 1)-3) coerced to int. The code below should do this.
>>
>> I don't particularly like either version. I prefer this:
>>
>> def load_int(obj):
>>  if isinstance(obj, int):
>>  # Case 1), an int, e.g. 7
>>  return obj
>>  elif isinstance(obj, str):
>>  # Case 2) and 3), a str or JSON serialised int.
>>  # E.g. '7' or '"7"'.
>>  try:
>>  return int(obj)
>>  except ValueError:
>>  return int(json.loads(obj))
>>  raise TypeError('require int or str, got %s' % type(obj).__name__)
>>
> [snip]
> 
> How about:
> 
> int(str(obj).strip('"'))

Absolutely not.

obj = '""1\n\n\n\n'  # not valid JSON
load_int(obj)
=> raises ValueError
int(str(obj).strip('"'))
=> wrongly returns 1


-- 
Steven

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


Re: problem with pefile

2014-10-30 Thread Cameron Simpson

On 29Oct2014 08:34, [email protected]  wrote:

OT: how can I hide my email in these posts?
Every time I try to send a post, google warns me that my email is visible and 
so I edit it out.


Why would you want to hide your email?

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


Re: Python Style Question

2014-10-30 Thread Roy Smith
In article <[email protected]>,
 Steven D'Aprano  wrote:

> Anton wrote:
> 
> > Let's say I have an incoming list of values *l*. Every element of *l* can
> > be one of the following options: 
> > 1) an integer value 
> > 2) a string in form of '', e.g. '7'
> > 3) a string with a json serialization of an integer value, e.g. '"7"'
> > 4) something else that should be ignored
> > 
> > I need to transform this list into another list with values from options
> > 1)-3) coerced to int. The code below should do this.
> 
> I don't particularly like either version. I prefer this:
> 
> def load_int(obj):
> if isinstance(obj, int):
> # Case 1), an int, e.g. 7
> return obj
> elif isinstance(obj, str):
> # Case 2) and 3), a str or JSON serialised int.
> # E.g. '7' or '"7"'.
> try:
> return int(obj)
> except ValueError:
> return int(json.loads(obj))
> raise TypeError('require int or str, got %s' % type(obj).__name__)

Depending on how strictly you're trying to do input validation, the 
int(json.loads(obj)) may not be what you want.  It allows well-formed 
json encoding floats, for example.

And, of course, since

>>> isinstance(True, int)
True

this code accepts booleans.  Oh, but wait, that's by design :-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: problem with pefile

2014-10-30 Thread Kiuhnm
On Friday, October 31, 2014 1:33:07 AM UTC+1, Cameron Simpson wrote:
> On 29Oct2014 08:34, gandalf23 wrote:
> >OT: how can I hide my email in these posts?
> >Every time I try to send a post, google warns me that my email is visible 
> >and so I edit it out.
> 
> Why would you want to hide your email?
> 
> Cameron Simpson 

I don't want more spam.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: problem with pefile

2014-10-30 Thread Cameron Simpson

On 30Oct2014 17:58, Kiuhnm  wrote:

On Friday, October 31, 2014 1:33:07 AM UTC+1, Cameron Simpson wrote:

On 29Oct2014 08:34, gandalf23 wrote:
>OT: how can I hide my email in these posts?
>Every time I try to send a post, google warns me that my email is visible and 
so I edit it out.

Why would you want to hide your email?


I don't want more spam.


You just need to filter your email better.
Most of us do not hide our addresses.

I manage to filter most of my spam by filing anything which gets past all my 
rules that catch mailing lists and which do not come from addresses in my 
"known" group into a probably-spam folder. It is surprisingly effective.


Basicly:
  - to me (me in to/cc/bcc), from a "known" author ==> inbox
  - matches one of my mailing list rules ==> appropriate-folder
  - otherwise ==> probably-spam

That is a simplification, but it is my basic scheme. Works fairly well.

Anyway, this is off-topic for python-list so I'll shut up now.

Cheers,
Cameron Simpson 

It must be public fact, because I'm not the only one who knows about it.
- Stefan A. Werner 
--
https://mail.python.org/mailman/listinfo/python-list


set environmental variable from python

2014-10-30 Thread Artur Bercik
I have to set environmental variable in my windows PC as follows:

variable name: GISBASE

value: C:\GRASS-64

Is it possible to set it from python?

import sys

sys.path.append("C:\\GRASS-64")

But how to give variable name? I have to set both the variable name and
value.

Thanks in the advance.

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


Re: Classes

2014-10-30 Thread sohcahtoa82
On Thursday, October 30, 2014 2:37:54 PM UTC-7, Seymore4Head wrote:
> On Thu, 30 Oct 2014 14:28:19 -0700, Larry Hudson 
> wrote:
> 
> >On 10/30/2014 01:16 PM, Seymore4Head wrote:
> >> class pet:
> >>  def set_age(self,age):
> >>  self.age=age
> >>  def get_age(self):
> >>  return self.age
> >> pax=pet
> >> pax.set_age(4)
> >>
> >> Traceback (most recent call last):
> >>File "C:\Functions\test.py", line 18, in 
> >>  pax.set_age(4)
> >> TypeError: set_age() missing 1 required positional argument: 'age'
> >>
> >> I am trying to pass 4 as the age.  Obviously I am doing it wrong.
> >>
> >You have already received the answer -- pax=pet should be pax=pet(), but I 
> >have a simple 
> >side-comment about style.  It is common Python convention to capitalize 
> >class names, IOW make 
> >this class Pet instead of class pet.  This is convention not a requirement, 
> >but it does help 
> >distinguish class names from ordinary variable names -- especially to others 
> >reading your code 
> >(as well as yourself a few days later).   ;-)
> >
> >  -=- Larry -=-
> 
> I try to take typing shortcuts and it bites me in the behind.
> Good suggestion
> Thanks

A shortcut is the fastest way to get somewhere you weren't going.

Python makes programming very easy (Compared to C/C++ and many other 
languages), but there are still a lot of shortcuts you can't make.
-- 
https://mail.python.org/mailman/listinfo/python-list


ANN: Antipathy v0.8

2014-10-30 Thread Ethan Furman
has just been made compatible with Python 3!  It runs on everything from 2.4 forward, haven't testing anything prior to 
that.


It is available for download at https://pypi.python.org//pypi/antipathy

---

Antipathy -- for those tired of ``os.path``
===

Tired of calling a function for every path manipulation you need to do?

Is:

>>> path, filename = os.path.split(some_name)
>>> basename, ext = os.path.splitext(filename)
>>> basename = basename + '_01'
>>> new_name = os.path.join(path, basename+ext)

wearing on your nerves?

In short, are you filled with antipathy [1] for os.path?

Then get antipathy and work with Path:

>>> some_name = Path('/home/ethan/source/my_file.txt')
>>> backups = Path('/home/ethan/backup/')
>>> print some_name.path
'/home/ethan/source/'
>>> print some_name.ext
'.txt'
>>> print some_name.exists()
True  # (well, if it happens to exist at this moment ;)
>>> backup = backups / some_name.filename + '_01' + some_name.ext
>>> print backup
'/home/ethan/backup/my_file_01.txt'
>>> some_name.copy(backup)

Because Path is a subclass of bytes/str/unicode, it can still be passed to other functions that expect a 
bytes/str/unicode object and work seamlessly [2].


[1] https://www.google.com/#q=antipathy

[2] in most cases -- there are a few places that do a `type` check instead of 
an `isinstance` check.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Saving a file "in the background" -- How?

2014-10-30 Thread Deepfriedice

Why not just call the save function as a separate thread?
threading.Thread(target=save, args=(data)).start()
--
https://mail.python.org/mailman/listinfo/python-list


Re: set environmental variable from python

2014-10-30 Thread Dave Angel

On 10/30/2014 09:22 PM, Artur Bercik wrote:

I have to set environmental variable in my windows PC as follows:

variable name: GISBASE

value: C:\GRASS-64

Is it possible to set it from python?


Which Python?  I'll have to assume 3.x



import sys

sys.path.append("C:\\GRASS-64")

But how to give variable name? I have to set both the variable name and
value.



sys.path has nothing to do with an environment variable of GISBASE.

Instead you could look up os.environ at:

  https://docs.python.org/3/library/os.html

Also see os.getenv and os.setenv.



Note that it's not necessarily supported.  But I believe it is for a 
standard build on Windows.


Next question is what you hope to achieve by setting such a variable. 
You do realize that it will vanish again when your python process ends? 
 So if you're just planning to use it in your own code, I'd recommend 
finding another method of saving the name & value.


The only value I can see is if you plan to create a subprocess from your 
Python code.


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


Re: Saving a file "in the background" -- How?

2014-10-30 Thread Terry Reedy

On 10/30/2014 6:21 PM, Joel Goldstick wrote:

On Thu, Oct 30, 2014 at 5:30 PM, Virgil Stokes  wrote:

While running a python program I need to save some of the data that is being
created. I would like to save the data to a file on a disk according to a
periodical schedule  (e.g. every 10 minutes). Initially, the amount of data
is small (< 1 MB) but after sometime the amount of data can be >10MB. If a
problem occurs during data creation, then the user should be able to start
over from the last successfully saved data.

For my particular application, no other file is being saved and the data
should always replace (not be appended to) the previous data saved. It is
important that  the data be saved without any obvious distraction to the
user who is busy creating more data. That is, I would like to save the data
"in the background".

What is a good method to perform this task using Python 2.7.8 on a Win32
platform?
--
https://mail.python.org/mailman/listinfo/python-list


I've not tried this, but stackoverflow has a solution that looks like
it could work for you:
http://stackoverflow.com/questions/16214736/write-data-to-disk-in-python-as-a-background-process


Python 3.4 should have an asyncio solution.


--
Terry Jan Reedy

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


Re: set environmental variable from python

2014-10-30 Thread Artur Bercik
Dear Dave Angel

Thanks for your answer.

I am using Python 2.7

I want to set it permanently.
I have to set several variables so it would be easier if I could set them
from Python.

Hearing the solution.

On Fri, Oct 31, 2014 at 10:50 AM, Dave Angel  wrote:

> On 10/30/2014 09:22 PM, Artur Bercik wrote:
>
>> I have to set environmental variable in my windows PC as follows:
>>
>> variable name: GISBASE
>>
>> value: C:\GRASS-64
>>
>> Is it possible to set it from python?
>>
>
> Which Python?  I'll have to assume 3.x
>
>
>> import sys
>>
>> sys.path.append("C:\\GRASS-64")
>>
>> But how to give variable name? I have to set both the variable name and
>> value.
>>
>>
> sys.path has nothing to do with an environment variable of GISBASE.
>
> Instead you could look up os.environ at:
>
>   https://docs.python.org/3/library/os.html
>
> Also see os.getenv and os.setenv.
>
>
>
> Note that it's not necessarily supported.  But I believe it is for a
> standard build on Windows.
>
> Next question is what you hope to achieve by setting such a variable. You
> do realize that it will vanish again when your python process ends?  So if
> you're just planning to use it in your own code, I'd recommend finding
> another method of saving the name & value.
>
> The only value I can see is if you plan to create a subprocess from your
> Python code.
>
> --
> DaveA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: set environmental variable from python

2014-10-30 Thread Zachary Ware
On Thursday, October 30, 2014, Artur Bercik  wrote:

> Dear Dave Angel
>
> Thanks for your answer.
>
> I am using Python 2.7
>
> I want to set it permanently.
> I have to set several variables so it would be easier if I could set them
> from Python.
>

Depending on how "permanently" you mean, about your only solutions would be
"os.system('setx <...>')" or manually manipulating the registry with the
_winreg module.

Hope this helps,
--
Zach


-- 
Sent from Gmail Mobile
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: set environmental variable from python

2014-10-30 Thread Rustom Mody
On Friday, October 31, 2014 8:01:08 AM UTC+5:30, Zachary Ware wrote:
> On Thursday, October 30, 2014, Artur Bercik  wrote:
> 
> Dear Dave Angel
> 
> 
> Thanks for your answer.
> 
> 
> I am using Python 2.7
> 
> 
> I want to set it permanently.
> I have to set several variables so it would be easier if I could set them 
> from Python.
> 
> 
> Depending on how "permanently" you mean, about your only solutions
> would be "os.system('setx <...>')" or manually manipulating the
> registry with the _winreg module.

Or dont do it from python but directly with regedit??

The question really is: Why do you wish to do this from within python?


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


Re: set environmental variable from python

2014-10-30 Thread Artur Bercik
could you please elaborate 'setx <...>'?


On Fri, Oct 31, 2014 at 11:30 AM, Zachary Ware <
[email protected]> wrote:

> On Thursday, October 30, 2014, Artur Bercik  wrote:
>
>> Dear Dave Angel
>>
>> Thanks for your answer.
>>
>> I am using Python 2.7
>>
>> I want to set it permanently.
>> I have to set several variables so it would be easier if I could set them
>> from Python.
>>
>
> Depending on how "permanently" you mean, about your only solutions would
> be "os.system('setx <...>')" or manually manipulating the registry with the
> _winreg module.
>
> Hope this helps,
> --
> Zach
>
>
> --
> Sent from Gmail Mobile
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: set environmental variable from python

2014-10-30 Thread Artur Bercik
I have to set several variables so it would be easier if I could set them
from Python.

On Fri, Oct 31, 2014 at 11:36 AM, Rustom Mody  wrote:

> On Friday, October 31, 2014 8:01:08 AM UTC+5:30, Zachary Ware wrote:
> > On Thursday, October 30, 2014, Artur Bercik  wrote:
> >
> > Dear Dave Angel
> >
> >
> > Thanks for your answer.
> >
> >
> > I am using Python 2.7
> >
> >
> > I want to set it permanently.
> > I have to set several variables so it would be easier if I could set
> them from Python.
> >
> >
> > Depending on how "permanently" you mean, about your only solutions
> > would be "os.system('setx <...>')" or manually manipulating the
> > registry with the _winreg module.
>
> Or dont do it from python but directly with regedit??
>
> The question really is: Why do you wish to do this from within python?
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: set environmental variable from python

2014-10-30 Thread Rustom Mody
On Friday, October 31, 2014 7:33:43 AM UTC+5:30, Artur Bercik wrote:
> Dear Dave Angel
> 
> 
> Thanks for your answer.
> 
> 
> I am using Python 2.7
> 
> 
> I want to set it permanently.
> I have to set several variables so it would be easier if I could set them 
> from Python.

regedit is scriptable
http://support.microsoft.com/kb/310516

[Be careful though! Follow the precautions like backing up the registry
before messing around]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: set environmental variable from python

2014-10-30 Thread Zachary Ware
On Thu, Oct 30, 2014 at 9:40 PM, Artur Bercik  wrote:
> could you please elaborate 'setx <...>'?

>From a Command Prompt, do 'help setx' for details on how to use setx.

Rustom's suggestion of using regedit is going to be far easier than
using _winreg (which probably shouldn't even be considered as an
option).  Using `os.system('setx ...')` is going to be the easiest way
to do things if you have to calculate the values of your variables,
but if you just have a bunch of values that you're going to have to
key in anyway, just use setx directly (or in a batch script).

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


Re: Python Style Question

2014-10-30 Thread Steven D'Aprano
Roy Smith wrote:

> In article <[email protected]>,
>  Steven D'Aprano  wrote:
> 
>> Anton wrote:
>> 
>> > Let's say I have an incoming list of values *l*. Every element of *l*
>> > can be one of the following options:
>> > 1) an integer value
>> > 2) a string in form of '', e.g. '7'
>> > 3) a string with a json serialization of an integer value, e.g. '"7"'
>> > 4) something else that should be ignored
>> > 
>> > I need to transform this list into another list with values from
>> > options 1)-3) coerced to int. The code below should do this.
>> 
>> I don't particularly like either version. I prefer this:
>> 
>> def load_int(obj):
>> if isinstance(obj, int):
>> # Case 1), an int, e.g. 7
>> return obj
>> elif isinstance(obj, str):
>> # Case 2) and 3), a str or JSON serialised int.
>> # E.g. '7' or '"7"'.
>> try:
>> return int(obj)
>> except ValueError:
>> return int(json.loads(obj))
>> raise TypeError('require int or str, got %s' % type(obj).__name__)
> 
> Depending on how strictly you're trying to do input validation, the
> int(json.loads(obj)) may not be what you want.  It allows well-formed
> json encoding floats, for example.

Really?

py> int(json.loads(json.dumps(23.5)))
23

Damn! You're right.

Back to Plan A:

elif isinstance(obj, str):
try:
return int(obj)
except ValueError:
if obj and obj.startswith('"') and obj.endswith('"'):
return int(obj[1:-1])
raise


But of course even the int() function itself may be a little more flexible
than we might want:

py> int('1')
1


So I guess the lessons are:

* before writing code, you need to decide what the code is meant to do;

* and that includes what input must be rejected, not just what input 
  must be accepted.


> And, of course, since
> 
 isinstance(True, int)
> True
> 
> this code accepts booleans.  Oh, but wait, that's by design :-)

Naturally :-)

If you wanted to avoid it, that's easy, add a clause:

if isinstance(obj, bool):
raise TypeError

at the start of the function.


-- 
Steven

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


Re: Python Style Question

2014-10-30 Thread Denis McMahon
On Fri, 31 Oct 2014 09:48:10 +1100, Steven D'Aprano wrote:

> MRAB wrote:

>> How about:
>> 
>> int(str(obj).strip('"'))
> 
> Absolutely not.
> 
> obj = '""1\n\n\n\n'  # not valid JSON load_int(obj)
> => raises ValueError int(str(obj).strip('"'))
> => wrongly returns 1

How about

#!/usr/bin/python

import re, json

l = [1, -1, 0, '+2', '2', '-2', '0', '"+3"', '"3"', '"-3"', '"0"', 
 json.dumps(-4), json.dumps(4), json.dumps(0), 
 'x', 'sqjklsqjk__', (5, 6), 
 7.7, -7.7, '8.8', '+8.8', '-8.8', '"9.9"', '"+9.9"', '"-9.9"']

patt1 = re.compile(r'^([-+]?\d+)$')
patt2 = re.compile(r'^"([-+]?\d+)"$')

def getTheInt(x):

if isinstance(x,int):
return x

if isinstance(x,str):
tmp = patt1.match(x)

if tmp:
return int(tmp.group(1))

tmp = patt2.match(x)

if tmp:
return int(tmp.group(1))

return None

a = []

for n in l:
a.append(getTheInt(n))

print a

# end of code

prints:

[1, -1, 0, 2, 2, -2, 0, 3, 3, -3, 0, -4, 4, 0, None, None, None, None, 
None, None, None, None, None, None, None]

I know re matching the strings may be overkill, but it may be the best 
way of checking that the string contains the expected character format to 
convert to an int.

-- 
Denis McMahon, [email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list