Re: [Tutor] Need help printing a pickled data

2013-06-24 Thread Peter Otten
Matt D wrote:

> On 06/24/2013 07:17 PM, Alan Gauld wrote:
>> On 24/06/13 23:05, Matt D wrote:
>>> I have been unable to find a way to write pickled data to text file.
>> 
>> Probably because pickled data is not plain text.
>> You need to use binary mode. However...
>> 
>> 
>>>  def __init__(self, data):
>>>  wx.PyEvent.__init__(self)
>>>  self.SetEventType (wxDATA_EVENT)
>>>  # and this is the actual data
>>>  self.data = data
>>>  with open('mypicklelog.txt','a') as log:
>>>  log.write(self.data)
>> 
>> Since you are not using pickle here, all you are really doing
>> is trying to write whatever data is to a text file that
>> happens to have 'pickle' in its name.
>> 
>> When writing to a text file you need to write strings.
>> You have no guarantee that 'data' is a string. You should
>> probably convert it before writing it. Thats one of the
>> advantages of using real pickles - they take care of
>> that complication for you.
>> 
>>> I cant figure out why these last two line dont write to the .txt file
>>> after the program has received the pickled Python dictionary?
>> 
>> Pickle data has to be unpickled before you can use it.
>> Before you can write it back again you need to repickle it.
>> The code you posted does not show you producing and pickled
>> data nor indeed you reading any pickled data...
>> 
>> If 'data' is indeed in pickle format you cannot simply write
>> it to a text file since Pickle is not in a text format.
>> 
>> 
> im sorry; some more code will clarify i think ;

No, you aren't listening to Alan. The suggestive filename notwithstanding

> with open('mypicklelog.txt','a') as log:
> log.write(self.data)

will fail unless self.data is a string. Disregarding all other problems for 
the moment, you need

with open('mypicklelog.txt','ab') as log: # open in binary mode
pickle.dump(self.data, log) # serialize data and write to file

where pickle.dump(obj, file) converts `obj` to a sequence of bytes before it 
is written to `file`.

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


Re: [Tutor] mistaken about splitting expressions over lines

2013-06-24 Thread Dave Angel

On 06/24/2013 09:48 PM, Jim Mooney wrote:

For some reason I took the impression that you could split expressions
over lines. However, this works:

word = 'spam'
new_word = word + 'eggs'
print(word)

But this is a syntax error:

word = 'spam'
new_word = word +
'eggs'
print(word)

  That's easy to avoid, but what if you're adding five or six very long
things, like some really long strings?



Simplest thing is to add parentheses around the expression.

  new_word = (word + 'a very long string' + other_word +
  "another long string" + still_another)

Alternatively, you can also use the statement continuation mechanism, 
whereby the last character of the line is a backslash.  Using that 
approach you can break almost anywhere, except within a token or inside 
a string literal.  And you can break up string literals without using a 
"+" operator, because adjacent string literals are combined at compile time.


  a = "this" \
  " string" " is long"

is exactly equivalent to
  a = "this string is long"


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


[Tutor] mistaken about splitting expressions over lines

2013-06-24 Thread Jim Mooney
For some reason I took the impression that you could split expressions
over lines. However, this works:

word = 'spam'
new_word = word + 'eggs'
print(word)

But this is a syntax error:

word = 'spam'
new_word = word +
'eggs'
print(word)

 That's easy to avoid, but what if you're adding five or six very long
things, like some really long strings?

-- 
Jim
Never run on gravel with a lightbulb in your mouth (personal
experience - don't ask.)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help printing a pickled data

2013-06-24 Thread Matt D
On 06/24/2013 07:17 PM, Alan Gauld wrote:
> On 24/06/13 23:05, Matt D wrote:
>> I have been unable to find a way to write pickled data to text file.
> 
> Probably because pickled data is not plain text.
> You need to use binary mode. However...
> 
> 
>>  def __init__(self, data):
>>  wx.PyEvent.__init__(self)
>>  self.SetEventType (wxDATA_EVENT)
>>  # and this is the actual data
>>  self.data = data
>>  with open('mypicklelog.txt','a') as log:
>>  log.write(self.data)
> 
> Since you are not using pickle here, all you are really doing
> is trying to write whatever data is to a text file that
> happens to have 'pickle' in its name.
> 
> When writing to a text file you need to write strings.
> You have no guarantee that 'data' is a string. You should
> probably convert it before writing it. Thats one of the
> advantages of using real pickles - they take care of
> that complication for you.
> 
>> I cant figure out why these last two line dont write to the .txt file
>> after the program has received the pickled Python dictionary?
> 
> Pickle data has to be unpickled before you can use it.
> Before you can write it back again you need to repickle it.
> The code you posted does not show you producing and pickled
> data nor indeed you reading any pickled data...
> 
> If 'data' is indeed in pickle format you cannot simply write
> it to a text file since Pickle is not in a text format.
> 
> 
im sorry; some more code will clarify i think ;

class DataEvent(wx.PyEvent):
   # the values of the text fields get passed into the constructor
inside of data
def __init__(self, data):
wx.PyEvent.__init__(self)
# this line *binds* this class to a certain type of event,
wxDATA_EVENT
self.SetEventType (wxDATA_EVENT)
# and this is the actual data
self.data = data
with open('mypicklelog.txt','a') as log:
log.write(self.data)

self.data stores the data as a dictionary.  from lower inthe program:

 # Display the values on the UI
def display_data(self,event):
#gets the "message" into the event object
#message is equal to the "data" parameter in the "DataEvent" class
message = event.data

# unpickle the string
pickled_dict = message.to_string()

#separate the string into values for each text control (attrs is
a pickle object)
attrs = pickle.loads(pickled_dict)

#pass this pickle object into update
self.update(attrs)


The purpose of getting the pickle in file is so that i can make a little
program to resend it to this program at will for testing purposes.
Clearly I was not aware that we cant put pickled data into a test file.
 What would be the best way to save the pickle for testing purposes?




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


Re: [Tutor] Need help printing a pickled data

2013-06-24 Thread Marc Tompkins
On Mon, Jun 24, 2013 at 3:48 PM, Matt D  wrote:


> > def __init__(self, data):
> > wx.PyEvent.__init__(self)
> > # this line *binds* this class to a certain type of event,
> > wxDATA_EVENT
> > self.SetEventType (wxDATA_EVENT)
> > # and this is the actual data
> > self.data = data
> > with open('mypicklelog.txt','a') as log:
> > log.write(self.data)
>

Jumping in a little late here, but: do you do anything else, later on, with
self.data?  If not, you could skip the "self.data = data" line and just do
your thing with "data"...

If you ARE doing something with it later on, of course, please disregard.
I just wanted to point out that not everything needs to be persisted, if
you're only using it once.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help printing a pickled data

2013-06-24 Thread Alan Gauld

On 24/06/13 23:05, Matt D wrote:

I have been unable to find a way to write pickled data to text file.


Probably because pickled data is not plain text.
You need to use binary mode. However...



 def __init__(self, data):
 wx.PyEvent.__init__(self)
 self.SetEventType (wxDATA_EVENT)
 # and this is the actual data
 self.data = data
 with open('mypicklelog.txt','a') as log:
 log.write(self.data)


Since you are not using pickle here, all you are really doing
is trying to write whatever data is to a text file that
happens to have 'pickle' in its name.

When writing to a text file you need to write strings.
You have no guarantee that 'data' is a string. You should
probably convert it before writing it. Thats one of the
advantages of using real pickles - they take care of
that complication for you.


I cant figure out why these last two line dont write to the .txt file
after the program has received the pickled Python dictionary?


Pickle data has to be unpickled before you can use it.
Before you can write it back again you need to repickle it.
The code you posted does not show you producing and pickled
data nor indeed you reading any pickled data...

If 'data' is indeed in pickle format you cannot simply write
it to a text file since Pickle is not in a text format.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] Need help printing a pickled data

2013-06-24 Thread Matt D
On 06/24/2013 06:05 PM, Matt D wrote:
> I have been unable to find a way to write pickled data to text file.
> My last attempt was to add the last two lines:
> 
>  # the dataevent class -- stores the data that gets transmitted when the
> event occurs.
> #it is the data in text fields, stored in self.data as a dictionary,
> which is basically a c++ map
> #One of these classes gets created whenever an event occurs.
> class DataEvent(wx.PyEvent):
> # the values of the text fields get passed into the constructor
> inside of data
> def __init__(self, data):
> wx.PyEvent.__init__(self)
> # this line *binds* this class to a certain type of event,
> wxDATA_EVENT
> self.SetEventType (wxDATA_EVENT)
> # and this is the actual data
> self.data = data
> with open('mypicklelog.txt','a') as log:
> log.write(self.data)
> 
> I cant figure out why these last two line dont write to the .txt file
> after the program has received the pickled Python dictionary?  Very
> stumped.

>  Sorry I forgot to show the error in terminal:

File "/usr/local/lib/python2.7/dist-packages/baz/op25_traffic_pane.py",
line 53, in __init__
log.write(self.data)
TypeError: expected a character buffer object

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


Re: [Tutor] Need help printing a pickled data

2013-06-24 Thread Steven D'Aprano
On Mon, Jun 24, 2013 at 06:05:37PM -0400, Matt D wrote:

> I have been unable to find a way to write pickled data to text file.

Normally you write pickled data to a file like this:

import pickle

data = {'something': 'goes', 'here': 42}
with open("/path/to/file/name.pickle", "rb") as f:
pickle.dump(data, f)


And then read it back again like this:

with open("/path/to/file/name.pickle") as f:
data = pickle.load(f)


You certainly shouldn't be writing pickle data to a log file! Firstly, 
log files are usually opened in text mode, not binary mode, so it 
probably won't work, and secondly even if it did work, you will be 
dumping a load of pickled binary data into the middle of what should be
a text file. That's a bad idea. And even if it succeeded, what are you  
going to learn from seeing a line like this:

\x80\x03}q\x00(X\x04\x00\x00\x00hereq\x01K*X\t\x00\x00\x00somethingq\x02X\x04\x00\x00\x00goesq\x03u.
 

in the middle of your log file? Log files are supposed to be for humans 
to read, not for binary data like a pickle.


> My last attempt was to add the last two lines:
[...]
> I cant figure out why these last two line dont write to the .txt file
> after the program has received the pickled Python dictionary?  Very
> stumped.

What does it do? Do you get an error?


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


Re: [Tutor] Need help appending data to a logfile

2013-06-24 Thread Matt D
On 06/24/2013 05:57 PM, Dave Angel wrote:
> On 06/24/2013 05:39 PM, Matt D wrote:
>>
>>> But what he's doing has nothing to do with logging.  He's just using
>>> that word.
>>>
>>>
>> Right, I'm not doing a debugging thing.  Just trying to create a log of
>> data that has been passed into the display of this program.  Since I
>> started trying to use the array the program is not working.  So I am
>> wondering if its not the best way to try to save TextCtrl values.
>>
> 
> You accidentally posted this offline, direct to me.  So it loses all
> context.  I'll try to get it back into the thread, but it may not "take."
> 
> I don't know what array you're referring to.  I VERY seldom use arrays
> in Python, since list is much more flexible and easy to use.  Nor do I
> know what you mean by the program not working.
> 
> I also don't know what you mean by saving TextCtrl values.  Aren't they
> being appended to the csv file (in random order) with your latest changes?
> 
> 
> You asked about a "save-as" feature.  Why isn't that as simple as
> copying the current contents of the saved csv file?  Or do you not know
> how you would go about copying?
> 
> Be specific with your questions, and you might get some answers.  Use
> those answers in later versions, and you'll get the same people more
> willing to help further.
> 
> Why is it no longer of interest to you to get a predictable order in
> your csv file?
> 
> 
> -- 
> DaveA
> 
> 
Well i decided to switch to a .txt file because it is easier for me to
lay eyes on it and the commas are there if i want to import it into
librecalc or sas or whatever.  and values were writing in an acceptable
order becuase, while the order was not of my choosing, the order was
always the same.  so that is fine for importing into another program for
later inspection.

What you said about the 'save as' is right, i didnt know how to go about
copying the logfile.txt (as I had it) to the file the user opened.
thats why i decided to try an array like this:

 # openfile defined to start FileDialog and write the traffic log to the
file
def openFile(self, evt):
with wx.FileDialog(self, "Choose a file", os.getcwd(), "",
"*.txt*", wx.OPEN) as dlg:
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
mypath = os.path.basename(path)
with open(mypath, "a") as f:
f.writelines(self.log_array)

I name the array up in the initializer

self.log_array = []

and this is supposed to get the the values out of the pickle and into
the textcrls and into the array:

# Update the field values
# put values in array
def update(self, field_values):
next_line = ""
next_line += strftime("%Y-%m-%d %H:%M:%S")
next_line +=  ','.join( field_values[k] for k in
self.fields.keys() if k in field_values )
log_array.append(next_line)

#if the field 'duid' == 'hdu', then clear all the fields
if field_values['duid'] == 'hdu':
self.clear()
#loop through all TextCtrl fields storing the key/value pairs in
k, v
for k,v in self.fields.items():
# get the pickle value for this TextCtrl
f = field_values.get(k, None)
# if the value is empty then set the new value
if f:
v.SetValue(f)

But the program is not working, meaning the TextCtrl fields are not
getting their values and the log is not being written.  I dont know if I
am missing a self.something or I some indentation wrong that doest throw
the error or what.  Very Stuck.




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


[Tutor] Need help printing a pickled data

2013-06-24 Thread Matt D
I have been unable to find a way to write pickled data to text file.
My last attempt was to add the last two lines:

 # the dataevent class -- stores the data that gets transmitted when the
event occurs.
#it is the data in text fields, stored in self.data as a dictionary,
which is basically a c++ map
#One of these classes gets created whenever an event occurs.
class DataEvent(wx.PyEvent):
# the values of the text fields get passed into the constructor
inside of data
def __init__(self, data):
wx.PyEvent.__init__(self)
# this line *binds* this class to a certain type of event,
wxDATA_EVENT
self.SetEventType (wxDATA_EVENT)
# and this is the actual data
self.data = data
with open('mypicklelog.txt','a') as log:
log.write(self.data)

I cant figure out why these last two line dont write to the .txt file
after the program has received the pickled Python dictionary?  Very
stumped.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help appending data to a logfile

2013-06-24 Thread Dave Angel

On 06/24/2013 05:39 PM, Matt D wrote:



But what he's doing has nothing to do with logging.  He's just using
that word.



Right, I'm not doing a debugging thing.  Just trying to create a log of
data that has been passed into the display of this program.  Since I
started trying to use the array the program is not working.  So I am
wondering if its not the best way to try to save TextCtrl values.



You accidentally posted this offline, direct to me.  So it loses all 
context.  I'll try to get it back into the thread, but it may not "take."


I don't know what array you're referring to.  I VERY seldom use arrays 
in Python, since list is much more flexible and easy to use.  Nor do I 
know what you mean by the program not working.


I also don't know what you mean by saving TextCtrl values.  Aren't they 
being appended to the csv file (in random order) with your latest changes?



You asked about a "save-as" feature.  Why isn't that as simple as 
copying the current contents of the saved csv file?  Or do you not know 
how you would go about copying?


Be specific with your questions, and you might get some answers.  Use 
those answers in later versions, and you'll get the same people more 
willing to help further.


Why is it no longer of interest to you to get a predictable order in 
your csv file?



--
DaveA

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


Re: [Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem

2013-06-24 Thread Jim Mooney
eryksun 
>
> Oh my. I don't think using the numbers spelled out makes it any
> better. I couldn't keep dict_thirty_four vs dict_sixty_five straight
> in my head to save my life.

It was just for fun. But by coincidence I was trolling the web and
some guy wanted to know if Python could change a number into words,
like 349 into Three hundred forty nine. Not in the builtins, I'm
afraid.

Nothing recent seemed available to do that, on a quick websearch, but
I see an easy way to go up to ten dectillion so I'll write that for
practice. The only other module I found was so old I couldn't make
2to3 convert it. And it was vast overkill. I don't need Norwegian
numbers - let the Norwegians count for themselves - one fish, two
fish, three fish...

Actually, I can think of a use for a large number routine (without the
underlines)  Politicians like to alarm us and get contributions by
sending emails about the national debt all the time. "Sixteeen
trillion, eight hundred eighty two billion, two hundred ninety
million, one hundred fifty two thousand, two hundred forty seven
dollars" looks so much more alarming than the numerals. And of course,
if a dumb pol is reading his teleprompter he'll get brain freeze
trying to cipher numerals that big, but he can just read out words.

-- 
Jim
Resistance is futile, but running away is often surprisingly effective.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help (Antonio Zagheni)

2013-06-24 Thread Alan Gauld

On 24/06/13 14:34, Antonio Zagheni wrote:


But I am trying to paste the clipboard content to MS word and when I do
it MS word becomes not responding.


OK, so the question is not how to manipulate the clipboard but how to 
manipulate MS Word. There are multiple ways to approach that.

What technology are you using to talk to Word?
COM? DLL? Robotic?

Do you have any code you can share to show us what you are trying to do?
Also you could try the Win32 Python mailing list since they are experts 
at integrating Python with Windows things.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] Help (Antonio Zagheni)

2013-06-24 Thread Peter Otten
Antonio Zagheni wrote:

>> I am a begginer in Pythonu
>> I did a function that returns a string and I want to copy this to the
>> clipboard. I have tried a lot of suggestions found at Google but nothing
>> works properly. Is there an easy way to do that?
>> I am using Python 2.7 and Windows 7.
> 
> It's simple to access the clipboard with Tkinter:

[eryksun]
 
> >>> from Tkinter import Tk, TclError
> >>> root = Tk()
> >>> root.withdraw()
> ''
> >>> root.clipboard_clear()
> 
> >>> root.clipboard_append('eggs ')
> >>> root.clipboard_append('and spam')
> >>> root.clipboard_get()
> 'eggs and spam'
> 
> >>> root.clipboard_clear()
> >>> try: root.clipboard_get()
> ... except TclError as e: print e
> ...
> CLIPBOARD selection doesn't exist or form "STRING" not defined

[Antonio]

> But I am trying to paste the clipboard content to MS word and when I do it
> MS word becomes not responding.
> 
> So, if you can help...

Please show us the python script you are running and tell us how exactly you 
are invoking it.

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


Re: [Tutor] Function Return Values (or References)

2013-06-24 Thread Steven D'Aprano

On 24/06/13 18:12, John Steedman wrote:

Hi Tutors,

I'm confused by the following possible contradiction. Would someone please
explain or point me to the right docs.


[snip confusion about parameter passing and Python's object model]


By FACT 1  x should be a reference parameter...?
By Fact 2 x would seem to be a copy...?


Function arguments in Python are *neither* passed by reference nor passed by 
value (copied).

Here's a post I made some years ago going into long detail about it. I hope 
this is helpful for you.


http://mail.python.org/pipermail/tutor/2010-December/080505.html


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


Re: [Tutor] Help (Antonio Zagheni)

2013-06-24 Thread Antonio Zagheni
Hello eryksun,

Thanks for your help...

But I am trying to paste the clipboard content to MS word and when I do it MS 
word becomes not responding.

So, if you can help...

Thanks a lot again,

Antonio ZAgheni.


Message: 3
Date: Sun, 23 Jun 2013 18:18:11 -0400
From: eryksun 
To: Antonio Zagheni 
Cc: "tutor@python.org" 
Subject: Re: [Tutor] Help
Message-ID:
    
Content-Type: text/plain; charset=UTF-8

On Thu, Jun 20, 2013 at 6:10 PM, Antonio Zagheni  wrote:
>
> I am a begginer in Python.
> I did a function that returns a string and I want to copy this to the 
> clipboard.
> I have tried a lot of suggestions found at Google but nothing works properly.
> Is there an easy way to do that?
> I am using Python 2.7 and Windows 7.

It's simple to access the clipboard with Tkinter:

    >>> from Tkinter import Tk, TclError
    >>> root = Tk()
    >>> root.withdraw()
    ''
    >>> root.clipboard_clear()

    >>> root.clipboard_append('eggs ')
    >>> root.clipboard_append('and spam')
    >>> root.clipboard_get()
    'eggs and spam'

    >>> root.clipboard_clear()
    >>> try: root.clipboard_get()
    ... except TclError as e: print e
    ...
    CLIPBOARD selection doesn't exist or form "STRING" not defined


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


Re: [Tutor] Function Return Values (or References)

2013-06-24 Thread John Steedman
Thanks for all these clear and knowledgeable answers.  I'm much clearer on
this now and will read up a bit more around these subjects.

John


On Mon, Jun 24, 2013 at 10:59 AM, Peter Otten <__pete...@web.de> wrote:

> John Steedman wrote:
>
> > Hi Tutors,
> >
> > I'm confused by the following possible contradiction. Would someone
> please
> > explain or point me to the right docs.
> >
> > FACT 1
> >
> > "Variables in python hold references to objects."
> > http://en.wikipedia.org/wiki/Python_syntax_and_semantics
> >
> > FACT 2
> >
> def Increment ( x ) :
> // return x + 1
> x = x + 1
> return x
> 
> y = 1
> z = Increment ( y )
> y
> > 1
> z
> > 2
> >
> > By FACT 1  x should be a reference parameter...?
> > By Fact 2 x would seem to be a copy...?
> >
> > What in the world of dynamic typing is going on?
>
> There's a big confusion in terminology. Does
>
> http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing
>
> help? Here's a more detailed explanation:
>
> <
> http://learntofish.wordpress.com/2012/01/09/call-by-object-reference-call-by-sharing/
> >
>
>
>
> ___
> 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] Function Return Values (or References)

2013-06-24 Thread Peter Otten
John Steedman wrote:

> Hi Tutors,
> 
> I'm confused by the following possible contradiction. Would someone please
> explain or point me to the right docs.
> 
> FACT 1
> 
> "Variables in python hold references to objects."
> http://en.wikipedia.org/wiki/Python_syntax_and_semantics
> 
> FACT 2
> 
def Increment ( x ) :
// return x + 1
x = x + 1
return x

y = 1
z = Increment ( y )
y
> 1
z
> 2
> 
> By FACT 1  x should be a reference parameter...?
> By Fact 2 x would seem to be a copy...?
> 
> What in the world of dynamic typing is going on?

There's a big confusion in terminology. Does

http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing

help? Here's a more detailed explanation:



 

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


Re: [Tutor] Function Return Values (or References)

2013-06-24 Thread Dave Angel

On 06/24/2013 04:12 AM, John Steedman wrote:

Hi Tutors,

I'm confused by the following possible contradiction. Would someone please
explain or point me to the right docs.

FACT 1

"Variables in python hold references to objects."
http://en.wikipedia.org/wiki/Python_syntax_and_semantics

FACT 2


def Increment ( x ) :
// return x + 1
x = x + 1
return x

y = 1
z = Increment ( y )
y

1

z

2

By FACT 1  x should be a reference parameter...?
By Fact 2 x would seem to be a copy...?

What in the world of dynamic typing is going on?



Python docs usually use the word "binding" rather than reference.  A 
variable (name) is bound to an object.  But it can be rebound.  For 
example, any assignment rebinds the name to a (possibly new) object.  So 
as soon as you did the x=x+1, you're no longer referring to the original 
object.


Another factor is that int (and float, str, and tuple, plus some others) 
is immutable.  That means that once the object is created, its value 
cannot change.  So there's no way to change the Increment() function to 
do exactly what you ask for.  Since y is bound to an immutable object, 
the function cannot change that value.


Now let's choose a mutable object and try the analogous thing.

def add_to_end(mylist):
mylist = mylist + [42]
return mylist

Once again, if we test it with
k = [4]
j = add_to_end(k)
k
j

we'll see that k is unchanged.  But this one we CAN fix.

def add_to_end(mylist):
mylist.append(42)
#notice we do NOT rebind it, we mutate the object inplace
return mylist

Incidentally, convention is that if a function mutates its (single) 
argument, it does not return it, and if it returns a modified copy, it 
doesn't alter the original.  See for example sort() and sorted(), 
respectively.


If you happen to be familiar with C++, a reference there is bound once 
when it's defined, and it cannot be changed to reference a different 
object.  What would be equivalent to a python rebinding is simply a 
compile-time error.  Of course in C++, whenever such things get in the 
way, you fake your way out with casting.


Hope this helps.


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


Re: [Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem

2013-06-24 Thread eryksun
On Sun, Jun 23, 2013 at 10:38 PM, Jim Mooney  wrote:
> What about class variables instead of globals?, I put this in the my
> lazy typer module, maker.py, which works fine to persist the numbers
> between function calls so I can increment them:
>
> class count:
> dict = list = set = tuple = 0
>
> then I use count.dict += 1 , etc.
>
> Would that restrict python from an upward search, or am I dreaming?

A class body is compiled and evaluated as a function (with unoptimized
locals), but this function isn't searched as a nested scope. Otherwise
the methods of the class could refer to class attributes without using
__getattribute__, which would be confusing as it would bypass
descriptor binding (i.e. properties, bound methods).

But a consequence of this rule also tends to frustrate people:

>>> class Spam:
... n = 2
... evens = [x for x in range(10) if x % n == 0]
...
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in Spam
  File "", line 3, in 
NameError: global name 'n' is not defined

In this case, the  function is compiled to skip the class
scope and instead use LOAD_GLOBAL to find n. Since the class name
"Spam" isn't bound yet (the class object doesn't exist yet), you can't
get around the problem by using Spam.n.

Here's an example that shows the class scope getting skipped to
instead use the outer scope of function f():

>>> def f():
... n = 2
... class Spam:
... n = 3 # skip this
... evens = [x for x in range(10) if x % n == 0]
... return Spam.evens
...
>>> f()
[0, 2, 4, 6, 8]

> And yes, I got rid of the Basic-style names D1, D2. The program now
> converts numbers to human-names up to  dict_ninety_nine = , for
> instance.  And no, I didn't type ninety_nine dictionary entries to do
> that. I'm too lazy a typer  ;')

Oh my. I don't think using the numbers spelled out makes it any
better. I couldn't keep dict_thirty_four vs dict_sixty_five straight
in my head to save my life.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Function Return Values (or References)

2013-06-24 Thread John Steedman
Hi Tutors,

I'm confused by the following possible contradiction. Would someone please
explain or point me to the right docs.

FACT 1

"Variables in python hold references to objects."
http://en.wikipedia.org/wiki/Python_syntax_and_semantics

FACT 2

>>>def Increment ( x ) :
>>>// return x + 1
>>>x = x + 1
>>>return x
>>>
>>>y = 1
>>>z = Increment ( y )
>>>y
1
>>>z
2

By FACT 1  x should be a reference parameter...?
By Fact 2 x would seem to be a copy...?

What in the world of dynamic typing is going on?

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