Re: [Tutor] how obsolete is 2.2, and a pickle question

2011-09-08 Thread Peter Otten
c smith wrote:

> oh, and a question on 'pickle':
> can pickle deserialize things that were not serialized by python?
> can it convert data into a python data type regardless of it was
> originally a 'c array' or something else that python doesn't support?

As long as the file written by C is a valid pickle file and all classes used 
are available to the Python interpreter you are fine:

$ cat pickledemo_struct.c
#include 

typedef struct NAMEDPAIR {
  char name[10];
  int x;
  int y;
} namedpair;

main()
{
  FILE *f = fopen("tmp_struct.pickle", "wb");
  int i;
  namedpair *p, data[] = {{"Cube", 10, 20}, {"Pyramid", 30, 40}};
  fprintf(f, "(lp0\n");
  for (i = 0, p = data; i != 2; i++, p++) {
fprintf(f, "(S'%s'\nI%d\nI%d\ntp%d\na", p->name, p->x, p->y, i+1);
  }
  fprintf(f, ".");
}
$ gcc pickledemo_struct.c
$ ./a.out
$ python -c 'import pickle; print pickle.load(open("tmp_struct.pickle"))'
[('Cube', 10, 20), ('Pyramid', 30, 40)]

But remember that in C the information whether you have a 32 bit integer or 
four characters is in the code, not in the data; if you just dump that data 
to a file Python can still read it, but has no way of knowing what it's 
meant to be.


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


Re: [Tutor] how obsolete is 2.2?

2011-09-08 Thread Alan Gauld

On 08/09/11 04:26, c smith wrote:

I found a book at the local library that covers python but it's 2.2.
I already have been using 2.7 for basic stuff and would like to know if
it's worth my time to read this book.


That depends on your experience level and what you are looking to get 
out of it.


The Python 2 series is very backwards compatible so virtually everything 
you read in the book will still work in Python 2.7. It's just that some 
new whizzy features have been added since 2.2 that it won't cover. But 
many of those features are not things the average programmer uses every day.


The vast majority of the standard library modules haven't changed that 
much and any information about those will probably still be accurate.
Given you get to read it for free from the library I'd say yes, its very 
worthwhile.


But if you have been using Python for a while and want to dig deeper 
into its power features then it probably isn't worth reading because the 
changes in Python recently have focused on many of the more subtle 
things "under the covers" and 2.2 won't cover them,



can pickle deserialize things that were not serialized by python?


Not unless the thing that serialised them was deliberately copying 
Pythons serialisation format.



can it convert data into a python data type regardless of it was
originally a 'c array' or something else that python doesn't support?


No, the nearest thing to that is the struct module. But there you have 
to know what you are reading and construct a format specifier to match.


--
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] understanding **kwargs syntax

2011-09-08 Thread John
Following up on this...

Why does pylint seem to think it is a bad idea?

Description ResourcePathLocationType
ID:W0142 plot_ts_array_split_x: Used * or **
magic   tsplot.py   /research.plot  line 299PyLint Problem

Thanks,
john


On Thu, Aug 25, 2011 at 10:44 AM, Alan Gauld  wrote:
> On 25/08/11 09:27, John wrote:
>>
>> Just a quick question,
>>
>> is it wrong to use the *args and **kwargs ( the latter in particular)
>> when DEFINING a function?
>
> No, in fact it's essential if you don't know in advance what arguments are
> going to be passed to the function. This is very common if you are wrapping
> another function that itself takes variable arguments.
>
>> def fest(**kwargs):
>>     """ a function test """
>>     keys = sorted(kwargs.keys())
>>
>>     print("You provided {0} keywords::\n".format(len(keys)))
>>     for kw in keys:
>>         print("{0} =>  {1}".format(kw, kwargs[kw]))
>>
>> Are there some good examples of when this would be a good idea to
>> implement?
>
> GUI frameworks like Tkinter often take variable numbers of configuration
> values. If you want to wrap that with a
> function of your own you can do something like(pseudocode):
>
> def myfunc(**kwargs):
>   if some interesting arg exists
>        do something with it
>   return wrappedFunc(kwargs)
>
> There are plenty other cases, try grepping the standard library code
> for lines with def and **kwargs for some examples...
>
> --
> 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
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
Basemap: 1.0
Matplotlib: 1.0.0
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] need advice about a dictionary ({})

2011-09-08 Thread Richard D. Moores
I've succeeded in writing a dictionary ({}) that I can use as a small
personal phone book. The dictionary (very shortened and simplified)
looks like this in the script;

p = {}

p['bp1'] = 'xxx'
p['bp2'] = 'ooo'
p['ch'] = 'zzz'
p['me'] = 'aaa'
p['mg'] = 'vvv'
p['pu1'] = 'bbb'
p['pu2'] = 'ccc'
p['pw'] = 'kkk'

I have a function that enables the user to enter 'bp', for example,
and return both 'xxx' and 'ooo'.

(The keys are initials; I've disguised the values, each of which of
course are   name, home number, mobile number, speed dial number,
etc.)

But I'd like to put the lines of the dictionary in a text file so that
I can add key/value items to it by writing to it with another script.
I think I can do that, but I need some hints about how to get  the
script to access the text file in a way that lets the user look up a
phone number. I'm thinking that the script needs to recreate the
dictionary each time it's called, but I don't know how to do that.

Thanks,

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


Re: [Tutor] understanding **kwargs syntax

2011-09-08 Thread Peter Otten
John wrote:

> Following up on this...
> 
> Why does pylint seem to think it is a bad idea?
> 
> Description   ResourcePathLocationType
> ID:W0142 plot_ts_array_split_x: Used * or **
> magic tsplot.py   /research.plot  line 299PyLint Problem

I would guess it's a readability concern. Consider a simple function

def f(x, y=0):
print x + y

for a in [1], "ab", "abc":
f(*a)

Can you tell what will be printed immediately? For me

f(1)
f("a", "b")
f("a", "b", "c")

is much easier to predict.

That said, there are valid usecases for * and ** "magic", and of course 
pylint cannot take the tradeoffs into account. Therefore don't take pylint's 
warnings as gospel.

PS: the exception is intentional

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


Re: [Tutor] need advice about a dictionary ({})

2011-09-08 Thread Christian Witts

On 2011/09/08 12:58 PM, Richard D. Moores wrote:

I've succeeded in writing a dictionary ({}) that I can use as a small
personal phone book. The dictionary (very shortened and simplified)
looks like this in the script;

p = {}

p['bp1'] = 'xxx'
p['bp2'] = 'ooo'
p['ch'] = 'zzz'
p['me'] = 'aaa'
p['mg'] = 'vvv'
p['pu1'] = 'bbb'
p['pu2'] = 'ccc'
p['pw'] = 'kkk'

I have a function that enables the user to enter 'bp', for example,
and return both 'xxx' and 'ooo'.

(The keys are initials; I've disguised the values, each of which of
course are   name, home number, mobile number, speed dial number,
etc.)

But I'd like to put the lines of the dictionary in a text file so that
I can add key/value items to it by writing to it with another script.
I think I can do that, but I need some hints about how to get  the
script to access the text file in a way that lets the user look up a
phone number. I'm thinking that the script needs to recreate the
dictionary each time it's called, but I don't know how to do that.

Thanks,

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




You could pickle your dictionary object which will give you the 
persistence and then when your script starts up you can unpickle the 
file if it exists else create a new one. Of course if you make any 
changes to your object you'll need to pickle it once your app finishes 
otherwise new changes won't be written out.


With just a plain text file you can also just grep the info out
$ cat test.file
bp1:xxx|yyy
bp2:ooo|ppp
ch:zzz|asf
me:agkjh|agjh
$ grep -i ^bp* test.file
bp1:xxx|yyy
bp2:ooo|ppp
$ grep -i ^BP* test.file
bp1:xxx|yyy
bp2:ooo|ppp

--

Christian Witts
Python Developer

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


Re: [Tutor] need advice about a dictionary ({})

2011-09-08 Thread Richard D. Moores
On Thu, Sep 8, 2011 at 04:36, Christian Witts  wrote:
> On 2011/09/08 12:58 PM, Richard D. Moores wrote:
>
> I've succeeded in writing a dictionary ({}) that I can use as a small
> personal phone book. The dictionary (very shortened and simplified)
> looks like this in the script;
>
> p = {}
>
> p['bp1'] = 'xxx'
> p['bp2'] = 'ooo'
> p['ch'] = 'zzz'
> p['me'] = 'aaa'
> p['mg'] = 'vvv'
> p['pu1'] = 'bbb'
> p['pu2'] = 'ccc'
> p['pw'] = 'kkk'
>
> I have a function that enables the user to enter 'bp', for example,
> and return both 'xxx' and 'ooo'.
>
> (The keys are initials; I've disguised the values, each of which of
> course are   name, home number, mobile number, speed dial number,
> etc.)
>
> But I'd like to put the lines of the dictionary in a text file so that
> I can add key/value items to it by writing to it with another script.
> I think I can do that, but I need some hints about how to get  the
> script to access the text file in a way that lets the user look up a
> phone number. I'm thinking that the script needs to recreate the
> dictionary each time it's called, but I don't know how to do that.
>
> Thanks,
>
> Dick Moores
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
> You could pickle your dictionary object which will give you the persistence
> and then when your script starts up you can unpickle the file if it exists
> else create a new one. Of course if you make any changes to your object
> you'll need to pickle it once your app finishes otherwise new changes won't
> be written out.
>
> With just a plain text file you can also just grep the info out
> $ cat test.file
> bp1:xxx|yyy
> bp2:ooo|ppp
> ch:zzz|asf
> me:agkjh|agjh
> $ grep -i ^bp* test.file
> bp1:xxx|yyy
> bp2:ooo|ppp
> $ grep -i ^BP* test.file
> bp1:xxx|yyy
> bp2:ooo|ppp

I should have stated that I'm using Win 7, Python 3.2.1. No Unix.

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


Re: [Tutor] need advice about a dictionary ({})

2011-09-08 Thread Peter Otten
Richard D. Moores wrote:

> I've succeeded in writing a dictionary ({}) that I can use as a small
> personal phone book. The dictionary (very shortened and simplified)
> looks like this in the script;
> 
> p = {}
> 
> p['bp1'] = 'xxx'
> p['bp2'] = 'ooo'
> p['ch'] = 'zzz'
> p['me'] = 'aaa'
> p['mg'] = 'vvv'
> p['pu1'] = 'bbb'
> p['pu2'] = 'ccc'
> p['pw'] = 'kkk'
> 
> I have a function that enables the user to enter 'bp', for example,
> and return both 'xxx' and 'ooo'.
> 
> (The keys are initials; I've disguised the values, each of which of
> course are   name, home number, mobile number, speed dial number,
> etc.)
> 
> But I'd like to put the lines of the dictionary in a text file so that
> I can add key/value items to it by writing to it with another script.
> I think I can do that, but I need some hints about how to get  the
> script to access the text file in a way that lets the user look up a
> phone number. I'm thinking that the script needs to recreate the
> dictionary each time it's called, but I don't know how to do that.

Start with a simple file format. If you don't allow "=" in the key and "\n" 
in either key or value 

bp1=xxx
bp2=ooo
...
pw=kkk

should do. I suppose you know how to read a file one line at a time? Before 
you add the line into the dictionary you have to separate key and value 
(str.partition() may help with that) and remove the trailing newline from 
the value. If you need more flexibility look into the json module. This 
makes reading and writing the file even easier, and while the format is a 
bit more complex than key=value

>>> print json.dumps(p, indent=2)
{
  "me": "aaa",
  "mg": "vvv",
  "ch": "zzz",
  "pw": "kkk",
  "bp1": "xxx",
  "bp2": "ooo",
  "pu1": "bbb",
  "pu2": "ccc"
}

it can still be edited by a human.

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


Re: [Tutor] how obsolete is 2.2?

2011-09-08 Thread Steven D'Aprano

c smith wrote:


Also, am I correct in thinking that 3.0 will always be called 3.0 but will
change over time and will always include experimental features, while 2.x
will gradually increase the 'x' and the highest 'x' will indicate the most
current, stable release?


No, I'm afraid you are wrong.

Python 2.7 is the last version in the 2.x series. It will continue to 
get bug fixes and security updates for the next few years, but no new 
features.


2.7 and 3.2 are the most up to date versions. As I said, 2.7 is the last 
of the 2.x line. 3.x is the future of Python, although 2.7 will be 
supported for quite some time. But all new features will be going into 
3.x and 2.7 will only get bug fixes.


Python 3.0 is no longer supported: to be frank, it was released too 
early, and it has too many bugs and is painfully slow. If you are using 
3.0, you should update to 3.1 or 3.2, they are much, much better.





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


[Tutor] a quick Q: built-in method pop of list object at 0x7f8221a22cb0>

2011-09-08 Thread lina
Hi,





what does the 0x7f8221a22cb0 mean here? the computer physical address.

Thanks,


-- 
Best Regards,

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


[Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread lina
Hi,

I failed to understand the "collpase" meaning in a string.

can someone give me a simple example?

Sorry,

-- 
Best Regards,

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


Re: [Tutor] need advice about a dictionary ({})

2011-09-08 Thread Steven D'Aprano

Richard D. Moores wrote:


But I'd like to put the lines of the dictionary in a text file so that
I can add key/value items to it by writing to it with another script.


If you expect human beings (yourself, or possibly even the user) to edit 
the text file, then you should look at a human-writable format like these:



Good ol' fashioned Windows INI files:
import configparser
JSON:  import json
PLIST: import plistlib
YAML:  download from http://pyyaml.org/wiki/PyYAML


If the ability to edit the files isn't important, then I suggest using 
the pickle module instead.






--
Steven

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


Re: [Tutor] need advice about a dictionary ({})

2011-09-08 Thread Richard D. Moores
On Thu, Sep 8, 2011 at 04:43, Peter Otten <__pete...@web.de> wrote:
> Richard D. Moores wrote:
>
>> I've succeeded in writing a dictionary ({}) that I can use as a small
>> personal phone book. The dictionary (very shortened and simplified)
>> looks like this in the script;
>>
>> p = {}
>>
>> p['bp1'] = 'xxx'
>> p['bp2'] = 'ooo'
>> p['ch'] = 'zzz'
>> p['me'] = 'aaa'
>> p['mg'] = 'vvv'
>> p['pu1'] = 'bbb'
>> p['pu2'] = 'ccc'
>> p['pw'] = 'kkk'
>>
>> I have a function that enables the user to enter 'bp', for example,
>> and return both 'xxx' and 'ooo'.
>>
>> (The keys are initials; I've disguised the values, each of which of
>> course are   name, home number, mobile number, speed dial number,
>> etc.)
>>
>> But I'd like to put the lines of the dictionary in a text file so that
>> I can add key/value items to it by writing to it with another script.
>> I think I can do that, but I need some hints about how to get  the
>> script to access the text file in a way that lets the user look up a
>> phone number. I'm thinking that the script needs to recreate the
>> dictionary each time it's called, but I don't know how to do that.
>
> Start with a simple file format. If you don't allow "=" in the key and "\n"
> in either key or value
>
> bp1=xxx
> bp2=ooo
> ...
> pw=kkk
>
> should do. I suppose you know how to read a file one line at a time? Before
> you add the line into the dictionary you have to separate key and value
> (str.partition() may help with that) and remove the trailing newline from
> the value. If you need more flexibility look into the json module. This
> makes reading and writing the file even easier, and while the format is a
> bit more complex than key=value
>
 print json.dumps(p, indent=2)
> {
>  "me": "aaa",
>  "mg": "vvv",
>  "ch": "zzz",
>  "pw": "kkk",
>  "bp1": "xxx",
>  "bp2": "ooo",
>  "pu1": "bbb",
>  "pu2": "ccc"
> }
>
> it can still be edited by a human.

Thanks Peter!

You made it a lot easier than I thought it would be. Please see
 for the script's current incarnation.
The text of the demo data file is quoted in the script, lines 6-13. It
doesn't seem I need to use the json module, though I want to learn it
eventually.

The data file very easily edited. However, as the number of lines gets
large (maybe 100?) I'll need a way to determine if the new key is
already in the file. So I'll be working on a script that I can use to
safely add lines to the the file, by keeping all the keys unique.

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


Re: [Tutor] understanding **kwargs syntax

2011-09-08 Thread Alan Gauld

On 08/09/11 11:10, John wrote:

Following up on this...

Why does pylint seem to think it is a bad idea?

Description ResourcePathLocationType
ID:W0142 plot_ts_array_split_x: Used * or **
magic   tsplot.py   /research.plot  line 299PyLint Problem


I assume because it is a bad idea in most cases. If you know what the 
arguments are going to be then specify them. Otherwise you can get all 
sorts of rubbish being passed in that you have to figure out how to deal 
with. That's never a good place to be.


But occasionally you have to do things that are less than ideal.
And *args/**kwargs are useful in those situations, just don't
use them unless you have to.

--
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 advice about a dictionary ({})

2011-09-08 Thread Richard D. Moores
On Thu, Sep 8, 2011 at 04:43, Peter Otten <__pete...@web.de> wrote:
> Richard D. Moores wrote:
>
>> I've succeeded in writing a dictionary ({}) that I can use as a small
>> personal phone book. The dictionary (very shortened and simplified)
>> looks like this in the script;
>>
>> p = {}
>>
>> p['bp1'] = 'xxx'
>> p['bp2'] = 'ooo'
>> p['ch'] = 'zzz'
>> p['me'] = 'aaa'
>> p['mg'] = 'vvv'
>> p['pu1'] = 'bbb'
>> p['pu2'] = 'ccc'
>> p['pw'] = 'kkk'
>>
>> I have a function that enables the user to enter 'bp', for example,
>> and return both 'xxx' and 'ooo'.
>>
>> (The keys are initials; I've disguised the values, each of which of
>> course are   name, home number, mobile number, speed dial number,
>> etc.)
>>
>> But I'd like to put the lines of the dictionary in a text file so that
>> I can add key/value items to it by writing to it with another script.
>> I think I can do that, but I need some hints about how to get  the
>> script to access the text file in a way that lets the user look up a
>> phone number. I'm thinking that the script needs to recreate the
>> dictionary each time it's called, but I don't know how to do that.
>
> Start with a simple file format. If you don't allow "=" in the key and "\n"
> in either key or value
>
> bp1=xxx
> bp2=ooo
> ...
> pw=kkk
>
> should do. I suppose you know how to read a file one line at a time? Before
> you add the line into the dictionary you have to separate key and value
> (str.partition() may help with that) and remove the trailing newline from
> the value. If you need more flexibility look into the json module. This
> makes reading and writing the file even easier, and while the format is a
> bit more complex than key=value
>
 print json.dumps(p, indent=2)
> {
>  "me": "aaa",
>  "mg": "vvv",
>  "ch": "zzz",
>  "pw": "kkk",
>  "bp1": "xxx",
>  "bp2": "ooo",
>  "pu1": "bbb",
>  "pu2": "ccc"
> }
>
> it can still be edited by a human.

Thanks Peter!

You made it a lot easier than I thought it would be. Please see
 for the script's current incarnation.
The text of the demo data file is quoted in the script, lines 6-13. It
doesn't seem I need to use the json module, though I want to learn it
eventually.

The data file very easily edited. However, as the number of lines gets
large (maybe 100?) I'll need a way to determine if the new key is
already in the file. So I'll be working on a script that I can use to
safely add lines to the the file, by keeping all the keys unique.

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


Re: [Tutor] a quick Q: built-in method pop of list object at 0x7f8221a22cb0>

2011-09-08 Thread Steven D'Aprano

lina wrote:

Hi,





what does the 0x7f8221a22cb0 mean here? the computer physical address.


That's the ID of the list object, converted to hexadecimal.

Every object in Python gets a unique (for the life of the object) ID. In 
CPython, the version you are using, that ID happens to be the memory 
address, and can be reused. For Jython and IronPython, the ID is an 
auto-incrementing counter, and will never be re-used:


first object created gets ID 1
second object gets ID 2
third object gets ID 3
...
etc.



--
Steven

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


Re: [Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread Steven D'Aprano

lina wrote:

Hi,

I failed to understand the "collpase" meaning in a string.

can someone give me a simple example?

Sorry,



I don't understand what you mean. Can you give context?



--
Steven




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


Re: [Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread Alan Gauld

On 08/09/11 14:02, lina wrote:

Hi,

I failed to understand the "collpase" meaning in a string.

can someone give me a simple example?


Can you give us some context?
Its not a method of a string object so far as I can tell?
Where did you read about it?

--
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] a quick Q: built-in method pop of list object at 0x7f8221a22cb0>

2011-09-08 Thread Alan Gauld

On 08/09/11 13:59, lina wrote:



what does the 0x7f8221a22cb0 mean here? the computer physical address.


It's a unique identifier for the object which is implementation 
dependant. In practice you can consider it the memory address.


But I wouldn't try using it as an address by passing it into a
C function say. That's not guaranteed to work at all!


--
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 advice about a dictionary ({})

2011-09-08 Thread Alan Gauld

On 08/09/11 11:58, Richard D. Moores wrote:

I've succeeded in writing a dictionary ({}) that I can use as a small
personal phone book. The dictionary (very shortened and simplified)
looks like this in the script;

p = {}

p['bp1'] = 'xxx'
p['bp2'] = 'ooo'
p['ch'] = 'zzz'
p['me'] = 'aaa'
p['mg'] = 'vvv'
p['pu1'] = 'bbb'
p['pu2'] = 'ccc'
p['pw'] = 'kkk'



You could have done that in one line if you preferred:

> p = {
 'bp1':'xxx',
 'bp2':'ooo'
   etc/...
 'pw':'kkk'
}



But I'd like to put the lines of the dictionary in a text file so that
I can add key/value items to it by writing to it with another script.


Consider using a shelve (See the shelve module)
It is basically a file that you can treat as a dictionary...

Try:

>>> import shelve
>>> help(shelve)

For examples and info.


--
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


[Tutor] throwing exception across modules?

2011-09-08 Thread James Hartley
This is more a design question.

One lesson C++ programmers might learn is that throwing exceptions from
within library code is fraught with problems because the internals of
exception handling were spelled out in the C++ standard.  This manifests
itself as problems when the library was compiled with one vendor's compiler,
but the user of the library is using another compiler.

While I understand that Python doesn't suffer from this exact problem, are
there other reasons that raising exceptions in a module only be caught by
consumers of the module a bad idea?

Any insight which can be shared would be most appreciated.

Thanks.

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


Re: [Tutor] a quick Q: built-in method pop of list object at 0x7f8221a22cb0>

2011-09-08 Thread lina
Thanks, this is very informative.

open some windows for me.



On Thu, Sep 8, 2011 at 9:58 PM, Alan Gauld  wrote:
> On 08/09/11 13:59, lina wrote:
>>
>> 
>>
>> what does the 0x7f8221a22cb0 mean here? the computer physical address.
>
> It's a unique identifier for the object which is implementation dependant.
> In practice you can consider it the memory address.
>
> But I wouldn't try using it as an address by passing it into a
> C function say. That's not guaranteed to work at all!
>
>
> --
> 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
>



-- 
Best Regards,

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


Re: [Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread lina
On Thu, Sep 8, 2011 at 9:59 PM, Alan Gauld  wrote:
> On 08/09/11 14:02, lina wrote:
>>
>> Hi,
>>
>> I failed to understand the "collpase" meaning in a string.
>>
>> can someone give me a simple example?
>
> Can you give us some context?
> Its not a method of a string object so far as I can tell?
> Where did you read about it?

>From "dive into python",

http://diveintopython.org/

one example:

def info(object, spacing=10, collapse=1):
"""Print methods and docs strings.

Take modules, class, list, dictionary, or strong."""
methodList = [e for e in dir(object) if callable(getattr(object, e))]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print "\n".join(["%s %s" %
(method.ljust(spacing),
processFunc(str(getattr(object, method).__doc__)))
for method in methodList])

if __name__ == "__main__":
print info.__doc__

I felt so hard to understand the collapse,

Please don't discourage me telling me it's an old book,
To me I started reading till 42 pages. let me finish it.

I used to study python on and off,
sometimes give a whole week, but due to not using it,
so
it's frustrating that when I really needed it, I barely could complete one.

>
> --
> 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
>



-- 
Best Regards,

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


Re: [Tutor] throwing exception across modules?

2011-09-08 Thread Steven D'Aprano

James Hartley wrote:

This is more a design question.

One lesson C++ programmers might learn is that throwing exceptions from
within library code is fraught with problems because the internals of
exception handling were spelled out in the C++ standard.  This manifests


Do you mean "weren't spelled out"?



itself as problems when the library was compiled with one vendor's compiler,
but the user of the library is using another compiler.

While I understand that Python doesn't suffer from this exact problem, are
there other reasons that raising exceptions in a module only be caught by
consumers of the module a bad idea?


Not at all. Python is designed to use exceptions as the primary error 
mechanism. Nearly every module and function you will use in Python will 
use exceptions to signal errors.


A few will also use exceptions to signal non-error exceptional cases, 
e.g. StopIteration is used by iterators when they run out of items.


Exceptions in Python aren't bolted on the top, they are fundamental to 
the way the language works. Even things like for loops work by catching 
exceptions.




Any insight which can be shared would be most appreciated.


The only thing which sometimes catches out beginners is that they forget 
to use fully-qualified names for exceptions. E.g. you may need to do this:


import socket
try:
...
except socket.error:
...


instead of just "except error".

If possible, document which exceptions your code might throw. At least, 
document which exceptions you expect to throw under normal circumstances.


An exception in the top level of your module will be treated as fatal: 
it will prevent the module from being imported. (When I say fatal, I 
mean fatal for your module, not the caller: the caller can always catch 
the exception and skip the import.)


Think carefully about what exceptions you should use. Try to integrate 
with the standard Python exception hierarchy. See the docs for further 
details.


It's a matter of opinion whether you should use built-in exceptions 
as-is, or whether you subclass them. Subclassing can be as simple as:


class StatsError(ValueError):
pass

or as complicated as you want. But in general, keep exceptions simple.

Try not to raise private exceptions where the caller will see them. In 
other words, if you define a private exception type by flagging the name 
with a leading single underscore:


class _InternalUseOnly(TypeError):  # single underscore means "private"
pass

then never raise it unless you also catch it.



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


Re: [Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread Andre Engels
On Thu, Sep 8, 2011 at 4:16 PM, lina  wrote:

> On Thu, Sep 8, 2011 at 9:59 PM, Alan Gauld 
> wrote:
> > On 08/09/11 14:02, lina wrote:
> >>
> >> Hi,
> >>
> >> I failed to understand the "collpase" meaning in a string.
> >>
> >> can someone give me a simple example?
> >
> > Can you give us some context?
> > Its not a method of a string object so far as I can tell?
> > Where did you read about it?
>
> >From "dive into python",
>
> http://diveintopython.org/
>
> one example:
>
> def info(object, spacing=10, collapse=1):
>"""Print methods and docs strings.
>
>Take modules, class, list, dictionary, or strong."""
>methodList = [e for e in dir(object) if callable(getattr(object, e))]
>processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s:
> s)
>print "\n".join(["%s %s" %
>(method.ljust(spacing),
>processFunc(str(getattr(object, method).__doc__)))
>for method in methodList])
>
> if __name__ == "__main__":
>print info.__doc__
>
> I felt so hard to understand the collapse,
>
> Please don't discourage me telling me it's an old book,
> To me I started reading till 42 pages. let me finish it.
>
> I used to study python on and off,
> sometimes give a whole week, but due to not using it,
> so
> it's frustrating that when I really needed it, I barely could complete one.
>

Reading this, it seems that 'collapse' is a variable defined somewhere else
in the code.

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread Joel Goldstick
On Thu, Sep 8, 2011 at 10:36 AM, Andre Engels  wrote:

> On Thu, Sep 8, 2011 at 4:16 PM, lina  wrote:
>
>> On Thu, Sep 8, 2011 at 9:59 PM, Alan Gauld 
>> wrote:
>> > On 08/09/11 14:02, lina wrote:
>> >>
>> >> Hi,
>> >>
>> >> I failed to understand the "collpase" meaning in a string.
>> >>
>> >> can someone give me a simple example?
>> >
>> > Can you give us some context?
>> > Its not a method of a string object so far as I can tell?
>> > Where did you read about it?
>>
>> >From "dive into python",
>>
>> http://diveintopython.org/
>>
>> one example:
>>
>> def info(object, spacing=10, collapse=1):
>>"""Print methods and docs strings.
>>
>>Take modules, class, list, dictionary, or strong."""
>>methodList = [e for e in dir(object) if callable(getattr(object, e))]
>>processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda
>> s: s)
>>print "\n".join(["%s %s" %
>>(method.ljust(spacing),
>>processFunc(str(getattr(object, method).__doc__)))
>>for method in methodList])
>>
>> if __name__ == "__main__":
>>print info.__doc__
>>
>> I felt so hard to understand the collapse,
>>
>> Please don't discourage me telling me it's an old book,
>> To me I started reading till 42 pages. let me finish it.
>>
>> I used to study python on and off,
>> sometimes give a whole week, but due to not using it,
>> so
>> it's frustrating that when I really needed it, I barely could complete
>> one.
>>
>
> Reading this, it seems that 'collapse' is a variable defined somewhere else
> in the code.
>
> --
> André Engels, andreeng...@gmail.com
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
> collapse is a function that Mark must have described earlier in the chapter
you are working on.  Are you using the online version? which chapter



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


Re: [Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread Joel Goldstick
On Thu, Sep 8, 2011 at 10:48 AM, Joel Goldstick wrote:

>
> On Thu, Sep 8, 2011 at 10:36 AM, Andre Engels wrote:
>
>> On Thu, Sep 8, 2011 at 4:16 PM, lina  wrote:
>>
>>> On Thu, Sep 8, 2011 at 9:59 PM, Alan Gauld 
>>> wrote:
>>> > On 08/09/11 14:02, lina wrote:
>>> >>
>>> >> Hi,
>>> >>
>>> >> I failed to understand the "collpase" meaning in a string.
>>> >>
>>> >> can someone give me a simple example?
>>> >
>>> > Can you give us some context?
>>> > Its not a method of a string object so far as I can tell?
>>> > Where did you read about it?
>>>
>>> >From "dive into python",
>>>
>>> http://diveintopython.org/
>>>
>>> one example:
>>>
>>> def info(object, spacing=10, collapse=1):
>>>"""Print methods and docs strings.
>>>
>>>Take modules, class, list, dictionary, or strong."""
>>>methodList = [e for e in dir(object) if callable(getattr(object, e))]
>>>processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda
>>> s: s)
>>>print "\n".join(["%s %s" %
>>>(method.ljust(spacing),
>>>processFunc(str(getattr(object, method).__doc__)))
>>>for method in methodList])
>>>
>>> if __name__ == "__main__":
>>>print info.__doc__
>>>
>>> I felt so hard to understand the collapse,
>>>
>>> Please don't discourage me telling me it's an old book,
>>> To me I started reading till 42 pages. let me finish it.
>>>
>>> I used to study python on and off,
>>> sometimes give a whole week, but due to not using it,
>>> so
>>> it's frustrating that when I really needed it, I barely could complete
>>> one.
>>>
>>
>> Reading this, it seems that 'collapse' is a variable defined somewhere
>> else in the code.
>>
>> --
>> André Engels, andreeng...@gmail.com
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>> collapse is a function that Mark must have described earlier in the
> chapter you are working on.  Are you using the online version? which chapter
>
> I spoke too soon.  collapse is a boolean variable that you set if you want
> to have the code in the lamda function collapse the text.  If it is False
> then the statement returns false instead of whatever is going on in the
> Lambda
>


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


Re: [Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread Steven D'Aprano

lina wrote:


one example:

def info(object, spacing=10, collapse=1):
"""Print methods and docs strings.

Take modules, class, list, dictionary, or strong."""
methodList = [e for e in dir(object) if callable(getattr(object, e))]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print "\n".join(["%s %s" %
(method.ljust(spacing),
processFunc(str(getattr(object, method).__doc__)))
for method in methodList])



In this example, "collapse" is used as the name of an argument which 
takes a true/false flag. If collapse is true, runs of whitespace is 
collapsed into a single space:


"hello world" => "hello world"

The above function would be much easier to understand if it was written 
like this:


def info(object, spacing=10, collapse=1):
"""Print methods and docs strings.

Take modules, class, list, dictionary, or string.
"""
method_names = []
doc_strings = []
for name in dir(object):
attribute = getattr(object, name)
if callable(attribute):
method_names.append(name.ljust(spacing))
doc_strings.append(str(attribute.__doc__))
if collapse:
doc_strings = [" ".join(doc.split()) for doc in doc_strings]
parts = ["%s %s" % (n, d) for n,d in zip(method_names, doc_strings)]
print "\n".join(parts)



Much longer, but easier to follow for a beginner.



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


Re: [Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread lina
<... ... >
>> collapse is a function that Mark must have described earlier in the
>> chapter you are working on.  Are you using the online version? which chapter
>>

http://diveintopython.org/power_of_introspection/optional_arguments.html

>> I spoke too soon.  collapse is a boolean variable that you set if you want
>> to have the code in the lamda function collapse the text.  If it is False

collapse the text means? destory the text? make it collapse?

Thanks,

>> then the statement returns false instead of whatever is going on in the
>> Lambda
>
>
> --
> Joel Goldstick
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Best Regards,

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


Re: [Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread Steven D'Aprano

lina wrote:


collapse the text means? destory the text? make it collapse?


Collapse runs of spaces into a single space.



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


Re: [Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread lina
On Thu, Sep 8, 2011 at 11:03 PM, Steven D'Aprano  wrote:
> lina wrote:
>
>> collapse the text means? destory the text? make it collapse?
>
> Collapse runs of spaces into a single space.

That's what I want, thanks.  ^_^
>
>
>
> --
> Steven
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Best Regards,

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


Re: [Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread Marc Tompkins
On Thu, Sep 8, 2011 at 8:08 AM, lina  wrote:

> On Thu, Sep 8, 2011 at 11:03 PM, Steven D'Aprano 
> wrote:
> > lina wrote:
> >
> >> collapse the text means? destory the text? make it collapse?
> >
> > Collapse runs of spaces into a single space.
>
> That's what I want, thanks.  ^_^
>

Be aware that that meaning of "collapse" is not a standard Python term -
it's just the word that the author chose to describe this function.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread lina
On Thu, Sep 8, 2011 at 11:17 PM, Marc Tompkins  wrote:
> On Thu, Sep 8, 2011 at 8:08 AM, lina  wrote:
>>
>> On Thu, Sep 8, 2011 at 11:03 PM, Steven D'Aprano 
>> wrote:
>> > lina wrote:
>> >
>> >> collapse the text means? destory the text? make it collapse?
>> >
>> > Collapse runs of spaces into a single space.
>>
>> That's what I want, thanks.  ^_^
>
> Be aware that that meaning of "collapse" is not a standard Python term -
> it's just the word that the author chose to describe this function.

Thanks for reminding.

Sometimes it's not so easy to realize which part I should focus to
understand well.

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



-- 
Best Regards,

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


Re: [Tutor] a quick Q: what does the "collapse" mean?

2011-09-08 Thread Peter Otten
Steven D'Aprano wrote:

> lina wrote:
> 
>> one example:
>> 
>> def info(object, spacing=10, collapse=1):
>> """Print methods and docs strings.
>> 
>> Take modules, class, list, dictionary, or strong."""
>> methodList = [e for e in dir(object) if callable(getattr(object, e))]
>> processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda
>> s: s) print "\n".join(["%s %s" %
>> (method.ljust(spacing),
>> processFunc(str(getattr(object, method).__doc__)))
>> for method in methodList])
> 
> 
> In this example, "collapse" is used as the name of an argument which
> takes a true/false flag. If collapse is true, runs of whitespace is
> collapsed into a single space:
> 
> "hello world" => "hello world"
> 
> The above function would be much easier to understand if it was written
> like this:
> 
> def info(object, spacing=10, collapse=1):
>  """Print methods and docs strings.
> 
>  Take modules, class, list, dictionary, or string.
>  """
>  method_names = []
>  doc_strings = []
>  for name in dir(object):
>  attribute = getattr(object, name)
>  if callable(attribute):
>  method_names.append(name.ljust(spacing))
>  doc_strings.append(str(attribute.__doc__))
>  if collapse:
>  doc_strings = [" ".join(doc.split()) for doc in doc_strings]
>  parts = ["%s %s" % (n, d) for n,d in zip(method_names, doc_strings)]
>  print "\n".join(parts)
> 
> 
> 
> Much longer, but easier to follow for a beginner.

Or even

def info(object, spacing=10, collapse=True):
 for name in dir(object):
 attribute = getattr(object, name)
 if callable(attribute):
 doc = str(attribute.__doc__)
 if collapse:
 doc = " ".join(doc.split())
 print name.ljust(spacing), doc


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


Re: [Tutor] need advice about a dictionary ({})

2011-09-08 Thread James Reynolds
On Thu, Sep 8, 2011 at 10:03 AM, Alan Gauld wrote:

> On 08/09/11 11:58, Richard D. Moores wrote:
>
>> I've succeeded in writing a dictionary ({}) that I can use as a small
>> personal phone book. The dictionary (very shortened and simplified)
>> looks like this in the script;
>>
>> p = {}
>>
>> p['bp1'] = 'xxx'
>> p['bp2'] = 'ooo'
>> p['ch'] = 'zzz'
>> p['me'] = 'aaa'
>> p['mg'] = 'vvv'
>> p['pu1'] = 'bbb'
>> p['pu2'] = 'ccc'
>> p['pw'] = 'kkk'
>>
>>
> You could have done that in one line if you preferred:
>
> > p = {
>  'bp1':'xxx',
>  'bp2':'ooo'
>   etc/...
>  'pw':'kkk'
>
> }
>
>
>  But I'd like to put the lines of the dictionary in a text file so that
>> I can add key/value items to it by writing to it with another script.
>>
>
> Consider using a shelve (See the shelve module)
> It is basically a file that you can treat as a dictionary...
>
> Try:
>
> >>> import shelve
> >>> help(shelve)
>
> For examples and info.
>
>
> --
> 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
>



Another option would be for you to use XML and base it off of a schema.

There's a really nifty tool called generate DS (just google it) that will
turn any valid schema into a python module.

I pasted an example schema that you might use here:
http://pastebin.com/AVgVGpgu

 Once you install generateds, just cd to where it is installed and type:
python generateds.py -o pn.py PhoneNumber.xsd

This assumes you named the above schema as PhoneNumber.xsd

That will create a file called pn.py. For some reason it generated a bad
line on line 452, which I just commented out.

I then made a script in just a few lines to make a phonebook:

http://pastebin.com/h4JB0MkZ

This outputs XML that looks like this:


> 
> aaa
> 
> 1231231234
> 
> 
> 
> bbb
> 
> 1231231234
> 
> 
> 6789231234
> 
> 
> 
> ccc
> 
> 1231231234
> 
> 
> 
> ddd
> 
> 1231231234
> 
> 
> 


The advantage is, you can immediately grab the generated xml and create
python instances using the build() method for further editing. You would of
course need to create a schema that fits your needs. Mine was just a quick
and dirty example of what you could do.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Tkinter Entry field text

2011-09-08 Thread brandon w
How do you display text in a Entry field and have it disappear when a 
person clicks in it?


This is what I have so far:


from Tkinter import *

root = Tk()
root.title("Password Changer")
root.geometry("300x300+600+250")

label1 = Label(root, text="Enter you password: ")
label1.grid(sticky=W, row=0, column=0)

enter_data1 = Entry(root, bg = "pale green")
enter_data1.grid(row=0, column=1)
enter_data1.insert(0, "password")

root.mainloop()


To get text into this box the person must first delete what is already 
in there.


Python 2.6.6

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


[Tutor] Flat is better than Nested

2011-09-08 Thread Ryan Strunk
Hello everyone,
I am still learning to program by writing this boxing game. I'm running into
a problem with how to organize data. My current setup looks something like
this:
"""This feels incredibly disgusting to me."""
self.behaviors = {
'offensive_combos': {
'combo1': {
1: { #time in seconds
'punch': {
'speed': 2,
'strength': 4,
'side': 'left'}
}
1.5: { #time in seconds
'punch': {
'speed': 4,
'strength': 8,
'side': 'right'}
}
}
}
}
By the time I write this all into a file, the end user will never even know
this crazy hierarchy exists, but I will, and I don't like it. Do I just need
to get over it and realize that sometimes nested is necessary, or is there a
better way I might consider?
Thanks for any help you can provide.
Best,
Ryan

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


Re: [Tutor] Flat is better than Nested

2011-09-08 Thread Steven D'Aprano

Ryan Strunk wrote:

Hello everyone,
I am still learning to program by writing this boxing game. I'm running into
a problem with how to organize data. My current setup looks something like
this:
"""This feels incredibly disgusting to me."""



You might find it a little less disgusting with the application of some 
helper classes and a slightly different data format.


Combos probably should be treated as a sequence of moves. For 
simplicity, I'm going to assume each move takes the same time, and once 
a combo is entered, the opponent can't interrupt it. You may want to 
make it more complicated/realistic.



The hard part is deciding what fields you need. Here's my guess:


class Move:
   def __init__(self, speed, strength, side, purpose, kind, foul=False):
   self.speed = speed
   self.strength = strength
   self.side = side
   self.purpose = purpose
   self.kind = kind
   self.foul = foul


CENTRE = NEUTRAL = ''
LEFT, RIGHT = 'left right'.split()
ATTACK, DEFENSE = 'attack defense'.split()

right_cross = Move(2, 3, RIGHT, ATTACK, 'punch')
left_lead = Move(3, 4, LEFT, ATTACK, 'punch')
left_jab = Move(1, 1, LEFT, ATTACK, 'punch')
headbutt = Move(1, 3, CENTRE, ATTACK, 'headbutt', True)
step_in = Move(2, 0, NEUTRAL, NEUTRAL, 'footwork')
weave = Move(1, 0, NEUTRAL, DEFENSE, 'footwork')
rabbit_punch = Move(1, 2, CENTRE, ATTACK, 'punch', True)

class Combo:
def __init__(self, *moves):
self.moves = moves


old_one_two = Combo(left_lead, right_cross)
liverpool_kiss = Combo(step_in, headbutt)


combos = {
1: old_one_two,
2: liverpool_kiss,
3: Combo(weave, weave, step_in, rabbit_punch),
4: Combo(left_jab, left_jab, left_jab, step_in, uppercut),
}


Does that help?




--
Steven

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