[Tutor] string immutability

2011-10-24 Thread Johan Martinez
Hi,

I am struggling to understand Python string immutability. I am able to
modify Python string object after initializing/assigning it a value. So how
does immutability work? I am not following it. Sorry for really stupid
question. Any help?



>>> s = "First"
>>> print s.__class__

>>> print s
First
>>> s = "Second"
>>> print s
Second
>>>



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


Re: [Tutor] string immutability

2011-10-24 Thread Johan Martinez
On Mon, Oct 24, 2011 at 1:52 PM, Wayne Werner wrote:

> On Mon, Oct 24, 2011 at 1:04 PM, Johan Martinez wrote:
>
>> Hi,
>>
>> I am struggling to understand Python string immutability. I am able to
>> modify Python string object after initializing/assigning it a value. So how
>> does immutability work? I am not following it. Sorry for really stupid
>> question. Any help?
>>
>> 
>>
>> >>> s = "First"
>> >>> print s.__class__
>> 
>> >>> print s
>> First
>> >>> s = "Second"
>>
>
> This is not actually modifying the string object. Unlike most other
> programming languages where a variable refers to an actual location in
> memory (usually), in Python the variable names the actual value.
>
> So when you do s = "First" then you are telling python that you want to be
> able to refer to the string "First" by the name/variable s.
>
> When you execute s="Second" you are now telling python that instead of
> referring to "First" you want the name 's' to refer to the string "Second".
>
> If you try to modify the actual value of the string, you will raise an
> exception:
>
> >>> s = "First"
> >>> s[0] = "T"
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'str' object does not support item assignment
>
> HTH,
> Wayne
>


Thanks for the replies everyone - Steve, Dave, Sander and Wayne. I realized
my wrong understanding/interpretation after posting the message to the list,
which usually  happens most of the time with me!



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


Re: [Tutor] string immutability

2011-10-24 Thread Johan Martinez
On Mon, Oct 24, 2011 at 2:07 PM, Andreas Perstinger <
andreas.perstin...@gmx.net> wrote:

> On 2011-10-24 20:04, Johan Martinez wrote:
>
>> Hi,
>>
>> I am struggling to understand Python string immutability. I am able to
>> modify Python string object after initializing/assigning it a value.
>>
>>   s = "First"
>>>>>  print s.__class__
>>>>>
>>>> 
>>
>>>  print s
>>>>>
>>>> First
>>
>>>  s = "Second"
>>>>>  print s
>>>>>
>>>> Second
>>
>
> Dave, Sander and Wayne have already explained why you aren't modifying
> string objects in your example.
> With the id()-function you can also see what is happening:
>
> >>> s = "First"
> >>> id(s)
> 3077110080L# In CPython this is the memory address of the object
>   # with the name 's' (in your case "First")
> >>> s = "Second"
> >>> id(s)
> 3077110304L# You see that 's' refers now to another address
> >>> id("First")
> 3077110080L# But "First" is still on the same address as before
> >>> id("Second")
> 3077110304L# And this proves that "Second" is at the address
>   # which 's' refers to
>
> Bye, Andreas
>

Great, that's really helpful Andreas.

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


Re: [Tutor] string immutability

2011-10-24 Thread Johan Martinez
On Mon, Oct 24, 2011 at 2:32 PM, Steve Willoughby  wrote:

> On 24-Oct-11 12:17, Johan Martinez wrote:
>
>> Thanks for the replies everyone - Steve, Dave, Sander and Wayne. I
>> realized my wrong understanding/interpretation after posting the message
>> to the list, which usually  happens most of the time with me!
>>
>
> That happens to most of us all the time too :)  Unfortunately, with the lag
> between posting to the list and mail getting out to everyone, you'll
> probably get several replies that all say the same thing--we're not piling
> up on you, it's just a bunch of people being helpful without seeing that
> someone already answered yet.
>
> Glad we could help.  Looking more into how Python variables work unlocks a
> lot of potential for all sorts of data structure operations that other
> languages require pointers to do, but are a lot easier when essentially all
> "variables" are references to objects but with the details handled behind
> the scenes for you.
>
> --
> Steve Willoughby / st...@alchemy.com
> "A ship in harbor is safe, but that is not what ships are built for."
> PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C


Actually it's good to see so many replies and different methods and
explanations here.

Also, is there any doc link where I can find all the information about
String object - class and instance methods. Google pointed me to following
two links, but that wasn't helpful for finding instance method for finding
length of a string object (rather than using 'len' function).

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

Finally I figured it out ( __length__() ) thanks to ipython shell env. But
is there any online documentation or interactive reference like ruby-ri?

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


[Tutor] Syntax for list comps

2016-02-03 Thread Johan Martinez
Where can I find syntax for list comps? I am confused how/whether they are
evaluated left-right or right-left. Consider following list flattening
example:

mx = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

[value for row in mx for value in row]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

It seems like 'for' loops are evaluated from left to right (returned 'row'
is passed to right side for), but return 'value' (from second for loop) is
not on right, but left side.

That's a bit confusing syntax for me. Sorry if I am not clear in explaining
it.

What is the reasoning behind this syntax?


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


[Tutor] Creating class / OOP structure

2013-11-05 Thread Johan Martinez
I need help in modifying my program. Right now it looks as follows:


class Filedict():
def __init__(self, fname):
self.fname =fname

def parse(self):
with open(self.fname, 'r') as f:

# some file search and parsing logic
return parsed_file

def process(self, parsed_object):
for k in parsed_obj.keys():

 return processed_file


I instantiate Filedict and use it as follows:

f = Filedict('sales.txt')
parsed_f = f.parse()
processed_f = f.process(parsed_f)

So I need to pass parsed_f again to the process method. I would like to use
process method directly on initialized object. For example:

f = Filedict('sales.txt')
f.process()

Can someone help me in improving my code?

Should I store parsed_file as an object attribute as follows?

class Filedict():
def __init__(self, fname):
self.fname =fname
self.parsed_file = self.parse()


Any help?


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


Re: [Tutor] Creating class / OOP structure

2013-11-06 Thread Johan Martinez
On Tue, Nov 5, 2013 at 6:19 PM, Steven D'Aprano  wrote:

> On Tue, Nov 05, 2013 at 03:55:05PM -0800, Johan Martinez wrote:
> > I need help in modifying my program. Right now it looks as follows:
> [snip code]
> > Can someone help me in improving my code?
>
> Yes! The first thing to do is get rid of the unnecessary class. This is
> not Java where you have to write classes for everything. From the sample
> code that you show below, using OOP here accomplishes nothing except
> making the code more complicated and less efficient.
>
> Please don't think I am *against* OOP. But it is a tool, nothing more,
> and you should always use the right tool for the job. And in this case,
> I think the right tool is to create two functions:
>
> def parse(filename):
> with open(filename, 'r') as f:
> ...
> return parsed_file
>
> def process(parsed_file):
> for k in parsed_file:  # Iteration automatically uses keys.
> ...
> return processed_file
>
>
> And then simply call them like this:
>
> processed = process(parse('sales.txt'))
>
> Why is this better?
>
> In the code you show, you don't use the object-oriented structure, so
> why waste time building an object-ordiented structure? Similarly, after
> you have read the file once, the class solution holds onto the contents
> forever. But you don't need it forever, once you have parsed the
> contents they are no longer needed. So why hold on to them longer than
> necessary?
>
> Classes should only be used when you need to encapsulate state plus
> behaviour, in other words, when they represent a *thing*. Classes should
> be nouns: BankAccount, User, DecimalNumber all make good classes. Your
> class *needs* only behaviour -- the class doesn't need to store either
> self.fname nor self.parsed_file, since they are both only used once. In
> effect, they are temporary variables that are given names and made
> long-living:
>
> # no need for this
> filename = "sales.txt"
> parsed_file = parse(filename)
> processed = process(parsed_file)
>
> # now go on to use processed but not filename or parsed_file
> ...
>
> Since those two variables are only used once, there is no need to keep
> them as named variables. Get rid of them!
>
> processed = process(parse('sales.txt'))
>
>
> Now, obviously there are parts of the code you haven't shown us. Perhaps
> you do have good reason for storing parsed_file and filename for later
> use. If so, then my objection to using a class will be reduced, or even
> eliminated.
>
> But even then, there is one last problem with your class: it has a
> dangerously misleading name, which hints that it is not a well-designed
> class.
>
> "Filedict" is neither a file nor a dict -- it doesn't inherit from file,
> or behave like a file; it doesn't inherit from dict, or behave like a
> dict. It is, in fact, *not* a file/dict at all. What you really have is
> something with a nasty compound name:
>
> FileParserAndDictProcessor
>
>
> When your classes have nasty compound names like this, it is a very
> strong clue that the class doesn't actually represent a thing and
> probably shouldn't exist. Don't use classes just as a wrapper around a
> few functions and unrelated variables. (What does the file name have to
> do with the process() method? Why are they stored together?)
>
> For a very entertaining -- although quite long -- look at this issue,
> have a read of this:
>
>
> http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html
>
>
> You don't need to be a Java developer to get value from it.
>
>
> > Should I store parsed_file as an object attribute as follows?
> >
> > class Filedict():
> > def __init__(self, fname):
> > self.fname =fname
> > self.parsed_file = self.parse()
>
> Should you? No. Can you? Yes. But follow the logic -- you could continue
> the process of pushing more code into the __init__ method:
>
> class Filedict():  # Terrible name...
> def __init__(self, fname):
> self.fname =fname
> self.parsed_file = self.parse()
> self.processed = self.process()
>
> f = Filedict("sales.txt")
> processed = f.processed
>
> But now the instance f has no reason to exist, so dump it:
>
> processed = Filedict("sales.txt").processed
>
> which basically means you are using __init__ just as a wrapper to hide
> away a couple of function calls.
>
>
>
> --
> Steven



Thanks for the detailed reply Steven. I am trying to learn class/OOP
structure and selected file pa