Re: [Tutor] object attribute validation

2013-02-24 Thread neubyr
On Fri, Feb 22, 2013 at 10:31 PM, Steven D'Aprano wrote:

> On 23/02/13 10:50, neubyr wrote:
>
>> I would like to validate data attributes before the object is instantiated
>> or any changes thereafter. For example, following is a simple Person class
>> with name and age attributes. I would like to validate whether age is an
>> integer before it is added/changed in the object's dictionary. I have
>> taken
>> a simple integer validation example, but it could be something like
>> DateField validation or X509 certificate validation as well. Following is
>> my example code:
>>
>>
>> class Person(object):
>>def __init__(self,name,age):
>>  self.name = name
>>  self.age = age
>>
>>def get_age(self):
>>  return self._age
>>
>>def set_age(self,val):
>>  try:
>>int(val)
>>self._age = val
>>  except ValueError:
>>  raise Exception('Invalid value for age')
>>
>
> The setter is unnecessarily complicated. Just let the ValueError, or
> TypeError, or any other error, propagate:
>
> def set_age(self,val):
> self._age = int(val)
>
>
> This will allow the user to pass ages as strings, which I assume you want
> because that's what your code above does. instance.age = "6" will set the
> age to the int 6. If all you want to accept are ints, and nothing else:
>
>
> def set_age(self,val):
> if isinstance(val, int):
> self._age = val
> else:
> raise TypeError('expected an int, but got %r' % val)
>
>
>
>
> def del_age(self):
>>  del self._age
>>
>>age = property(get_age,set_age,del_**age)
>>
>
>
> In general, you would leave out the property deleter. I find that in
> general if you're validating attributes, you want them to be present and
> valid, so deleting should be an error.
>
>
> --
> Steven
>
>

Thank you for your comments Steven.

Yes, I think I should remove property deleter in this case.

I would like to use this Person class in another class. For example, if
Person class is 'model' in a small MVC-style web application, then where
should I place my validation. A view form will be passing parameters to a
controller which will create and write Person objects/models. Should the
validation be in place at all three levels?

I am inclined towards adding integer validation in views, but I am not sure
where should I add it in a controller class. Also, it's easy to add integer
validation in view form (javascript), but what if I have a more complex
format - X509 certificate or  some other file-type related validation? Is
it OK to validate them only in property setter methods?


-- N
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to change the char in string for Python

2013-02-24 Thread Jos Kerc
On Sun, Feb 24, 2013 at 2:26 PM, Sudo Nohup  wrote:

> Thanks very much!!
>
> I learnt a lot from you kind reply. Not only is it about the question
> itself, but also about how to ask a question in a mailing list.(Sorry that
> it is the first time for me to ask questions in a mailing list).
>
> The question comes from a riddle of the PythonChallenge website(
> http://www.pythonchallenge.com/pc/def/map.html).
>
> Now I write the code as the following,
>
> mystring = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq
> ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm
> jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
> temp = [ chr ( (ord(char)-ord('a')+2)%26 +ord('a'))  if
> (ord(char)>=ord('a') and ord(char)<=ord('z')) else char  for char in
> mystring ]
> result = "".join(temp)
> print result
>
> OR
>
> mystring = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq
> ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm
> jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
> result = []
> for char in mystring:
> if(ord(char)>=ord('a') and ord(char)<=ord('z')):
> char = chr ( (ord(char)-ord('a')+2)%26 +ord('a'))
> result.append(char)
> result = "".join(result)
> print result
>
> Thanks,
> James
>
>
>
>
Hi James,

for this riddle, look for the translate() method.


Have fun nwith the challenges.

Jos
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to change the char in string for Python

2013-02-24 Thread Sudo Nohup
Thanks very much!!

I learnt a lot from you kind reply. Not only is it about the question
itself, but also about how to ask a question in a mailing list.(Sorry that
it is the first time for me to ask questions in a mailing list).

The question comes from a riddle of the PythonChallenge website(
http://www.pythonchallenge.com/pc/def/map.html).

Now I write the code as the following,

mystring = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc
dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm
jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
temp = [ chr ( (ord(char)-ord('a')+2)%26 +ord('a'))  if
(ord(char)>=ord('a') and ord(char)<=ord('z')) else char  for char in
mystring ]
result = "".join(temp)
print result

OR

mystring = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc
dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm
jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
result = []
for char in mystring:
if(ord(char)>=ord('a') and ord(char)<=ord('z')):
char = chr ( (ord(char)-ord('a')+2)%26 +ord('a'))
result.append(char)
result = "".join(result)
print result

Thanks,
James


On Sun, Feb 24, 2013 at 8:40 PM, Dave Angel  wrote:

> Both your later remarks are top-posted, ruining the sequence of who posted
> what.
>
>
> On 02/24/2013 06:57 AM, Sudo Nohup wrote:
>
>> Thanks for your help.
>>
>> I just found a webpage used for me:
>> http://stackoverflow.com/**questions/10017147/python-**
>> replace-characters-in-string
>>
>> That page provides some other solutions. Thanks!
>>
>> On Sun, Feb 24, 2013 at 7:47 PM, Asokan Pichai 
>> **wrote:
>>
>>  On Feb 24, 2013 4:27 PM, "Sudo Nohup"  wrote:
>>>

 Dear all,

 I want to change the value of a char in a string for Python. However, It

>>> seems that "=" does not work.
>>>
>>
> assignment works fine, when it's really assignment.  But it doesn't work
> inside an expression, and you cannot change an immutable object in place.
>
>
>
 Could you help me? Thanks!

 str = "abcd"
 result = [char = 'a' for char in str if char == 'c']

>>>
> In a list comprehension, the if expression is used to skip items from the
> sequence.  So the above form, modified, might be used to remove selected
> characters from the string.
>
> By the way, since 'str' is a builtin, it's a bad practice to take it over
> for your own use.  For example, what if you subsequently needed to convert
> an int to a string?
>
>
>

 OR:

 str = 'abcd'
 for char in str:
  if char == 'a':
 char = 'c'

>>>
> You create a new object, and bind it to char, but then you don't do
> anything with it.
>
>
>

 OR:

 str = 'abcd'
 for i in range(len(str)):
  if str[i] == 'a':
 str[i] = 'c'

 (
 Traceback (most recent call last):
File "", line 3, in 
 TypeError: 'str' object does not support item assignment
 )

>>>
> A string object is immutable, so that you cannot use assignment to replace
> portions of it.
>
>
>
>>> Look up string replace function.
>>>
>>>
>>
> That of course is the simplest answer to the problem as originally given.
>
> (Here is where your amendment to the problem should have been given,
> rather than top-posting it.)
>
> But you now say you're planning to replace all the characters in the
> string, according to a formula.
>
> What yo should have specified in the first place is what version of Python
> you're using.  I'll assume 2.7
>
> This amended problem would lend itself nicely to translate(), and the link
> you posted does mention that.
>
> But there are several other approaches, similar to the ones you already
> tried, and sometimes one of them is more interesting or useful.
>
> For example, a list comprehension very close to what you tried would work
> fine (untested):
>
> temp = [ chr( ord(char) + 2 ) for char in mystring]
> result = "".join(temp)
>
> Likewise a loop:
>
> result = []
> for char in mystring:
> char = chr ( ord(char) + 2
> result.append(char)
> result = "".join(result)
>
>
> --
> DaveA
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to change the char in string for Python

2013-02-24 Thread Dave Angel
Both your later remarks are top-posted, ruining the sequence of who 
posted what.


On 02/24/2013 06:57 AM, Sudo Nohup wrote:

Thanks for your help.

I just found a webpage used for me:
http://stackoverflow.com/questions/10017147/python-replace-characters-in-string

That page provides some other solutions. Thanks!

On Sun, Feb 24, 2013 at 7:47 PM, Asokan Pichai wrote:


On Feb 24, 2013 4:27 PM, "Sudo Nohup"  wrote:


Dear all,

I want to change the value of a char in a string for Python. However, It

seems that "=" does not work.


assignment works fine, when it's really assignment.  But it doesn't work 
inside an expression, and you cannot change an immutable object in place.




Could you help me? Thanks!

str = "abcd"
result = [char = 'a' for char in str if char == 'c']


In a list comprehension, the if expression is used to skip items from 
the sequence.  So the above form, modified, might be used to remove 
selected characters from the string.


By the way, since 'str' is a builtin, it's a bad practice to take it 
over for your own use.  For example, what if you subsequently needed to 
convert an int to a string?





OR:

str = 'abcd'
for char in str:
 if char == 'a':
char = 'c'


You create a new object, and bind it to char, but then you don't do 
anything with it.





OR:

str = 'abcd'
for i in range(len(str)):
 if str[i] == 'a':
str[i] = 'c'

(
Traceback (most recent call last):
   File "", line 3, in 
TypeError: 'str' object does not support item assignment
)


A string object is immutable, so that you cannot use assignment to 
replace portions of it.




Look up string replace function.





That of course is the simplest answer to the problem as originally given.

(Here is where your amendment to the problem should have been given, 
rather than top-posting it.)


But you now say you're planning to replace all the characters in the 
string, according to a formula.


What yo should have specified in the first place is what version of 
Python you're using.  I'll assume 2.7


This amended problem would lend itself nicely to translate(), and the 
link you posted does mention that.


But there are several other approaches, similar to the ones you already 
tried, and sometimes one of them is more interesting or useful.


For example, a list comprehension very close to what you tried would 
work fine (untested):


temp = [ chr( ord(char) + 2 ) for char in mystring]
result = "".join(temp)

Likewise a loop:

result = []
for char in mystring:
char = chr ( ord(char) + 2
result.append(char)
result = "".join(result)


--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to change the char in string for Python

2013-02-24 Thread Steven D'Aprano

On 24/02/13 22:42, Sudo Nohup wrote:

Actually, I would like to substitute all the chars in a string with its
ascii adding 2, for cracking the naive "Caesar cipher".



A shameless plug:

https://pypi.python.org/pypi/obfuscate



--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to change the char in string for Python

2013-02-24 Thread Steven D'Aprano

On 24/02/13 21:56, Sudo Nohup wrote:

Dear all,

I want to change the value of a char in a string for Python. However, It
seems that "=" does not work.



Strings are immutable, which means that you cannot modify them in place. You 
can only create a new string with the characters you want.

If you want to change one letter, the simplest way is with string slicing:

s = "Hello world!"
t = s[:6] + "W" + s[7:]
print t
=> prints "Hello World!"


If you want to change many letters, the best way is to create a new list of the 
characters, and then join them:

s = "Hello"
chars = [chr(ord(c) + 13) for c in s]
t = ''.join(chars)
print t
=> prints 'Uryy|'



Best still is to use the string methods, if you can, such as str.upper(), 
str.replace(), etc.

http://docs.python.org/2/tutorial/introduction.html#strings

http://docs.python.org/2/library/stdtypes.html#string-methods



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to change the char in string for Python

2013-02-24 Thread Sudo Nohup
Thanks for your help.

I just found a webpage used for me:
http://stackoverflow.com/questions/10017147/python-replace-characters-in-string

That page provides some other solutions. Thanks!

On Sun, Feb 24, 2013 at 7:47 PM, Asokan Pichai wrote:

> On Feb 24, 2013 4:27 PM, "Sudo Nohup"  wrote:
> >
> > Dear all,
> >
> > I want to change the value of a char in a string for Python. However, It
> seems that "=" does not work.
> >
> > Could you help me? Thanks!
> >
> > str = "abcd"
> > result = [char = 'a' for char in str if char == 'c']
> >
> >
> > OR:
> >
> > str = 'abcd'
> > for char in str:
> > if char == 'a':
> >char = 'c'
> >
> >
> > OR:
> >
> > str = 'abcd'
> > for i in range(len(str)):
> > if str[i] == 'a':
> >str[i] = 'c'
> >
> > (
> > Traceback (most recent call last):
> >   File "", line 3, in 
> > TypeError: 'str' object does not support item assignment
> > )
>
> Look up string replace function.
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to change the char in string for Python

2013-02-24 Thread Asokan Pichai
On Feb 24, 2013 4:27 PM, "Sudo Nohup"  wrote:
>
> Dear all,
>
> I want to change the value of a char in a string for Python. However, It
seems that "=" does not work.
>
> Could you help me? Thanks!
>
> str = "abcd"
> result = [char = 'a' for char in str if char == 'c']
>
>
> OR:
>
> str = 'abcd'
> for char in str:
> if char == 'a':
>char = 'c'
>
>
> OR:
>
> str = 'abcd'
> for i in range(len(str)):
> if str[i] == 'a':
>str[i] = 'c'
>
> (
> Traceback (most recent call last):
>   File "", line 3, in 
> TypeError: 'str' object does not support item assignment
> )

Look up string replace function.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to change the char in string for Python

2013-02-24 Thread Sudo Nohup
Actually, I would like to substitute all the chars in a string with its
ascii adding 2, for cracking the naive "Caesar cipher".

So, there is a list of chars to be replaced.

If I use "replace" function, I have to replace them one by one.

Thanks all the same.

On Sun, Feb 24, 2013 at 7:32 PM, Marco Mistroni  wrote:

> You can use replace instead?
>  On 24 Feb 2013 10:59, "Sudo Nohup"  wrote:
>
>>  Dear all,
>>
>> I want to change the value of a char in a string for Python. However, It
>> seems that "=" does not work.
>>
>> Could you help me? Thanks!
>>
>> str = "abcd"
>> result = [char = 'a' for char in str if char == 'c']
>>
>>
>> OR:
>>
>> str = 'abcd'
>> for char in str:
>> if char == 'a':
>>char = 'c'
>>
>>
>> OR:
>>
>> str = 'abcd'
>> for i in range(len(str)):
>> if str[i] == 'a':
>>str[i] = 'c'
>>
>> (
>> Traceback (most recent call last):
>>   File "", line 3, in 
>>  TypeError: 'str' object does not support item assignment
>> )
>>
>>
>> James
>>
>>
>>
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to change the char in string for Python

2013-02-24 Thread Sudo Nohup
Dear all,

I want to change the value of a char in a string for Python. However, It
seems that "=" does not work.

Could you help me? Thanks!

str = "abcd"
result = [char = 'a' for char in str if char == 'c']


OR:

str = 'abcd'
for char in str:
if char == 'a':
   char = 'c'


OR:

str = 'abcd'
for i in range(len(str)):
if str[i] == 'a':
   str[i] = 'c'

(
Traceback (most recent call last):
  File "", line 3, in 
TypeError: 'str' object does not support item assignment
)


James
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor