Re: [Tutor] How to use __iter__

2011-08-08 Thread Peter Otten
Jia-Yu Aw wrote:

> How to use __iter__
> Von:
> Jia-Yu Aw 
>   Antwortadresse:
> Jia-Yu Aw 
>   Datum:
> Dienstag, 9. August 2011 03:48:20
>   An:
> tutor@python.org 
>   Gruppen:
> gmane.comp.python.tutor
> Hi all
> 
> I've been learning Classes and have read the documentation on __iter__ but 
still don't understand how it works. I have two pieces of code: the first is 
def __iter__, the second is using __iter__. Instead of being an iterator, 
I'm just using this is a function, which I think is incorrect. Can somebody 
explain __iter__ and, if it's related, next()?

An "iterable" is an object that has an with an __iter__() method. The 
__iter__() method is supposed to return an "iterator", i. e. an object with 
a next() method. The next() method is then called repeatedly until a next() 
call raises a StopIteration. You can think of

for item in items:
do_something_with(item)

as syntactic sugar for

it = items.__iter__()
while True:
try:
item = it.next()
except StopIteration:
break
do_something_with(item)

With that in mind 
> This is the first. But unlike what it says in the triple quotes, I return 
a whole list instead of a single shape:
> 
> def __iter__(self):
> """
> Return an iterator that allows you to iterate over the set of
> shapes, one shape at a time
> """
> import copy
> setCopy = copy.copy(self.set)
> shapeList = []
> while len(setCopy) > 0:
> try:
> y = setCopy[0]
> shapeList.append(y)
> setCopy.remove(y)
> except StopIteration:
> break
> return shapeList

your __iter__() method would become

class MyIter(object):
def __init__(self, items):
self.items = list(items)
def next(self):
if len(self.items) == 0:
raise StopIteration
return self.items.pop(0)

class MyIterable(object):
# ...
def __iter__(self):
return MyIter(self.set)

However, this is a clumsy way to implement an iterable.
One alternative takes advantage of the fact that Python already knows how to 
iterate over a set. 

class MyIterable(object):
def __iter__(self):
for item in self.set:
yield item

Here the "yield" statement turns __iter__() from a function into a 
"generator". Every call of a generator creates a new iterator, i. e. an 
object with a next() method. Every next() call proceeds execution of the 
generator's body until it reaches a yield. Once the end of the body is 
reached next() will raise Stopiterations forever:

>>> def f():
... yield 1
... yield 2
...
>>> g = f()
>>> g.next()
1
>>> g.next()
2
>>> g.next()
Traceback (most recent call last):
  File "", line 1, in 
StopIteration
>>> g.next()
Traceback (most recent call last):
  File "", line 1, in 
StopIteration

A final simplification would be

class MyIterable(object):
def __iter__(self):
return iter(self.set)
 
> The second, how I've used __iter__:
> 
> def findLargest(shapes):
> """
> Returns a tuple containing the elements of ShapeSet with the
>largest area.
> shapes: ShapeSet
> """
> ## TO DO
> 
> areaList = []
> areaDict = {}
> largestDict = {}

Don't do that:
 
> shapeList = shapes.__iter__()
> for s in shapeList:

The for-loop implicitly invokes the __iter__() method. Just loop over the 
original object:

  for s in shapes:
> areaDict[s] = s.area()
> areaList.append(s.area())
> 
> largestArea = max(areaList)
> areaList = [] #re-initialize areaList, cleaning it
> 
> import copy
> dictCopy = copy.copy(areaDict)
> for a in areaDict:
> if areaDict[a] != largestArea:
> del dictCopy[a]
> 
> return tuple(dictCopy)

Side note: you are copying data way to much. Don't! Most occurences of 
copy() only serve to help an experienced Pythonista identify newbie code ;)

As an inspiration here's an alternative implementation:

def find_largest(shapes):
largest_area = max(shape.area() for shape in shapes)
return [shape for shape in shapes if shape.area() == largest_area]



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


Re: [Tutor] Missing in web.py and nosetests

2011-08-08 Thread 李龑
Thanks again.

I add "print os.getcwd()" inside* app.py* and *app_test.py(the nosetests
script)  *and find they are different.
In app.py, the working dir is the whole directory including all
subdirectories, but in app_test.py the working dir is the tests directory
only.
I guess it's due to the working mechanism of the nosetests...

I also checked the permissions of those files, and they are all readable for
everyone :(

But I guess the problem is at the path of the template, the nosetests may
have a different way to know the template path. (But when I change the
pathname to be a absolute path, the nose goes wrong, and even the browser
can't see the webpage :(  ).

I also tried to add a* __init__.py* file into the templates directory, but
nothing different happens...(there is only 500 and AttributeError, "No
template named " + name)


the projects skeleton:
/gothonweb
/bin
__init__.py
app.py
/templates
index.html
hello_form.html
/tests
__init__.py
app_tests.py
tools.py





On Tue, Aug 9, 2011 at 8:02 AM, Steven D'Aprano  wrote:

> 李龑 wrote:
>
>> Thanks Steven.
>>
>> Sorry for trying to discuss nose or templates here :(
>>
>
> No need to be sorry, it isn't forbidden, but you may have more success
> asking help elsewhere.
>
>
>
>  Do you actually have a template called "hello_form"? If not, then my
>>> *guess*
>>> is that this is an *error* (even though it prints F) because you don't
>>> actually have a template called hello_form.
>>>
>>
>> Yes, I have this template, and the app runs well when I manually testing
>> it
>> in a web browser. So I guess the promblem might be that the nose testing
>> system need some kind of special operations to make it know where the
>> template is(but actually I do have a *render =
>> web.template.render("**templates/", base="layout" *in my app which
>> declares
>> the place of the template).
>>
>
>
> Then my guess is that the difference might be because you are calling the
> nose tests from a different working directory than the web browser sees. Can
> you get the app to display os.getcwd(), and then write a test that compares
> the working directory as seen by nose to the working directory as seen by
> the web app? Or change the template location to be an absolute pathname.
>
> Also check the permissions on the templates. Perhaps the template is
> readable by whatever user is running the web server, but not by whatever
> user is running the nose tests.
>
> All these suggestions are wild guesses, you understand.
>
>
> Good luck.
>
>
>
>
> --
> Steven
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>



-- 

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


[Tutor] How to use __iter__

2011-08-08 Thread Jia-Yu Aw
Hi all

I've been learning Classes and have read the documentation on __iter__ but 
still don't understand how it works. I have two pieces of code: the first is 
def __iter__, the second is using __iter__. Instead of being an iterator, I'm 
just using this is a function, which I think is incorrect. Can somebody explain 
__iter__ and, if it's related, next()?

This is the first. But unlike what it says in the triple quotes, I return a 
whole list instead of a single shape:

    def __iter__(self):
        """
        Return an iterator that allows you to iterate over the set of
        shapes, one shape at a time
        """
        import copy
        setCopy = copy.copy(self.set)
        shapeList = []
        while len(setCopy) > 0:
            try:
                y = setCopy[0]
                shapeList.append(y)
                setCopy.remove(y)
            except StopIteration:
                break
        return shapeList

The second, how I've used __iter__:

def findLargest(shapes):
    """
    Returns a tuple containing the elements of ShapeSet with the
       largest area.
    shapes: ShapeSet
    """
    ## TO DO
    
    areaList = []
    areaDict = {}
    largestDict = {}
    
    shapeList = shapes.__iter__()
    for s in shapeList:
        areaDict[s] = s.area()
        areaList.append(s.area())
        
    largestArea = max(areaList)
    areaList = [] #re-initialize areaList, cleaning it

    import copy
    dictCopy = copy.copy(areaDict)
    
    for a in areaDict:
        if areaDict[a] != largestArea:
            del dictCopy[a]

    return tuple(dictCopy)

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


[Tutor] Reprojection tool for vector datasets

2011-08-08 Thread Helen Brown
I am such a novice at this but I have gotten to a place where I am stuck. The 
attachment is what I have done so far but it also has an error for indentation. 
I will be working on that to. I have place comment as to what I want the 
modules to do but that is as far as I can go. Can someone lead me to the finish 
line ? I have four datasets and they are supposed to be reproject to NAD 1983 
UTM Zone 10. Plus I can not have any hard code.

Please explain how I can understand this better.

Thanks to the Python Lovers


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


Re: [Tutor] Missing in web.py and nosetests

2011-08-08 Thread Steven D'Aprano

李龑 wrote:

Thanks Steven.

Sorry for trying to discuss nose or templates here :(


No need to be sorry, it isn't forbidden, but you may have more success 
asking help elsewhere.




Do you actually have a template called "hello_form"? If not, then my *guess*
is that this is an *error* (even though it prints F) because you don't
actually have a template called hello_form.


Yes, I have this template, and the app runs well when I manually testing it
in a web browser. So I guess the promblem might be that the nose testing
system need some kind of special operations to make it know where the
template is(but actually I do have a *render =
web.template.render("templates/", base="layout" *in my app which declares
the place of the template).



Then my guess is that the difference might be because you are calling 
the nose tests from a different working directory than the web browser 
sees. Can you get the app to display os.getcwd(), and then write a test 
that compares the working directory as seen by nose to the working 
directory as seen by the web app? Or change the template location to be 
an absolute pathname.


Also check the permissions on the templates. Perhaps the template is 
readable by whatever user is running the web server, but not by whatever 
user is running the nose tests.


All these suggestions are wild guesses, you understand.


Good luck.



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


Re: [Tutor] Missing in web.py and nosetests

2011-08-08 Thread 李龑
Thanks Steven.

Sorry for trying to discuss nose or templates here :(

Do you actually have a template called "hello_form"? If not, then my *guess*
> is that this is an *error* (even though it prints F) because you don't
> actually have a template called hello_form.

Yes, I have this template, and the app runs well when I manually testing it
in a web browser. So I guess the promblem might be that the nose testing
system need some kind of special operations to make it know where the
template is(but actually I do have a *render =
web.template.render("templates/", base="layout" *in my app which declares
the place of the template).

Think I need to read more on those topics~_~

Thanks.



On Tue, Aug 9, 2011 at 3:02 AM, Steven D'Aprano  wrote:

> 李龑 wrote:
>
>> Hi all,
>>
>> I'm new in python and is learning about testing my little web.py app with
>> nosetests.
>>
>> When the app is running in the web browser, it's ok. And the terminal
>> returns something like "127.0.0.1:51936 - - [08/Aug/2011 23:00:37]
>> "HTTP/1.1
>> GET /hello" - 200 OK"
>>
>> But when I'm trying to test the app with nosetests, it always goes wrong.
>> As
>> I look into the Tracebacks, I guess this is caused by the templates I've
>> used in my app. But I'm not sure what should I do to make the nosetests
>> running right.
>>
>
>
> This is a forum for learning Python, not nose, or your web templating
> system. We can try to help, but you may have better luck on a dedicated nose
> forum, or on the main python-l...@python.org mailing list (also available
> on Usenet comp.lang.python).
>
>
> I don't actually use nose, so it is hard for me to interpret the tracebacks
> you give. My *guess* is that you are reporting one test *error* (a test that
> fails because your code is broken) plus one test *failure* (a test which
> just fails).
>
>
> The first traceback you give seems to be an unexpected error:
>
>
>   File "/Library/Python/2.7/site-**packages/web/template.py", line 993, in
>>> _load_template
>>>raise AttributeError, "No template named " + name
>>> AttributeError: No template named hello_form
>>> F
>>>
>>
> Do you actually have a template called "hello_form"? If not, then my
> *guess* is that this is an *error* (even though it prints F) because you
> don't actually have a template called hello_form.
>
>
> The second traceback seems to be a failing test:
>
>
>  AssertionError: Expected response '200' not in '500 Internal Server Error'
>>>
>>
> Your test expects a 500 Internal Server Error, but you actually get a 200
> OK response. So your test is wrong: it fails for no good reason.
>
>
> But I am not an expert on nose. I might be interpreting these tracebacks
> completely wrong.
>
>
> Aside:
>
> I can't find anything in the nose docs which explain how to read the test
> output except in the trivial case that all the tests pass.
>
> http://packages.python.org/**nose/index.html
>
>
> --
> Steven
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>



-- 

李龑  |  Li Yan
http://about.me/eyeplum
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] gzip

2011-08-08 Thread questions anon
Thank you and I will look into shutils,  below is the code that did work:

import gzip
import os

MainFolder=r"E:/data"

for (path, dirs, files) in os.walk(MainFolder):
for dir in dirs:
print dir
path=path+'/'
for gzfiles in files:
if gzfiles[-3:]=='.gz':
print "dealing with gzfiles:", gzfiles
compressedfiles=os.path.join(path,gzfiles)
f_in=gzip.GzipFile(compressedfiles, "rb")
newFile=f_in.read()
f_out=open(compressedfiles[:-3], "wb")
f_out.write(newFile)
print "end of processing"



On Mon, Aug 8, 2011 at 6:34 PM, Stefan Behnel  wrote:

> questions anon, 08.08.2011 01:57:
>
>  Thank you, I didn't realise that was all I needed.
>> Moving on to the next problem:
>> I would like to loop through a number of directories and decompress each
>> *.gz file and leave them in the same folder but the code I have written
>> only
>> seems to focus on the last folder. Not sure where I have gone wrong.
>> Any feedback will be greatly appreciated.
>>
>>
>> import gzip
>> import os
>>
>> MainFolder=r"D:/DSE_work/temp_**samples/"
>>
>> for (path, dirs, files) in os.walk(MainFolder):
>> for dir in dirs:
>> outputfolder=os.path.join(**path,dir)
>> print "the path and dirs are:", outputfolder
>> for gzfiles in files:
>> print gzfiles
>> if gzfiles[-3:]=='.gz':
>> print 'dealing with gzfiles:', dir, gzfiles
>> f_in=os.path.join(**outputfolder,gzfiles)
>> print f_in
>> compresseddata=gzip.GzipFile(**f_in, "rb")
>> newFile=compresseddata.read()
>> f_out=open(f_in[:-3], "wb")
>> f_out.write(newFile)
>>
>
> Note how "outputfolder" is set and reset in the first inner loop, *before*
> starting the second inner loop. Instead, build the output directory name
> once, without looping over the directories (which, as far as I understand
> your intention, you can ignore completely).
>
> Also, see the shutils module. It has a method that efficiently copies data
> between open file(-like) objects. With that, you can avoid reading the whole
> file into memory.
>
> Stefan
>
> __**_
> 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] Missing in web.py and nosetests

2011-08-08 Thread Steven D'Aprano

李龑 wrote:

Hi all,

I'm new in python and is learning about testing my little web.py app with
nosetests.

When the app is running in the web browser, it's ok. And the terminal
returns something like "127.0.0.1:51936 - - [08/Aug/2011 23:00:37] "HTTP/1.1
GET /hello" - 200 OK"

But when I'm trying to test the app with nosetests, it always goes wrong. As
I look into the Tracebacks, I guess this is caused by the templates I've
used in my app. But I'm not sure what should I do to make the nosetests
running right.



This is a forum for learning Python, not nose, or your web templating 
system. We can try to help, but you may have better luck on a dedicated 
nose forum, or on the main python-l...@python.org mailing list (also 
available on Usenet comp.lang.python).



I don't actually use nose, so it is hard for me to interpret the 
tracebacks you give. My *guess* is that you are reporting one test 
*error* (a test that fails because your code is broken) plus one test 
*failure* (a test which just fails).



The first traceback you give seems to be an unexpected error:


  File "/Library/Python/2.7/site-packages/web/template.py", line 993, in
_load_template
raise AttributeError, "No template named " + name
AttributeError: No template named hello_form
F


Do you actually have a template called "hello_form"? If not, then my 
*guess* is that this is an *error* (even though it prints F) because you 
don't actually have a template called hello_form.



The second traceback seems to be a failing test:


AssertionError: Expected response '200' not in '500 Internal Server Error'


Your test expects a 500 Internal Server Error, but you actually get a 
200 OK response. So your test is wrong: it fails for no good reason.



But I am not an expert on nose. I might be interpreting these tracebacks 
completely wrong.



Aside:

I can't find anything in the nose docs which explain how to read the 
test output except in the trivial case that all the tests pass.


http://packages.python.org/nose/index.html


--
Steven

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


Re: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack

2011-08-08 Thread Prasad, Ramit
>I would suggest using the string format() method to lay out the columns 
>as you want them.  You could use tab, but if your data values vary much, 
>you'll get inconsistent results (i.e., if one row's value goes past the 
>next tab stop).  You'll want to create your own for loop to iterate over 
>the (possibly sorted) list of values, printing each row the way you want it.

+1

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Missing in web.py and nosetests

2011-08-08 Thread 李龑
Hi all,

I'm new in python and is learning about testing my little web.py app with
nosetests.

When the app is running in the web browser, it's ok. And the terminal
returns something like "127.0.0.1:51936 - - [08/Aug/2011 23:00:37] "HTTP/1.1
GET /hello" - 200 OK"

But when I'm trying to test the app with nosetests, it always goes wrong. As
I look into the Tracebacks, I guess this is caused by the templates I've
used in my app. But I'm not sure what should I do to make the nosetests
running right.

Hope some one can tell me what to do next.

Thanks.


PS: The Tracebacks looks like below:

> $ nosetests
> Traceback (most recent call last):
>   File "/Library/Python/2.7/site-packages/web/application.py", line 236, in
> process
> return self.handle()
>   File "/Library/Python/2.7/site-packages/web/application.py", line 227, in
> handle
> return self._delegate(fn, self.fvars, args)
>   File "/Library/Python/2.7/site-packages/web/application.py", line 409, in
> _delegate
> return handle_class(cls)
>   File "/Library/Python/2.7/site-packages/web/application.py", line 384, in
> handle_class
> return tocall(*args)
>   File "/Users/eyeplum/python/projects/gothonweb/bin/app.py", line 14, in
> GET
> return render.hello_form()
>   File "/Library/Python/2.7/site-packages/web/template.py", line 1009, in
> __getattr__
> t = self._template(name)
>   File "/Library/Python/2.7/site-packages/web/template.py", line 1006, in
> _template
> return self._load_template(name)
>   File "/Library/Python/2.7/site-packages/web/template.py", line 993, in
> _load_template
> raise AttributeError, "No template named " + name
> AttributeError: No template named hello_form
> F
> ==
> FAIL: tests.app_tests.test_index
> --
> Traceback (most recent call last):
>   File
> "/Library/Python/2.7/site-packages/nose-1.1.1-py2.7.egg/nose/case.py", line
> 197, in runTest
> self.test(*self.arg)
>   File "/Users/eyeplum/python/projects/gothonweb/tests/app_tests.py", line
> 12, in test_index
> assert_response(resp)
>   File "/Users/eyeplum/python/projects/gothonweb/tests/tools.py", line 6,
> in assert_response
> assert status in resp.status, "Expected response %r not in %r" %
> (status, resp.status)
> AssertionError: Expected response '200' not in '500 Internal Server Error'
> --
> Ran 1 test in 0.083s
> FAILED (failures=1)



And the book I'm learning: http://learnpythonthehardway.org/book/ex51.html


-- 

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


Re: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack

2011-08-08 Thread Steve Willoughby

On 08-Aug-11 02:20, Kayode Odeyemi wrote:

Either way, once you have the list of the keys you want to display,
print them out once as column headings


My concern is how do I print them out as columns, since writer.writerows
is currently lining them out as rows (\n)
Is there a function available for me to do this or do I have to
construct the column structure myself, possibly leveraging
the tab character or just basically construct a while loop and append
spaces to each keys found?


I would suggest using the string format() method to lay out the columns 
as you want them.  You could use tab, but if your data values vary much, 
you'll get inconsistent results (i.e., if one row's value goes past the 
next tab stop).  You'll want to create your own for loop to iterate over 
the (possibly sorted) list of values, printing each row the way you want it.




Thanks

On Mon, Aug 8, 2011 at 9:41 AM, Steve Willoughby mailto:st...@alchemy.com>> wrote:

Either way, once you have the list of the keys you want to display,
print them out once as column headings




--
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde




--
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
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "Object designer" applications - are there any?

2011-08-08 Thread Flynn, Stephen (L & P - IT)
Yup - sounds more like what the final version of my little project will
do. 

 

At the moment, I'm more interested in taking each specific database's
version of it's DDL and converting it to an Oracle version of that DDL,
so initially it's not much more than a text converter which reads in
text describing Sybase tables and spits out DDL describing Oracle
tables.

 

I'll spend a day working out my objects, their methods and properties,
get that all nailed and begin the fun and games in translating my
headspace into Python.

 

I'll inevitably hassling you people as and when I get stuck or want some
advice on the best way to proceed, so I guess by the end of it, you'll
all be as sick of this as I will be. Share the misery...

 

 

S

 



From: ALAN GAULD [mailto:alan.ga...@btinternet.com] 
Sent: Friday, August 05, 2011 4:34 PM
To: Flynn, Stephen (L & P - IT); tutor@python.org
Subject: Re: [Tutor] "Object designer" applications - are there any?

 

 

> > I'm not sure you need OOP for this. 
> I suspect you're correct Alan, but as I'm using this an a learning
> exercise for the language it seemed too good an opportunity to miss 

That's fine so long as we understand why you are going down the OOP
route.

> can relate a table to an "object" in my head quite easily - just need
to
> know how to do it in Python...

OK, So if you can conceptualise a table what are the operations 
you would perform on it?

It sounds like you want to 
- add columns - from a definition file/document?
- generate DDL based on current structure?
- export a definition document?
- Maybe autopopulate the definition from a given database connection?

So the use case nmay be something like:

Create a table connected to the old database.
The table sucks up the metadata from the database and auto-populates
itself with columns(which might be another class with name, type,size
type details)

Create a new Table object targeted at the new database (which might not
exist yet?)
If the table can't auto-populate then feed it the oold table object
which it queries for 
a description. 
The new table then populates its own definition.

Finally get the new table to generate the DDL and populate the new
database.

You might want different table classes each based on different
databases, 
so they populate themselves based on the specific meta language and spit

out a common  description format. They cn then generate their own
dialect 
of DDL too...

Does that seem like a starter?

But really, when working with objects it helps to sit back and think
through 
how you want to use them from the outside rather than thinking about
what 
they look like inside. That way the internals will reflect what's
actually needed 
for the usage rather than some random model of what might be needed.

HTH,

Alan G.

 

Click here
  to report this email
as spam.



This email and any attachment to it are confidential.  Unless you are the 
intended recipient, you may not use, copy or disclose either the message or any 
information contained in the message. If you are not the intended recipient, 
you should delete this email and notify the sender immediately.

Any views or opinions expressed in this email are those of the sender only, 
unless otherwise stated.  All copyright in any Capita material in this email is 
reserved.

All emails, incoming and outgoing, may be recorded by Capita and monitored for 
legitimate business purposes. 

Capita exclude all liability for any loss or damage arising or resulting from 
the receipt, use or transmission of this email to the fullest extent permitted 
by law.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack

2011-08-08 Thread Kayode Odeyemi
>
> Either way, once you have the list of the keys you want to display, print
> them out once as column headings


My concern is how do I print them out as columns, since writer.writerows is
currently lining them out as rows (\n)
Is there a function available for me to do this or do I have to construct
the column structure myself, possibly leveraging
the tab character or just basically construct a while loop and append spaces
to each keys found?

Thanks

On Mon, Aug 8, 2011 at 9:41 AM, Steve Willoughby  wrote:

> Either way, once you have the list of the keys you want to display, print
> them out once as column headings




-- 
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack

2011-08-08 Thread Steve Willoughby

On 08-Aug-11 01:18, Kayode Odeyemi wrote:

Thanks so much. This is exactly what I'm looking for. In addition, since
fields is obviously a dict, I won't want to have to display it's keys
repeatedly. Is there a way to get the keys once, have it displayed and
used as columns, then it's values are displayed beneath it. Something like:

updated tel
20113456
201134510


Sure.  You have to make the assumption that all the dictionaries in your 
list x have the same keys, or iterate over all of them, making a master 
list of all the keys you found.  Either way, once you have the list of 
the keys you want to display, print them out once as column headings, 
then iterate over the list, printing each key's value in the same order 
each time.


Another approach, if it seems like you're stuffing a lot of data into 
complex dictionary structures, is to turn this into a class.  That way 
you can define the attributes of each object and even implement a 
print() method (or at least define __str__() and/or __repr__() methods) 
to print each object sensibly.




--
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
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] gzip

2011-08-08 Thread Stefan Behnel

questions anon, 08.08.2011 01:57:

Thank you, I didn't realise that was all I needed.
Moving on to the next problem:
I would like to loop through a number of directories and decompress each
*.gz file and leave them in the same folder but the code I have written only
seems to focus on the last folder. Not sure where I have gone wrong.
Any feedback will be greatly appreciated.


import gzip
import os

MainFolder=r"D:/DSE_work/temp_samples/"

for (path, dirs, files) in os.walk(MainFolder):
 for dir in dirs:
 outputfolder=os.path.join(path,dir)
 print "the path and dirs are:", outputfolder
 for gzfiles in files:
 print gzfiles
 if gzfiles[-3:]=='.gz':
 print 'dealing with gzfiles:', dir, gzfiles
 f_in=os.path.join(outputfolder,gzfiles)
 print f_in
 compresseddata=gzip.GzipFile(f_in, "rb")
 newFile=compresseddata.read()
 f_out=open(f_in[:-3], "wb")
 f_out.write(newFile)


Note how "outputfolder" is set and reset in the first inner loop, *before* 
starting the second inner loop. Instead, build the output directory name 
once, without looping over the directories (which, as far as I understand 
your intention, you can ignore completely).


Also, see the shutils module. It has a method that efficiently copies data 
between open file(-like) objects. With that, you can avoid reading the 
whole file into memory.


Stefan

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


Re: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack

2011-08-08 Thread Kayode Odeyemi
Thanks so much. This is exactly what I'm looking for. In addition, since
fields is obviously a dict, I won't want to have to display it's keys
repeatedly. Is there a way to get the keys once, have it displayed and used
as columns, then it's values are displayed beneath it. Something like:

updated tel
2011 3456
2011 34510

right now, I'm having it displayed as

updated
2011
tel
3456
updated
2011
tel
34510

I am having the fields being written using a writer like this:

x = {'pk': 1L, 'model': 'trans', 'fields': {'updated': 2011, 'tel': 3456}},
{'pk': 2L, 'model': 'trans2', 'fields': {'updated': 2011, 'tel': 34510}}
writer = csv.writer(response)

for entry in x:
   for key, value in entry.items():
   print key
   if key == "fields":
   for field_key, field_value in value.items():
   d = [field_key] #a list of sequence
   x = [field_value]
   writer.writerow(d)
   writer.writerow(x)
   else:
   print "  %s" % value


On Sun, Aug 7, 2011 at 5:45 PM, Steve Willoughby  wrote:

> On 07-Aug-11 09:17, Steve Willoughby wrote:
>
>  First of all, that's not a dict. It's just a tuple of strings.
>> so, when you say:
>>
>>  #loop through and get the keys of each
>>> for k,v in x:
>>>
>>
>> You'll get one iteration, where k=the first string and v=the second.
>> However, you ignore k and v in all the code that follows, so I'm really
>> confused what you're trying to do here.
>>
>
> I just noticed I glossed over a key point, for that to work you'd need x to
> be a sequence of such tuples.  As it stands there, you'll get an error
> because each element of x is a single string, so it can't pull two values
> out of each of them.
>
>
> --
> 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
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>



-- 
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor