[Tutor] Directory not empty :: Fast mode

2005-05-16 Thread Jonas Melian
To knowing if a directory isn't empty, I use:

dir_example = "/usr/foo/"

if glob.glob(os.path.join(dir_example, "*")):
...


But, as it has to expand all files, i'm supposed that it's a little slow
to simply knowing if a directory is empty.

Any improvement?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] kernel serie

2005-05-19 Thread Jonas Melian
I want get the kernel serie, so 2.x only (2.6 or 2.4)

info_kernel = platform.release() # get the kernel version
info_kernel = '.'.join(info_kernel.split('.',2)[:2])

is there any way of get it in one line only?

Thanks in advance!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Comparing a string

2005-05-20 Thread Jonas Melian
I'm tryin compare a string with a value with style of pattern-matching.

string = 'i686'

if string == glob.glob(i?86):

This is fails because glob() is for listing files in a directory that
match a Unix ls-pattern

how make it?

Thanks!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Exceptions for checking root, files

2005-05-21 Thread Jonas Melian
Hi,

I never haven't worked with exceptions, and I'm a little confused.

In my programs I always build a function to check things as:

- The user that runned the script is root
- All the files and directories with whom I am going to work exist
- etc

else the program exits.

Does this checks can be runned from an exception?

P.S.: I did read http://www.python.org/doc/current/tut/node10.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Checking and showing all errors before of exit

2005-05-21 Thread Jonas Melian
Is there any way of checking all possible errors, show you all error
messages, and then exit.

If i use :: sys.exit("error message") :: it only shows this error
message before of exit.

Thanks in advance!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] looking for a pattern in a lot of files

2005-05-22 Thread Jonas Melian
I've to looking for a pattern ('locale for') in a lot of files
(/dir/*_[A-Z][A-Z])

it's goes ok

any improvement about this code?
how print the actual file?
could i add an exception? by if there aren't files


for line in fileinput.input(glob.glob(os.path.join
(dir_locales, "*_[A-Z][A-Z]"))):
if re.search("locale for", line):
print line
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Checking and showing all errors before of exit

2005-05-23 Thread Jonas Melian
Kent Johnson wrote:
> 
>>Is there any way of checking all possible errors, show you all error
>>messages, and then exit.
> 
> I don't understand your question. Can you give an example of what you would 
> like to do?
> 
The idea was check all exceptions before of exit. I made it :)

flag_error = False
for x in [dir_lo, dir_k, dir_x]:
try:
os.listdir(x)
except OSError, err_o:
flag_error = True
print "Error! %s: %r" % (err_o.strerror, err_o.filename)

if flag_error:
sys.exit()

Now, I have a dudes:

1) Is it necessary use .exit() with some value (as 1) for indicate that
has been an error?

2) With .listdir() the exception can checks if the directory exist, but
how check if there are files in that directory too?

Thanks in advance!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Sorting a directory

2005-05-24 Thread Jonas Melian
Hi all,

I have to working with the files lines in this directory:

:::
dir_locales = "/usr/share/i18n/locales/"

for line in fileinput.input(glob.glob(os.path.join\
(dir_locales, "*_[A-Z][A-Z]"))):
...

:::

The problem is that the directory otuput is:
aa_DJ
aa_ER
aa_ET
af_ZA
...

and i would sort this files by the 2 last letters, so:
aa_DJ
so_DJ
aa_ER
byn_ER
gez_ER
ti_ER
tig_ER
...

I have not foun a lot of info about sort

Thanks!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sorting a directory

2005-05-24 Thread Jonas Melian
Kent Johnson wrote:
>>and i would sort this files by the 2 last letters, so:
> 
> The sort() method of a mutable sequence is very powerful. Docs for it are 
> here:
> http://docs.python.org/lib/typesseq-mutable.html
> 
> The key= parameter of sort() allows you to provide a function which, given a 
> member of the sequence 
> being sorted, returns the sort key for that item. In your case you can define 
> a simple helper 
> function that returns the last two characters of a string:
> 
> def lastTwoChars(s):
>return s[-2:]
> 
> then sort like this:
> 
> dir_locales = "/usr/share/i18n/locales/"
> 
> files = glob.glob(os.path.join(dir_locales, "*_[A-Z][A-Z]"))
> files.sort(key=lastTwoChars)  # Note: NOT key=lastTwoChars()
> 
> for line in fileinput.input(files):
>...
> 

Thanks for this information.

I get:
::
files.sort(key=lastTwoChars)
TypeError: sort() takes no keyword arguments
::

Could it be by the Python version? I have Python 2.3.5
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Exceptions and its error messages

2005-05-25 Thread Jonas Melian
Hi,

How to know all the exceptions that there are? (i.e. OSError, ImportError)
And all error messages of each exception? (i.e. err_o.strerror,
err_o.filename)

Thanks in advance!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Data base in XML

2005-05-25 Thread Jonas Melian
Hi all,

I'm going to build a little data base in XML, with information about
localization for each country.

Then, I'm in dude of using xml.sax (built in python) or elementtree.
Which do you recommend to me?

And is it necessary build a DTD or Schema file?

Thanks in advance!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exceptions and its error messages

2005-05-25 Thread Jonas Melian
Kent Johnson wrote:
> Jonas Melian wrote:
>> How to know all the exceptions that there are? (i.e. OSError, ImportError)
> 
> Some library modules define their own exceptions such as socket.error so
> the above is not a complete
> list of exceptions defined in the standard distribution, just the ones
> that are built-in.
> 
> And of course third-party modules and your own code can define new
> exceptions so I would say it's
> not possible to know *all* the exceptions that there are.
> 
>> And all error messages of each exception? (i.e. err_o.strerror,
>> err_o.filename)
> 
> I don't understand this part of the question; what is err_o?
> 
I use i.e. with OSError exception the next error messages:
err_o.strerror, err_o.filename

::
try:
(os.listdir(x))
except OSError, err_o:
print "Error! %s: %r" % (err_o.strerror, err_o.filename)
::

But how knowing all error messages from some module?
Is there any way of knowing from python interactive line?

::
>>> import [module]
>>> help(exceptions)
::
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Data base in XML

2005-05-25 Thread Jonas Melian
Kent Johnson wrote:
>>I'm going to build a little data base in XML, with information about
>>localization for each country.
> 
> Why XML? You could use pickle or CSV or a real database...
> 

I have choosed XML because it's designed as a universal data exchange
format.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] UTF-8 by default

2005-05-28 Thread Jonas Melian
Hi all,

I'm working with an XML file, and i want to write in UTF-8
How write by default in UTF-8 instead of ASCII?

And I want not to use: print u'String'

Thanks in advance!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] UTF-8 by default

2005-05-29 Thread Jonas Melian
Kent Johnson wrote:
>>How write by default in UTF-8 instead of ASCII?
> 
> 
> How are you writing the file? What encoding is your data originally?
> 

For writing the XML file:
>>ElementTree.ElementTree(root).write("file.xml")

The source encoding is UTF-8 ( # -*- coding: utf-8 -*- )


But I also want that the program shows its messages in differents
languages, so it's necessary writting (>>>print 'Message') in UTF-8 by
default
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] os.spawnlp and os.spawnlpe

2005-05-29 Thread Jonas Melian
Hi,

which is the difference between os.spawnlp and os.spawnlpe?
With an example, please. I don't understand it.

Thanks!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Dudes with os.spawnlp

2005-05-29 Thread Jonas Melian
This code run 'X -configure' using $PATH for looking for its path

::
try:
#retcode = call("X" + " -configure", shell=True)  # 2.4

code_return = os.spawnlp(os.P_WAIT, "X", "X", "-configure")

if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
::

1) The OSError exception never is runned. I tested with an command that
doesnt exist (Xe)

2) For redirecting command output message, I think that I could to use:
os.spawnlp(os.P_WAIT, "X", "X", "-configure", "&>/dev/null")
But, is there any way more elegant in python?

3) That command built a file. Is it possible knows its name?

Thanks in advance!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dudes with os.spawnlp

2005-05-29 Thread Jonas Melian
Kent Johnson wrote:
> I don't know the answer to your question, but I wonder what you mean by 
> 'dudes'. You use that word a 
> lot and it never makes sense to me; I suspect you mistake its meaning.
> 
> Can you find another word?
> 

Oh sorry,
s/dudes/doubts
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] skip some directories

2005-05-30 Thread Jonas Melian
Hi,

I'm trying to working with some directories only

import os
dirName = "/usr/share/fonts/"
dirBase = ['misc','TTF','Type1','CID','100dpi','75dpi'] # directories to
skip

for root, dirs, files in os.walk(dirName):
for end in dirBase:
if root.endswith(end):
print 'skiped'
else:
print root

# but this fails, because always run 'print root'

#This is the only way:

if root.endswith('misc'):
print 'skiped'
else:
...

#but how pass all values in 'dirBase'?

Thanks in advance!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] skip some directories

2005-05-30 Thread Jonas Melian
Danny Yoo wrote:
>>I'm trying to working with some directories only
>>
>>import os
>>dirName = "/usr/share/fonts/"
>>dirBase = ['misc','TTF','Type1','CID','100dpi','75dpi'] # directories to
>>skip
>>
>>for root, dirs, files in os.walk(dirName):
>>for end in dirBase:
>>if root.endswith(end):
>>print 'skiped'
>>else:
>>print root
> 
> Let's break out the logic a little bit.  Would it be accurate to write
> this as:
> 
> ### Pseudocode ###
> for root, dirs, files in os.walk(dirName):
> if weShouldSkipThis(root):
> print "skipped"
> else:
> print root
> ##
> 
At the end, i found the way of make it:

dirBase = ['misc','TTF','Type1','CID','100dpi','75dpi','encodings', 'util']

for root, dirs, files in os.walk(dirName):
print dirs  # for checking all directories that i have at beginning
for name in dirs:
if name in dirBase:
dirs.remove(name)
print dirs  # compare if all directories in dirBase has been deleted

But it fails at delete some directories. Why?

['100dpi', '75dpi', 'TTF', 'Type1', 'arphicfonts', 'baekmuk-fonts',
'corefonts', 'cyrillic', 'default', 'encodings', 'freefont',
'kochi-substitute', 'local', 'misc', 'sharefonts', 'ukr', 'util']

['75dpi', 'Type1', 'arphicfonts', 'baekmuk-fonts', 'corefonts',
'cyrillic', 'default', 'freefont', 'kochi-substitute', 'local',
'sharefonts', 'ukr']

It did fail with '75dpi', and 'Type1'
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Net mask in hex. to dec.

2005-08-10 Thread Jonas Melian
Hi,

I get the netmask (mask="0xff00") from ifconfig in openbsd, and i 
would convert it to decimal (255.255.255.0)

I think that socket module doesn't help on this. So I'll have to make 
something as this for separate 'mask'

[s[i:i+2] for i in range(0, len(s), 2)]

then i could use int('', 16)

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] iterating in the same line

2005-08-13 Thread Jonas Melian
I would check 3 words at the starting of a line

s=['foo','bar','qwe']

if ln.startswith(s):   (this is bad)

what is the best way for making it?

if max(map(ln.startswith,s)):
or
reduce(lambda m,n:m or n, map(ln.startswith, s))

Thanks!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterating in the same line

2005-08-14 Thread Jonas Melian
I'm trying match the lines that starting with someone variable in 's'

These sentences:
if max(map(ln.startswith,s)):
reduce(lambda m,n:m or n, map(ln.startswith, s)):

were said me in #python for this proposal.


Alan G wrote:

> Sorry Jonas,
>
> I don't understand what you are trying to do at all.
> The subject line and your code snippets don't seem to match up.
>
>> Subject: [Tutor] iterating in the same line
>
>
>> I would check 3 words at the starting of a line
>>
>> s=['foo','bar','qwe']
>>
>> if ln.startswith(s):   (this is bad)
>
>
> Why is it bad -- other than it doesn't work!
> I think you mean something like
>
> for st in s:
>  if line.startswith(st):  do something
>
>> if max(map(ln.startswith,s)):
>
>
> But this does something completely different!
>
> This selects the 'biggest' line that starts with anything in s.
> then if the biggest line is not null does something?
>
>> reduce(lambda m,n:m or n, map(ln.startswith, s))
>
>
> And this does something different again.
> It uses map to create a list containg ln if ln startswith one of the 
> strings in s, then tries to reduce that list to one element(which it 
> already is!) by 'or'ing the elements.
>
> I can't even begin to guess from that what it is you are actually 
> trying to do.
>
> Can you give us more explanation and maybe some sample data?
>
> Alan G.
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] os.access vs os.path.isfile

2005-08-20 Thread Jonas Melian
os.access is better/fast that os.path.isfile for checking if exist a file?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Sorting by numbers

2005-08-21 Thread Jonas Melian
 From an input as this:

Standard timing 0: 85 Hz, 640x480
Standard timing 1: 85 Hz, 800x600
Standard timing 2: 85 Hz, 1024x768
Standard timing 3: 85 Hz, 1280x1024
Standard timing 4: 70 Hz, 1600x1200
Standard timing 5: 60 Hz, 1920x1440

I want to get columns 3 and 5 for sort them from mayor mo minor, so:

85 1280x1024
85 1024x768
85 800x600
85 640x480
70 1600x1200
60 1920x1440

--
modes = []
i = 3; j = 5  # Columns for get
for ln in data:
if ln.startswith('Standard'):
   modes.append(ln.split()[i:j+1:j+1-i-1])

 >>> modes
[['85', '640x480'], ['85', '800x600'], ['85', '1024x768'], ['85', 
'1280x1024'], ['70', '1600x1200'], ['60', '1920x1440']]
 >>> modes.sort()
 >>> modes
[['60', '1920x1440'], ['70', '1600x1200'], ['85', '1024x768'], ['85', 
'1280x1024'], ['85', '640x480'], ['85', '800x600']]
---

Well, it's from minor to mayor.
But the big problem is that Python does lexicographic sorting on tuples. 
So, how sort the second column by the numbers before of 'x'?

I'm supossing that there is to use split()

Any help? please
Thanks in advance!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sorting by numbers

2005-08-21 Thread Jonas Melian
Solution:
modes.sort(key=lambda item: int(item[1].split('x')[0])) # 2.4
modes.sort(lambda x, y: cmp(int(x[1].split('x')[0]), 
int(y[1].split('x')[0]))) #2.3.5

Jonas Melian wrote:

> From an input as this:
>
>Standard timing 0: 85 Hz, 640x480
>Standard timing 1: 85 Hz, 800x600
>Standard timing 2: 85 Hz, 1024x768
>Standard timing 3: 85 Hz, 1280x1024
>Standard timing 4: 70 Hz, 1600x1200
>Standard timing 5: 60 Hz, 1920x1440
>
>I want to get columns 3 and 5 for sort them from mayor mo minor, so:
>
>85 1280x1024
>85 1024x768
>85 800x600
>85 640x480
>70 1600x1200
>60 1920x1440
>
>--
>modes = []
>i = 3; j = 5  # Columns for get
>for ln in data:
>if ln.startswith('Standard'):
>   modes.append(ln.split()[i:j+1:j+1-i-1])
>
> >>> modes
>[['85', '640x480'], ['85', '800x600'], ['85', '1024x768'], ['85', 
>'1280x1024'], ['70', '1600x1200'], ['60', '1920x1440']]
> >>> modes.sort()
> >>> modes
>[['60', '1920x1440'], ['70', '1600x1200'], ['85', '1024x768'], ['85', 
>'1280x1024'], ['85', '640x480'], ['85', '800x600']]
>---
>
>Well, it's from minor to mayor.
>But the big problem is that Python does lexicographic sorting on tuples. 
>So, how sort the second column by the numbers before of 'x'?
>
>I'm supossing that there is to use split()
>
>Any help? please
>Thanks in advance!
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sorting by numbers

2005-08-21 Thread Jonas Melian
:( I get
 >>> modes
[['85', '640x480'], ['85', '800x600'], ['85', '1024x768'], ['85', 
'1280x1024'], ['70', '1600x1200'], ['60', '1920x1440']]
please help!

>Solution:
>modes.sort(key=lambda item: int(item[1].split('x')[0])) # 2.4
>modes.sort(lambda x, y: cmp(int(x[1].split('x')[0]), 
>int(y[1].split('x')[0]))) #2.3.5
>
>Jonas Melian wrote:
>
>  
>
>>From an input as this:
>>
>>Standard timing 0: 85 Hz, 640x480
>>Standard timing 1: 85 Hz, 800x600
>>Standard timing 2: 85 Hz, 1024x768
>>Standard timing 3: 85 Hz, 1280x1024
>>Standard timing 4: 70 Hz, 1600x1200
>>Standard timing 5: 60 Hz, 1920x1440
>>
>>I want to get columns 3 and 5 for sort them from mayor mo minor, so:
>>
>>85 1280x1024
>>85 1024x768
>>85 800x600
>>85 640x480
>>70 1600x1200
>>60 1920x1440
>>
>>--
>>modes = []
>>i = 3; j = 5  # Columns for get
>>for ln in data:
>>   if ln.startswith('Standard'):
>>  modes.append(ln.split()[i:j+1:j+1-i-1])
>>
>>
>>
>>>>>modes
>>>>>  
>>>>>
>>[['85', '640x480'], ['85', '800x600'], ['85', '1024x768'], ['85', 
>>'1280x1024'], ['70', '1600x1200'], ['60', '1920x1440']]
>>
>>
>>>>>modes.sort()
>>>>>modes
>>>>>  
>>>>>
>>[['60', '1920x1440'], ['70', '1600x1200'], ['85', '1024x768'], ['85', 
>>'1280x1024'], ['85', '640x480'], ['85', '800x600']]
>>---
>>
>>Well, it's from minor to mayor.
>>But the big problem is that Python does lexicographic sorting on tuples. 
>>So, how sort the second column by the numbers before of 'x'?
>>
>>I'm supossing that there is to use split()
>>
>>Any help? please
>>Thanks in advance!
>>
>>___
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
>> 
>>
>>
>>
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] no rsplit

2005-08-21 Thread Jonas Melian
v = "64x43x12"  -> '64x43', '12'

How split it by the las 'x'?

In 2.4 it could be used rsplit("x",1)

but i've 2.3.5

Is there another way of splitting a string from the end?
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] nested loops

2005-08-22 Thread Jonas Melian
Is there any way more efficient for run a nested loop?

--
for a in list_a:
for b in list_b:
if a == b: break


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Sort a list following the order of other list

2005-08-22 Thread Jonas Melian
best = [ [1024, 768], [800, 600], [640, 480] ]  (it's larger)

modes = [
(24, [1280, 1024]),
(24, [1024, 768]),
(24, [640, 480]),
(16, [1600, 1200]),
(16, [1280, 1024]),
(15, [320, 200]),
]

I want to create a list with ALL elements of 'modes', but following the 
order of list 'best' (if exist the number). At the end the rest of 
numbers in modes, are added too. And all this for each modes[0] (24, 16, 
15, ...)

For a simple list is easy:
a = [123, 45, 98, 2, 12];  b=[12, 35, 45, 2]
[y for y in b if y in a] + [x for x in a if x not in b]

Help please, that i'm going crazy
v 2.3.5

Thanks in advance
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Sort a Set

2005-08-23 Thread Jonas Melian
I get a list of repeated numbers  [24, 24, 24, 16, 16, 15, 15 ]
Is possible get it without repeated numbers, without using set()?

If I use set, then the list is unsorted and i cann't sorting it.

For get the values i use:

[x[0] for x in cardTmp]

or:

from itertools import imap
for i in imap(lambda x: x[0], cardTmp): print i

A idea it would be create a generator that will return elements one by 
one, and then it would be possible know if that element is in the new 
list. But generators are in 2.4


Python 2.3.5

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] iteration is overwriting the previous set value

2005-10-19 Thread Jonas Melian
def _pre_save(self):
for field in [self.name, self.native_name]:
if not field.istitle():
#print field.title()
field = field.title()

The change I try to do there (field = field.title()) is not being applied
I changed code so that you do 'self.foo = bar' statements for each 
attribute instead of using a loop and see if data gets saved, and it goes ok

I'm supposed that each iteration is overwriting the previous set value

how solve it? using a dict?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iteration is overwriting the previous set value

2005-10-20 Thread Jonas Melian
bob wrote:

> At 04:16 PM 10/19/2005, Jonas Melian wrote:
>
>> def _pre_save(self):
>> for field in [self.name, self.native_name]:
>> if not field.istitle():
>> #print field.title()
>> field = field.title()
>>
>> The change I try to do there (field = field.title()) is not being 
>> applied
>
>
> Yes it is. field (a local variable) is being replaced by 
> field.title(). You can confirm that by putting
> print field after the assignment.
>
> However I guess you want the change to apply to self.name and 
> self.native_name.
>
> Unfortunately you have a list containing the values of self.name and 
> self.native_name. Even if you modified the list elements (which 
> assignment to field does not do) self.name and self.native_name would 
> not be affected.
>
> Use getattr and setattr to access and assign the attributes, which you 
> specify by name.
>
> def _pre_save(self):
> for fieldname in ['name', 'native_name']:
> setattr(self, fieldname) = getattr(self, fieldname).title()
>
> [snip]
>
This fails:
SyntaxError: can't assign to function call

Danny Yoo's goes ok

You've the reason: there is no benefit in using "if not field.istitle():"

Thanks all

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iteration is overwriting the previous set value

2005-10-20 Thread Jonas Melian
Your code is correct. Thanks
I understood it. 'field' is a local variable inner that loop.

Respect to a related matter, a should be '42'

Danny Yoo wrote:

>On Thu, 20 Oct 2005, Jonas Melian wrote:
>
>  
>
>Hi Jonas,
>
>
>Do you understand why it isn't working?
>
>The issue is that 'field' is just another variable name, and the
>assignment just redirects that particular name to some other value.  So
>when we're doing:
>
>field = field.title()
>
>this statement has no effect on any other name, and in particular, doesn't
>do any mutation on 'self'.
>
>
>As a related matter:
>
>##
>  
>
>>>>a = "42"
>>>>b = a
>>>>b = "17"
>>>>
>>>>
>##
>
>What do you expect 'a' to be?
>
>
>
>  
>
>>I'm supposed that each iteration is overwriting the previous set value
>>
>>how solve it? using a dict?
>>
>>
>
>One way to do this is to use getattr() and setattr() so that we can do
>mutation on 'self'.  Your example above should work with:
>
>###
>def _pre_save(self):
>for fieldname in ['name', 'native_name']:
>value = getattr(self, fieldname)
>if not value.istitle():
>setattr(self, fieldname, value.title())
>###
>
>
>Hope this helps!
>
>
>  
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Time - sum/difference

2005-10-20 Thread Jonas Melian
I would get the local time of a country, using UTC (Universal Time 
Coordinated) and DST (Daylight SavingTime) of that country.

An example, utc time -02:30 and dst +1 :

country_utc = datetime.time(2,30)
isUTCNegative = True
dst = datetime.time(1,0)

Now I would the difference of both times.
-02:30 + 01:00 -> -01:30

Is possible get sum/difference of time values? How?

Thanks in advance
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Time - sum/difference

2005-10-21 Thread Jonas Melian
I wanted to sum two time values:

-02:30
+01:00
--
-01:30

I found one solution:
 >>> time_local = dt.time(2,30)
 >>> time_str = str(time_local).split(':')

Now I'll can get the first value, convert to integer and sum it.

Kent Johnson wrote:

>Jonas Melian wrote:
>  
>
>>I would get the local time of a country, using UTC (Universal Time 
>>Coordinated) and DST (Daylight SavingTime) of that country.
>>
>>An example, utc time -02:30 and dst +1 :
>>
>>country_utc = datetime.time(2,30)
>>isUTCNegative = True
>>dst = datetime.time(1,0)
>>
>>Now I would the difference of both times.
>>-02:30 + 01:00 -> -01:30
>>
>>Is possible get sum/difference of time values? How?
>>
>>
>
>I'm not exactly sure what you are looking for, but you can subtract 
>datetime.datetime instances. If you are trying to find the difference between 
>local time and utc this is one way:
>
> >>> import datetime as dt
> >>> dt.datetime.now()
>datetime.datetime(2005, 10, 20, 19, 41, 30, 393000)
> >>> dt.datetime.utcnow()
>datetime.datetime(2005, 10, 20, 23, 41, 52, 195000)
> >>> dt.datetime.utcnow()-dt.datetime.now()
>datetime.timedelta(0, 14400)
>
>though there is a race condition here that might give you an error of a 
>millisecond sometimes.
>
>Kent
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Time - sum/difference

2005-10-24 Thread Jonas Melian
Anyway, I found a library for working with time zones
http://pytz.sourceforge.net/

Hugo González Monteverde wrote:

> What I usually do is convert them all to UNIX epoch and then substact 
> the values in seconds:
>
> >>> import time
> >>> early = time.time()
> >>> sleep(5)
> >>> time.sleep(5)
> >>> late = time.time()
> >>> print late - early
> 5.7889997959
> >>>
>
>
> Jonas Melian wrote:
>
>> I would get the local time of a country, using UTC (Universal Time 
>> Coordinated) and DST (Daylight SavingTime) of that country.
>>
>> An example, utc time -02:30 and dst +1 :
>>
>> country_utc = datetime.time(2,30)
>> isUTCNegative = True
>> dst = datetime.time(1,0)
>>
>> Now I would the difference of both times.
>> -02:30 + 01:00 -> -01:30
>>
>> Is possible get sum/difference of time values? How?
>>
>> Thanks in advance
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor