Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-16 Thread Steven D'Aprano

On 16/02/13 19:32, eryksun wrote:

On Sat, Feb 16, 2013 at 1:21 AM, Steven D'Aprano  wrote:

while atexit can be set anywhere and isn't obvious. It's also somewhat
risky, since you never know when some library you import will silently
replace it with their own hook.


Use try/finally if the task is clearer that way. atexit is better
suited to libraries. logging uses atexit (flushing/closing handlers)
as does multiprocessing (terminating/joining active child processes).

As to the risk, atexit was added in 2.0 and directly using
sys.exitfunc was deprecated in 2.4.



Ah yes, atexit doesn't *replace* the hook, it allows multiple hooks.
Correction noted.



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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-16 Thread eryksun
On Sat, Feb 16, 2013 at 1:21 AM, Steven D'Aprano  wrote:
> while atexit can be set anywhere and isn't obvious. It's also somewhat
> risky, since you never know when some library you import will silently
> replace it with their own hook.

Use try/finally if the task is clearer that way. atexit is better
suited to libraries. logging uses atexit (flushing/closing handlers)
as does multiprocessing (terminating/joining active child processes).

As to the risk, atexit was added in 2.0 and directly using
sys.exitfunc was deprecated in 2.4.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-15 Thread Steven D'Aprano

On 15/02/13 16:38, eryksun wrote:

On Thu, Feb 14, 2013 at 4:33 PM, Prasad, Ramit
  wrote:

My knee jerk response is a try/finally block, but I am sure there
are better ways.


The atexit.register decorator hooks sys.exitfunc:

http://docs.python.org/2/library/atexit



I find a try...finally block more readable and obvious than a hidden
atexit function. At least the try...finally block is explicit:


try:
main()
finally:
do_stuff()


while atexit can be set anywhere and isn't obvious. It's also somewhat
risky, since you never know when some library you import will silently
replace it with their own hook.

Also, keep in mind that you can't rely on atexit hooks to run. Or the
finally block for that matter. They can fail to run when:


- the Python process is killed from the outside, say using "kill -9"
  under Linux;

- or the entire computer goes down, say after a power failure;

- or the operating system crashes and takes everything else down;

- or something calls os._exit() while your code is running, say some
  external library.


So if you're serious about saving data, you cannot afford to wait until
the program quits before saving the user's work. You should be saving
whenever the user makes some change.



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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-15 Thread Alan Gauld

On 15/02/13 03:09, neubyr wrote:


I do have a doubt regarding this - e.g. how would I implement this if my
program/application is web based. For example, loading the text file
during web server start and stop.


For a long running process like a web server this is probably the wrong 
approach. You probably want to save the data more regularly - maybe even 
at the end of every user transaction. But with a web server we have the 
additional problem of usually wanting to handle multiple requests in 
parallel so storing data in memory gets more complicated - which takes 
us back to using a data base which pretty much handles all of that for you.


If you will only have a single request running at a time then you can 
use the same try/finally approach in your transaction processing code. 
But because they run  so often I'd add the 'dirty flag' idea that 
somebody else mentioned too so that you don;t sabve if no changes have 
been made.


A dirty flag is simply a global (or class) level variable (isDirty) that 
gets set by your code anytime you change the data. If a book changes its 
state it sets the flag to True. The save code then does something like


with open(filename) as store
   if Book.isDirty:
  for book in Book.instances:
  book.save(store)

That will ensure that any changes are saved but we don't waste time
if no changes exist.

--
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] associating two objects without ORM and processing a text file

2013-02-14 Thread eryksun
On Thu, Feb 14, 2013 at 4:33 PM, Prasad, Ramit
 wrote:
> My knee jerk response is a try/finally block, but I am sure there
> are better ways.

The atexit.register decorator hooks sys.exitfunc:

http://docs.python.org/2/library/atexit

Registered atexit functions are run early during interpreter
finalization. Signal handling is still enabled (e.g. SIGINT), and you
can still import. In the standard lib, logging and multiprocessing use
atexit.

In a C extension there's also Py_AtExit for registering a C function:

http://docs.python.org/2/c-api/sys.html#Py_AtExit

Calling the exitfuncs is the last task in Py_Finalize, after
everything has been torn down, so they should not use the C-API.

Example:

import atexit
from tempfile import NamedTemporaryFile
from subprocess import Popen, PIPE
from ctypes import CDLL, pythonapi

@atexit.register
def f():
print "shutdown: atexit"

# register a C function
with NamedTemporaryFile() as so:
p = Popen(['gcc', '-xc', '-shared', '-fPIC', '-o',
   so.name, '-'], stdin=PIPE, stdout=so)
p.communicate('''#include 
  void fc(void) {printf("shutdown: Py_AtExit\\n");}''')
fc = CDLL(so.name).fc # keep reference
pythonapi.Py_AtExit(fc)

try:
raise RuntimeError
finally:
print "shutdown: finally"

Output:

shutdown: finally
Traceback (most recent call last):
  File "atexit_example.py", line 20, in 
raise RuntimeError
RuntimeError
shutdown: atexit
shutdown: Py_AtExit
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-14 Thread neubyr
On Thu, Feb 14, 2013 at 4:05 PM, Dave Angel  wrote:

> On 02/14/2013 04:33 PM, Prasad, Ramit wrote:
>
>> Dave Angel wrote:
>>
>>> On 02/14/2013 12:35 PM, Prasad, Ramit wrote:
>>>
 neubyr wrote:

> I am not sure how to save an object in memory to a file before exiting
> the program. Any examples or
> related documentation links would be really helpful. I am guessing it
> would be using some kind of
> before teardown method, but not sure about it. Any help?
>

 Look at the pickle or shelve modules.
 http://www.doughellmann.com/**PyMOTW/pickle/index.html
 http://www.doughellmann.com/**PyMOTW/shelve/index.html


>>> You miss the point.  The OP wants to make sure the text file is saved no
>>> matter how the program happens to exit.  He's not asking how to format
>>> the file.
>>>
>>>
>> Hmm. Good point Dave, I did miss that point.
>>
>> My knee jerk response is a try/finally block, but I am sure there
>> are better ways.
>>
>> # UNTESTED
>> stored_data = {}
>> try:
>>  stored_data = load_data()
>>  while True:
>>  #
>> except Exception:
>>  raise # reraise exception to keep trace and still
>># propogate error for attention
>> finally:
>>  store_data(stored_data) # Save data since we are exiting
>>  # (intentionally or not).
>>
>
> That would be my reaction as well.  I would, however make it conditional
> on some changes having been made.  That way if this program run only made
> queries, the effort and risk of saving can be avoided.
>
> The other thing I'd recommend is to store the data in an alternate file,
> and only delete the original when the alternate is ready to rename. That
> way, you can't readily get into trouble if something crashes while saving.
>
>
>
>
>
Thanks Ramit and Dave!

I haven't had chance to code/learn further, but I will give play with this
soon.

I do have a doubt regarding this - e.g. how would I implement this if my
program/application is web based. For example, loading the text file during
web server start and stop.

Hope to try it out soon!


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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-14 Thread neubyr
On Wed, Feb 13, 2013 at 1:55 PM, Alan Gauld wrote:

> On 13/02/13 19:14, neubyr wrote:
>
>  I am not sure how to save an object in memory to a file
>> before exiting the program. Any examples or related documentation links
>> would be really helpful. I am guessing it would be using some kind of
>> before teardown method, but not sure about it. Any help?
>>
>
> If using class methods or standalone functions just call them explicitly
> at the start and end of your program. If you want to
> be sure it gets called use a try/finally
>
> try:
>Book.loadBooks(filename)  # load the data
># do your program stuff
> finally:
>Book.saveBooks(filename)   # save the data
>
> That ensures that even if there is an exception the data will always be
> saved.
>
>
>

Thanks Alan!

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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-14 Thread Dave Angel

On 02/14/2013 04:33 PM, Prasad, Ramit wrote:

Dave Angel wrote:

On 02/14/2013 12:35 PM, Prasad, Ramit wrote:

neubyr wrote:

I am not sure how to save an object in memory to a file before exiting the 
program. Any examples or
related documentation links would be really helpful. I am guessing it would be 
using some kind of
before teardown method, but not sure about it. Any help?


Look at the pickle or shelve modules.
http://www.doughellmann.com/PyMOTW/pickle/index.html
http://www.doughellmann.com/PyMOTW/shelve/index.html



You miss the point.  The OP wants to make sure the text file is saved no
matter how the program happens to exit.  He's not asking how to format
the file.



Hmm. Good point Dave, I did miss that point.

My knee jerk response is a try/finally block, but I am sure there
are better ways.

# UNTESTED
stored_data = {}
try:
 stored_data = load_data()
 while True:
 #
except Exception:
 raise # reraise exception to keep trace and still
   # propogate error for attention
finally:
 store_data(stored_data) # Save data since we are exiting
 # (intentionally or not).


That would be my reaction as well.  I would, however make it conditional 
on some changes having been made.  That way if this program run only 
made queries, the effort and risk of saving can be avoided.


The other thing I'd recommend is to store the data in an alternate file, 
and only delete the original when the alternate is ready to rename. 
That way, you can't readily get into trouble if something crashes while 
saving.




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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-14 Thread Prasad, Ramit
Dave Angel wrote:
> On 02/14/2013 12:35 PM, Prasad, Ramit wrote:
> > neubyr wrote:
> >> I am not sure how to save an object in memory to a file before exiting the 
> >> program. Any examples or
> >> related documentation links would be really helpful. I am guessing it 
> >> would be using some kind of
> >> before teardown method, but not sure about it. Any help?
> >
> > Look at the pickle or shelve modules.
> > http://www.doughellmann.com/PyMOTW/pickle/index.html
> > http://www.doughellmann.com/PyMOTW/shelve/index.html
> >
> 
> You miss the point.  The OP wants to make sure the text file is saved no
> matter how the program happens to exit.  He's not asking how to format
> the file.
> 

Hmm. Good point Dave, I did miss that point. 

My knee jerk response is a try/finally block, but I am sure there 
are better ways.

# UNTESTED
stored_data = {}
try:
stored_data = load_data()
while True:
#
except Exception:
raise # reraise exception to keep trace and still
  # propogate error for attention
finally:
store_data(stored_data) # Save data since we are exiting
# (intentionally or not).


~Ramit


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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-14 Thread Dave Angel

On 02/14/2013 12:35 PM, Prasad, Ramit wrote:

neubyr wrote:

I am not sure how to save an object in memory to a file before exiting the 
program. Any examples or
related documentation links would be really helpful. I am guessing it would be 
using some kind of
before teardown method, but not sure about it. Any help?


Look at the pickle or shelve modules.
http://www.doughellmann.com/PyMOTW/pickle/index.html
http://www.doughellmann.com/PyMOTW/shelve/index.html



You miss the point.  The OP wants to make sure the text file is saved no 
matter how the program happens to exit.  He's not asking how to format 
the file.




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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-14 Thread Prasad, Ramit
neubyr wrote:
> I am not sure how to save an object in memory to a file before exiting the 
> program. Any examples or
> related documentation links would be really helpful. I am guessing it would 
> be using some kind of
> before teardown method, but not sure about it. Any help?

Look at the pickle or shelve modules.
http://www.doughellmann.com/PyMOTW/pickle/index.html
http://www.doughellmann.com/PyMOTW/shelve/index.html

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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-13 Thread Alan Gauld

On 13/02/13 19:14, neubyr wrote:


I am not sure how to save an object in memory to a file
before exiting the program. Any examples or related documentation links
would be really helpful. I am guessing it would be using some kind of
before teardown method, but not sure about it. Any help?


If using class methods or standalone functions just call them explicitly 
at the start and end of your program. If you want to

be sure it gets called use a try/finally

try:
   Book.loadBooks(filename)  # load the data
   # do your program stuff
finally:
   Book.saveBooks(filename)   # save the data

That ensures that even if there is an exception the data will always be 
saved.


--
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] associating two objects without ORM and processing a text file

2013-02-13 Thread neubyr
On Tue, Feb 12, 2013 at 4:56 PM, Steven D'Aprano wrote:

> On 13/02/13 04:32, neubyr wrote:
>
>  I am not following your comment on opening books file twice in
>> list_by_author method. I have opened it only once and then reading each
>> line while checking for a regex match. Am I missing something?
>>
>
>
> You open the catalog file once to read the books in the first place.
>
> Then when you want a list of books by author Fred, you open the catalog
> file, even though all the books are (somewhere) in memory.
>
> Then when you want a list of books by author Bob, you open the catalog
> file again. Then when you want a list of books by Sally, you open the
> catalog file yet again. And so on.
>
>
>
>
Thank you for your feedback Dave and Steven.

I realize that I am opening the file for every add/delete call. I thought
you were referring to duplicate file open call within the code snippet
itself.

I am not sure how to save an object in memory to a file before exiting the
program. Any examples or related documentation links would be really
helpful. I am guessing it would be using some kind of before teardown
method, but not sure about it. Any help?

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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-12 Thread Steven D'Aprano

On 13/02/13 04:32, neubyr wrote:


I am not following your comment on opening books file twice in
list_by_author method. I have opened it only once and then reading each
line while checking for a regex match. Am I missing something?



You open the catalog file once to read the books in the first place.

Then when you want a list of books by author Fred, you open the catalog
file, even though all the books are (somewhere) in memory.

Then when you want a list of books by author Bob, you open the catalog
file again. Then when you want a list of books by Sally, you open the
catalog file yet again. And so on.


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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-12 Thread Dave Angel

On 02/12/2013 12:32 PM, neubyr wrote:

On Mon, Feb 11, 2013 at 7:34 PM, Steven D'Aprano wrote:





I am not following your comment on opening books file twice in
list_by_author method. I have opened it only once and then reading each
line while checking for a regex match. Am I missing something?



Not tiwce, 490 times.  Each time you call that method, you're going to 
open and read the whole file?  Why on earth would you do that, rather 
than just storing the Book instances in a list for later perusal?  Read 
the file when starting, and save it when quitting.  You did say you were 
going to be inserting and deleting books, right?  You sure don't want to 
write that code to manage a text file.



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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-12 Thread neubyr
On Mon, Feb 11, 2013 at 7:34 PM, Steven D'Aprano wrote:

> On 12/02/13 10:16, Alan Gauld wrote:
>
>> On 11/02/13 22:49, neubyr wrote:
>>
>>  is right approach to implement 'list_by_author' function as a class
>>> method is typically used as an alternative constructor.
>>>
>>
>> Not at all that is only one use case for class methods.
>> A class method is *any* method that operates on the whole class of
>> objects - i.e. all instances(potentially including those still to be
>> created)
>>
>
>
> Strictly speaking, a class method is just a method which takes as its
> first argument the class itself, not the instance. What it does with
> that is completely open.
>
> The usual thing is to use class methods for alternative constructors,
> e.g. Decimal.fromfloat.
>
> If the class keeps a list of all instances, then the class method
> could walk the list and operate on each instance in turn. (But why
> would you do that?)
>
> If the class method modifies the class itself, then it could indirectly
> have an effect on each instance.
>
> Although class methods could do anything, it is hard to think of
> actually useful things for them to do apart from being used as a
> constructor.
>
> [...]
>
>  Here I am
>>> returning list of objects and not just an object.
>>>
>>
>> Which is to say a subset of the class Book.
>> Therefore quite reasonably a class method.
>>
>
> Just a minute, I think that is completely wrong. A Book is not a set,
> so how can you have subset of it?
>
> What is a subset of "Pride and Prejudice"? Perhaps chapter 5.
>
> There are more problems with this idea that you query the Book to get
> a list of books by some author. Suppose you did this:
>
> prpr = Book("Pride and Prejudice", "Jane Austin")
> prpr.list_by_author()
>
> Now *each and every* book is responsible for tracking all the other
> books by the same author. This is a lousy design. Even worse:
>
> prpr.list_by_author("Jane Austin")
>
>
> since now books are responsible for tracking ALL books by ALL authors,
> since the caller could say:
>
> prpr.list_by_author("Leo Tolstoy")
>
>
> Of course, books should know their own author, not the authors of other
> books, but authors should know all their own books:
>
> author = prpr.author  # --> Author("Jane Austin")
>
> author.get_books()  # --> return a list of books by this author
>
>
> This is an argument for making Authors a class, with behaviour, rather
> than just a string.
>
>
>
>  @classmethod
>>> def list_by_author(self,author):
>>> """ Return list of books of an author """
>>> bookfile = config.bookfile
>>> books = [] # empty list - used as list of Books
>>>
>> [snip]
>
>
> First off, by convention the first argument to a class method should be
> called "cls", not "self".
>
> Secondly, here you are relying on a mysterious global "config", which
> points to a bookfile. What does this have to do with a book?
>
> - Does a nail keep track of the packet it came from?
>
> - Why should a book keep track of the catalog it was listed in?
>
> This should be a top level function, not a Book method.
>
> The rest of the method's design is also poor. You have already read
> the file once, to get the initial set of books. So why read the file
> again, every time you want to get some piece of information.
>
> Big databases, capable of holding billions of pieces of data, have
> to use disk-based storage because you can't keep that much data in
> memory at once. For anything smaller, you should only read and write
> to disk for persistence, everything else should use in-memory data
> structures. In this case, that means a dict.
>
>
>
>  return books # return list of books
>>>
>>
> Really? Thank goodness for the comment, I wouldn't have understood
> that line of code otherwise!
>
> *wink*
>
>
>
:)

Thank you for your inputs Steven. I will keep your suggestions in mind
while refactoring this code.

I am not following your comment on opening books file twice in
list_by_author method. I have opened it only once and then reading each
line while checking for a regex match. Am I missing something?

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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-12 Thread eryksun
On Mon, Feb 11, 2013 at 8:56 PM, Alan Gauld  wrote:
> (One of the unfortunate features of Python's implementation of
> class methods is that you can call them from an instance which
> doesn't really make sense! IMHO)

Smalltalk derives a metaclass for the class methods, in parallel with
the class. That's an option in Python, if you prefer it. It can hinder
multiple inheritance, however. Using a classmethod object is more
flexible.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-11 Thread Alan Gauld

On 12/02/13 01:34, Steven D'Aprano wrote:


If the class keeps a list of all instances, then the class method
could walk the list and operate on each instance in turn. (But why
would you do that?)


Because its how classes work in some languages (like smalltalk).
The class object represents all instances of the class.


Although class methods could do anything, it is hard to think of
actually useful things for them to do apart from being used as a
constructor.


Again its the norm in Smalltalk apps to implement electors(searches) and 
other class wide operations in the class methods. Most Smalltalk classes 
have at least 5 or 6 class methods.



Which is to say a subset of the class Book.
Therefore quite reasonably a class method.


Just a minute, I think that is completely wrong. A Book is not a set,
so how can you have subset of it?


A Book is an instance of the class Book.
Book is a class of object encompassing all books.
So returning a subset of all instances of the class is normal class 
method behaviour.



What is a subset of "Pride and Prejudice"? Perhaps chapter 5.


That might be a chapter or two? But Pride and Prejudice is not the class 
Book, it's an instance of Book.



There are more problems with this idea that you query the Book to get
a list of books by some author. Suppose you did this:

prpr = Book("Pride and Prejudice", "Jane Austin")
prpr.list_by_author()


No, you don't query the instance, you should query the class.

Book.list_by_author()   # -> a dict of lists keyed by author name?

(One of the unfortunate features of Python's implementation of
class methods is that you can call them from an instance which
doesn't really make sense! IMHO)


Now *each and every* book is responsible for tracking all the other
books by the same author. This is a lousy design. Even worse:

prpr.list_by_author("Jane Austin")

since now books are responsible for tracking ALL books by ALL authors,


Which is why it should be a class method not an instance one.
And in the real world we'd do that by building class methods
querying a database.


Of course, books should know their own author, not the authors of other
books, but authors should know all their own books:


instances should, I agree.

The Book class should know about all books in the class.


First off, by convention the first argument to a class method should be
called "cls", not "self".


Yes, my bad.
Although it is of course only a Python convention.


Secondly, here you are relying on a mysterious global "config", which
points to a bookfile. What does this have to do with a book?


The storage mechanism is an implementation detail. In Smalltalk its part 
of the infrastructure of the runtime.



- Does a nail keep track of the packet it came from?


No, but the nail factory may keep track of the nails it
produces, or at least the batches...


- Why should a book keep track of the catalog it was listed in?


A book wouldn't. but the Book class might.


The rest of the method's design is also poor. You have already read
the file once, to get the initial set of books. So why read the file
again, every time you want to get some piece of information.


This I agree with. It would be better to persist the data somewhere for 
a small dataset.


--
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] associating two objects without ORM and processing a text file

2013-02-11 Thread Steven D'Aprano

On 12/02/13 10:16, Alan Gauld wrote:

On 11/02/13 22:49, neubyr wrote:


is right approach to implement 'list_by_author' function as a class
method is typically used as an alternative constructor.


Not at all that is only one use case for class methods.
A class method is *any* method that operates on the whole class of
objects - i.e. all instances(potentially including those still to be
created)



Strictly speaking, a class method is just a method which takes as its
first argument the class itself, not the instance. What it does with
that is completely open.

The usual thing is to use class methods for alternative constructors,
e.g. Decimal.fromfloat.

If the class keeps a list of all instances, then the class method
could walk the list and operate on each instance in turn. (But why
would you do that?)

If the class method modifies the class itself, then it could indirectly
have an effect on each instance.

Although class methods could do anything, it is hard to think of
actually useful things for them to do apart from being used as a
constructor.

[...]

Here I am
returning list of objects and not just an object.


Which is to say a subset of the class Book.
Therefore quite reasonably a class method.


Just a minute, I think that is completely wrong. A Book is not a set,
so how can you have subset of it?

What is a subset of "Pride and Prejudice"? Perhaps chapter 5.

There are more problems with this idea that you query the Book to get
a list of books by some author. Suppose you did this:

prpr = Book("Pride and Prejudice", "Jane Austin")
prpr.list_by_author()

Now *each and every* book is responsible for tracking all the other
books by the same author. This is a lousy design. Even worse:

prpr.list_by_author("Jane Austin")


since now books are responsible for tracking ALL books by ALL authors,
since the caller could say:

prpr.list_by_author("Leo Tolstoy")


Of course, books should know their own author, not the authors of other
books, but authors should know all their own books:

author = prpr.author  # --> Author("Jane Austin")

author.get_books()  # --> return a list of books by this author


This is an argument for making Authors a class, with behaviour, rather
than just a string.



@classmethod
def list_by_author(self,author):
""" Return list of books of an author """
bookfile = config.bookfile
books = [] # empty list - used as list of Books

[snip]


First off, by convention the first argument to a class method should be
called "cls", not "self".

Secondly, here you are relying on a mysterious global "config", which
points to a bookfile. What does this have to do with a book?

- Does a nail keep track of the packet it came from?

- Why should a book keep track of the catalog it was listed in?

This should be a top level function, not a Book method.

The rest of the method's design is also poor. You have already read
the file once, to get the initial set of books. So why read the file
again, every time you want to get some piece of information.

Big databases, capable of holding billions of pieces of data, have
to use disk-based storage because you can't keep that much data in
memory at once. For anything smaller, you should only read and write
to disk for persistence, everything else should use in-memory data
structures. In this case, that means a dict.



return books # return list of books


Really? Thank goodness for the comment, I wouldn't have understood
that line of code otherwise!

*wink*



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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-11 Thread neubyr
On Mon, Feb 11, 2013 at 6:58 PM, Steven D'Aprano wrote:

> On 11/02/13 16:14, neubyr wrote:
>
>> I have a text file with each line in following format:
>>
>> Book Name, Author Name, Genre, Publication Date
>>
>> I would like to perform following queries on this file:
>>   * Get all books written by an author
>>   * Remove all books of an author
>>   * Get information about a book (pretty print matching line!)
>>   * Get books of particular genre
>>
>> Also, I would like to add and delete entries in this file. I am not
>> planning to use any database for this purpose and would like to get better
>> grasp on file parsing and classes/OOP. I need some help in creating
>> classes
>> and following are my initial thoughts:
>>
>> # Create a class for Book object
>> class Book:
>>atributes: name, author_name, genre, publication-date
>>
>
>
> You could use a class. But since Books don't have any behaviour, a simple
> struct or record would be better than a class:
>
>
> from collections import namedtuple
> Book = namedtuple("Book", "name author genre date")
>
> lotr = Book("The Hobbit", "J.R.R. Tolkien", "Fantasy", "1937")
>
>
> This has the advantage of simplicity. But if you need to add behaviour to
> the
> Book class, e.g. validation of the fields, you should be able to inherit
> from
> a named tuple. Untested:
>
>
> class Book(namedtuple("Book", "name author genre date")):
> @property
> def genre(self):
> return super(Book, self).genre
> @genre.setter(self, value):
> super(Book, self).genre = value.title()  # 'fantasy' -> 'Fantasy'
>
>
>
>  # Create
>> Author:
>>   attribute(s): name
>>
>
>
> As Alan suggested, a waste of time. Since the Author has no behaviour and
> only a single field, why not just use a string?
>
>
>
>
>  # Create class for reading and writing to the file
>> class Booksfile:
>>methods: ??
>>
>
> Why should this be a class? This is not Java.
>
> http://steve-yegge.blogspot.**com.au/2006/03/execution-in-**
> kingdom-of-nouns.html
>
>
> Just write a function that reads a file and returns a list of Books.
>
> Or perhaps I should say:
>
>
> Programmer().getwriter().**write(MakeCallable(FileReader)**
> .setmethod("read",
> return_type=list, return_item_values=Book)
>
>
>
>
>  * How do I associate/relate Book and Author classes so that it will help
>> me
>> in getting information like 'get list of books written by an author'? Data
>> attribute?
>>
>
> You want to map authors to books. Whenever you want a mapping, use a dict:
>
>
> data = {
> 'J.R.R. Tolkien': [Book("The Hobbit"), Book("The Lord of the Rings")],
> 'Tom Clancy': [Book("The Hunt for Red October")],
> 'Terry Pratchett': [Book('Small Gods'), Book('Night Watch'),
> Book('Nation')],
> 'Stephenie Meyer': [
> Book('Something about abusive boyfriends but that's okay because
> they sparkle')],
>
> }
>
>
>
>  * Should I create a new Booksfile object for reading, writing and deleting
>> entries in the file OR add corresponding methods to the book object
>> itself?
>>
>
> Heavens no. Why should the book know about the library catalog it is
> listed in?
> Your book class should be responsible for the book, and nothing but the
> book.
>
>
>
>
> --
> Steven
>
>

Thanks Steven!

I have used namedtuple like approach in few Ruby programs (not the same
problem) using Structs, but it didn't strike me for this exercise [1]. I am
going to try this approach soon.

I haven't added any validation methods for fields yet, but I am planning to
add them soon - e.g. validate alphabets or alphanumeric characters etc. It
may bring up new questions from my side, but I am sure you all will be glad
to help.. :)

1. http://www.ruby-doc.org/core-1.9.3/Struct.html

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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-11 Thread Steven D'Aprano

On 11/02/13 16:14, neubyr wrote:

I have a text file with each line in following format:

Book Name, Author Name, Genre, Publication Date

I would like to perform following queries on this file:
  * Get all books written by an author
  * Remove all books of an author
  * Get information about a book (pretty print matching line!)
  * Get books of particular genre

Also, I would like to add and delete entries in this file. I am not
planning to use any database for this purpose and would like to get better
grasp on file parsing and classes/OOP. I need some help in creating classes
and following are my initial thoughts:

# Create a class for Book object
class Book:
   atributes: name, author_name, genre, publication-date



You could use a class. But since Books don't have any behaviour, a simple
struct or record would be better than a class:


from collections import namedtuple
Book = namedtuple("Book", "name author genre date")

lotr = Book("The Hobbit", "J.R.R. Tolkien", "Fantasy", "1937")


This has the advantage of simplicity. But if you need to add behaviour to the
Book class, e.g. validation of the fields, you should be able to inherit from
a named tuple. Untested:


class Book(namedtuple("Book", "name author genre date")):
@property
def genre(self):
return super(Book, self).genre
@genre.setter(self, value):
super(Book, self).genre = value.title()  # 'fantasy' -> 'Fantasy'



# Create
Author:
  attribute(s): name



As Alan suggested, a waste of time. Since the Author has no behaviour and
only a single field, why not just use a string?




# Create class for reading and writing to the file
class Booksfile:
   methods: ??


Why should this be a class? This is not Java.

http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html


Just write a function that reads a file and returns a list of Books.

Or perhaps I should say:


Programmer().getwriter().write(MakeCallable(FileReader).setmethod("read",
return_type=list, return_item_values=Book)




* How do I associate/relate Book and Author classes so that it will help me
in getting information like 'get list of books written by an author'? Data
attribute?


You want to map authors to books. Whenever you want a mapping, use a dict:


data = {
'J.R.R. Tolkien': [Book("The Hobbit"), Book("The Lord of the Rings")],
'Tom Clancy': [Book("The Hunt for Red October")],
'Terry Pratchett': [Book('Small Gods'), Book('Night Watch'),
Book('Nation')],
'Stephenie Meyer': [
Book('Something about abusive boyfriends but that's okay because they 
sparkle')],
}




* Should I create a new Booksfile object for reading, writing and deleting
entries in the file OR add corresponding methods to the book object itself?


Heavens no. Why should the book know about the library catalog it is listed in?
Your book class should be responsible for the book, and nothing but the book.




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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-11 Thread neubyr
On Mon, Feb 11, 2013 at 5:16 PM, Alan Gauld wrote:

> On 11/02/13 22:49, neubyr wrote:
>
>  is right approach to implement 'list_by_author' function as a class
>> method is typically used as an alternative constructor.
>>
>
> Not at all that is only one use case for class methods.
> A class method is *any* method that operates on the whole class of objects
> - i.e. all instances(potentially including those still to be created)
>
> Now I agree that in some lanmguages they tend to be limited to factory
> metjods(eg Objective C implicitly goes that way) but in others  like
> Smalltalk search methods and persistence etc are often found as class
> methods. In Python, because of it's hybrid nature, these are often
> "demoted" to global scope functions.
>
>
>
>  Here I am
>> returning list of objects and not just an object.
>>
>
> Which is to say a subset of the class Book.
> Therefore quite reasonably a class method.
>
>
> @classmethod
>>def list_by_author(self,author):
>>  """ Return list of books of an author """
>>  bookfile = config.bookfile
>>  books = [] # empty list - used as list of Books
>>  # TODO: improve regex
>>  regex = re.compile(author)
>>  with open (bookfile,'r') as f:
>>for line in f:
>>  if regex.findall(line):
>># error prone - if name contains comma
>>l = line.split(',')
>># create book object and append it to a list
>>book = self(*l)
>>books.append(book)
>>  return books # return list of books
>>
>
> I'd probably, for a small dataset, load a list of books into the class at
> startup and save it at termination. Which makes the search code easier and
> potentially can be data driven so you pass the filter attribute as a
> parameter. You can then use getattr() to find the value:
>
> def findBooks(cls, param, value):
> return [book for book in books if getattr(book, param) == value]
>
> You could make it more flexible still by defining the filter as a function
> and passing a lambda:
>
> def findBooks(cls, filterExp):
> return [book for book in books if filterExp(book)]
>
>
> Usage example:
>
> DickensBooks = Book.findBook(lambda b: 'Dickens' in b.author)
>
>
> Of course if you have a huge dataset then that won't work - which brings
> us back to a database :-)
>
>
> HTH
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>


That's really helpful Alan. Thank you for your inputs on class methods and
how can I modify my existing find/list method.

I am not using any database/ORM as I am trying to learn basic search/filter
operations on file and enumerator objects. Also, ORMs generally add magic
methods based on associations (at least with Ruby ActiveRecord: e.g.
has_many and belongs_to associations). I would like to do it 'manually'
before using any other library.

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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-11 Thread Alan Gauld

On 11/02/13 22:49, neubyr wrote:


is right approach to implement 'list_by_author' function as a class
method is typically used as an alternative constructor.


Not at all that is only one use case for class methods.
A class method is *any* method that operates on the whole class of 
objects - i.e. all instances(potentially including those still to be 
created)


Now I agree that in some lanmguages they tend to be limited to factory 
metjods(eg Objective C implicitly goes that way) but in others  like 
Smalltalk search methods and persistence etc are often found as class 
methods. In Python, because of it's hybrid nature, these are often 
"demoted" to global scope functions.




Here I am
returning list of objects and not just an object.


Which is to say a subset of the class Book.
Therefore quite reasonably a class method.


   @classmethod
   def list_by_author(self,author):
 """ Return list of books of an author """
 bookfile = config.bookfile
 books = [] # empty list - used as list of Books
 # TODO: improve regex
 regex = re.compile(author)
 with open (bookfile,'r') as f:
   for line in f:
 if regex.findall(line):
   # error prone - if name contains comma
   l = line.split(',')
   # create book object and append it to a list
   book = self(*l)
   books.append(book)
 return books # return list of books


I'd probably, for a small dataset, load a list of books into the class 
at startup and save it at termination. Which makes the search code 
easier and potentially can be data driven so you pass the filter 
attribute as a parameter. You can then use getattr() to find the value:


def findBooks(cls, param, value):
return [book for book in books if getattr(book, param) == value]

You could make it more flexible still by defining the filter as a 
function and passing a lambda:


def findBooks(cls, filterExp):
return [book for book in books if filterExp(book)]


Usage example:

DickensBooks = Book.findBook(lambda b: 'Dickens' in b.author)


Of course if you have a huge dataset then that won't work - which brings 
us back to a database :-)


HTH

--
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] associating two objects without ORM and processing a text file

2013-02-11 Thread neubyr
On Mon, Feb 11, 2013 at 12:36 PM, Dave Angel  wrote:

> On 02/11/2013 01:19 PM, Alan Gauld wrote:
>
>> On 11/02/13 05:14, neubyr wrote:
>>
>>>
>>> 
>>>
>>>
>>  * How do I associate/relate Book and Author classes so that it will help
>>> me in getting information like 'get list of books written by an author'?
>>> Data attribute?
>>>
>>
>> I woudn't have a separate Author class but, if you must, something like:
>>
>> class Book:
>>def __init__(self, theAuthor,theTitle):
>>self.Author = theAuthor
>>self.title = theTitle
>>
>> class Author:
>>def __init__(self,aName):
>>   self.name = aName
>>
>> myBook = Book(Author('Jane Austin'), 'Pride & Prejudice')
>>
>
> Big problem with that;  then there may be multiple instances of Author,
> representing the same Author.  Instead, there needs to be a factory
> function which reuses the same Author objects if an additional book with
> the same author is encountered.  Without such an approach, one might as
> well stick with strings, which is what we each recommended.
>
>
> --
> DaveA
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>



Thank you for suggestions - Mitya, Dave and Alan.

I am doing it as a learning exercise and it's not a class assignment. I
have little experience with Ruby and now trying to learn Python. It's not
going to be any production application and I haven't thought about
concurrency problems yet.

Based on suggestions, following is a code snippet that I have right now. I
agree that there isn't any need of separate Author object right now, so I
may remove it as well. I have created a class method 'list_by_author' to
return list of books. I am not sure if class method is right approach to
implement 'list_by_author' function as a class method is typically used as
an alternative constructor. Here I am returning list of objects and not
just an object.

Any suggestions for improving this code will be really useful.


class Book(object):
  def __init__(self,name,author,genre,pubdate):
self.name = name
self.author   = author
self.genre= genre
self.pubdate  = pubdate

  # TODO: use csv module
  # write/add method
  def add(self,uname,kname):
""" Write book info to a file """
pass

  @classmethod
  def list_by_author(self,author):
""" Return list of books of an author """
bookfile = config.bookfile
books = [] # empty list - used as list of Books
# TODO: improve regex
regex = re.compile(author)
with open (bookfile,'r') as f:
  for line in f:
if regex.findall(line):
  # error prone - if name contains comma
  l = line.split(',')
  # create book object and append it to a list
  book = self(*l)
  books.append(book)
return books # return list of books



class Author(object):
  def __init__(self,name):
self.name = name

  def books(self):
""" Get list of books """
books = Book.list_by_author(self.name)
return books



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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-11 Thread neubyr
Thank you for your inputs Dave. That's really helpful. Reply in-line below:


On Sun, Feb 10, 2013 at 11:56 PM, Dave Angel  wrote:

> On 02/11/2013 12:14 AM, neubyr wrote:
>
>> I have a text file with each line in following format:
>>
>> Book Name, Author Name, Genre, Publication Date
>>
>> I would like to perform following queries on this file:
>>   * Get all books written by an author
>>   * Remove all books of an author
>>   * Get information about a book (pretty print matching line!)
>>   * Get books of particular genre
>>
>> Also, I would like to add and delete entries in this file. I am not
>> planning to use any database for this purpose and would like to get better
>> grasp on file parsing and classes/OOP.
>>
>
> I take it from this that this is a class assignment, and that neither
> speed nor enormous data capacity nor concurrent operation is a requirement.
>  But your professor may have other requirements that you haven't told us
> about.


Not a class assignment, just picked up this problem as a learning exercise.


>
>
> I need some help in creating classes
>
>> and following are my initial thoughts:
>>
>> # Create a class for Book object
>> class Book:
>>atributes: name, author_name, genre, publication-date
>>
>> # Create
>> Author:
>>   attribute(s): name
>>
>
> Is this in order to save space, since each Book instance can then have a
> reference to an Author object, rather than a reference to a string
> containing the Author's name.
>
> If you deem this class useful, then don't you also want one for Genre ?



Hmm.. I didn't think about saving space by reference an object. I created
separate class thinking from database/ORM perspective. I am not planning to
use it right now anyway, but if I was creating a non-trivial application
with database models then I would have had Books tables, Authors tables
etc..

I think I don't need it here though.



>
>
>
>
>> # Create class for reading and writing to the file
>> class Booksfile:
>>methods: ??
>>
>
> Why ?  Are you transliterating this from Java ?



Scrapped that class - adding add/list/delete methods in Book class. Thanks
for pointing it out.


>
>
>
>>
>> * How do I associate/relate Book and Author classes so that it will help
>> me
>> in getting information like 'get list of books written by an author'? Data
>> attribute?
>>
>
> If performance doesn't matter, then create one list of Book instances, and
> search it for whichever characteristics you like.
>
>
>
>  * Should I create a new Booksfile object for reading, writing and deleting
>> entries in the file OR add corresponding methods to the book object
>> itself?
>>
>
> Neither, a pair of regular functions will do fine.  One that loads when
> you start the program, and another that saves the file when you exit. If
> you really expect to update the file incrementally, deleting entries in it,
> then think hard about your decision to roll your own database.  A text file
> isn't random access.
>
>
>
>> I am not planning to use SQLite or any database and would like to use text
>> file only. Appreciate any help on designing such application.
>>
>>
>>
> The real question is where you might proceed after meeting these first
> requirements.  For example, if you expect the list to grow to a few hundred
> million entries, then you'll need to be very careful about layout.  And
> starting and exiting the program would be very slow, since you can do
> nothing till all the data has been loaded in and converted to objects.
>
> Or perhaps you'll want to have another file with additional author data,
> associated with the first by carefully spelling the author's name the same
> in all cases.  In that case, having a separate Author class makes great
> sense.  So if you expect to grow in that direction, then you should create
> the class now, even though it has only one attribute.
>
>
> --
> DaveA
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>


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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-11 Thread Dave Angel

On 02/11/2013 01:19 PM, Alan Gauld wrote:

On 11/02/13 05:14, neubyr wrote:







* How do I associate/relate Book and Author classes so that it will help
me in getting information like 'get list of books written by an author'?
Data attribute?


I woudn't have a separate Author class but, if you must, something like:

class Book:
   def __init__(self, theAuthor,theTitle):
   self.Author = theAuthor
   self.title = theTitle

class Author:
   def __init__(self,aName):
  self.name = aName

myBook = Book(Author('Jane Austin'), 'Pride & Prejudice')


Big problem with that;  then there may be multiple instances of Author, 
representing the same Author.  Instead, there needs to be a factory 
function which reuses the same Author objects if an additional book with 
the same author is encountered.  Without such an approach, one might as 
well stick with strings, which is what we each recommended.



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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-11 Thread Alan Gauld

On 11/02/13 05:14, neubyr wrote:


I have a text file with each line in following format:

Book Name, Author Name, Genre, Publication Date

I would like to perform following queries on this file:
  * Get all books written by an author
  * Remove all books of an author
  * Get information about a book (pretty print matching line!)
  * Get books of particular genre

Also, I would like to add and delete entries in this file. I am not
planning to use any database for this purpose and would like to get
better grasp on file parsing and classes/OOP. I need some help in
creating classes and following are my initial thoughts:

# Create a class for Book object
class Book:
   atributes: name, author_name, genre, publication-date



Yep, that looks like all you need.



# Create
Author:
  attribute(s): name


No idea why you want this. A waste of space ...


# Create class for reading and writing to the file
class Booksfile:
   methods: ??


You do not create classes for functions. The functions are part of the 
class. You can have a list of Books read from the file as an attribute 
of your Books class. Populate it at program startup and write the edited 
list back at termination. (Or any other time you make a

change for improved robustness)


* How do I associate/relate Book and Author classes so that it will help
me in getting information like 'get list of books written by an author'?
Data attribute?


I woudn't have a separate Author class but, if you must, something like:

class Book:
  def __init__(self, theAuthor,theTitle):
  self.Author = theAuthor
  self.title = theTitle

class Author:
  def __init__(self,aName):
 self.name = aName

myBook = Book(Author('Jane Austin'), 'Pride & Prejudice')


* Should I create a new Booksfile object for reading, writing and
deleting entries in the file OR add corresponding methods to the book
object itself?


Instance methods in the Book for reading/writing single lines
Class methods in Book for reading/writing the entire file
(or standalone functions could also be used) into a bookList class 
attribute.



I am not planning to use SQLite or any database and would like to use
text file only. Appreciate any help on designing such application.


As a learning exercise that's fine, for any real world problem it would 
be foolish. This is what databases were built for...


HTH

--
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] associating two objects without ORM and processing a text file

2013-02-10 Thread Dave Angel

On 02/11/2013 12:14 AM, neubyr wrote:

I have a text file with each line in following format:

Book Name, Author Name, Genre, Publication Date

I would like to perform following queries on this file:
  * Get all books written by an author
  * Remove all books of an author
  * Get information about a book (pretty print matching line!)
  * Get books of particular genre

Also, I would like to add and delete entries in this file. I am not
planning to use any database for this purpose and would like to get better
grasp on file parsing and classes/OOP.


I take it from this that this is a class assignment, and that neither 
speed nor enormous data capacity nor concurrent operation is a 
requirement.  But your professor may have other requirements that you 
haven't told us about.


I need some help in creating classes

and following are my initial thoughts:

# Create a class for Book object
class Book:
   atributes: name, author_name, genre, publication-date

# Create
Author:
  attribute(s): name


Is this in order to save space, since each Book instance can then have a 
reference to an Author object, rather than a reference to a string 
containing the Author's name.


If you deem this class useful, then don't you also want one for Genre ?




# Create class for reading and writing to the file
class Booksfile:
   methods: ??


Why ?  Are you transliterating this from Java ?




* How do I associate/relate Book and Author classes so that it will help me
in getting information like 'get list of books written by an author'? Data
attribute?


If performance doesn't matter, then create one list of Book instances, 
and search it for whichever characteristics you like.




* Should I create a new Booksfile object for reading, writing and deleting
entries in the file OR add corresponding methods to the book object itself?


Neither, a pair of regular functions will do fine.  One that loads when 
you start the program, and another that saves the file when you exit. 
If you really expect to update the file incrementally, deleting entries 
in it, then think hard about your decision to roll your own database.  A 
text file isn't random access.




I am not planning to use SQLite or any database and would like to use text
file only. Appreciate any help on designing such application.




The real question is where you might proceed after meeting these first 
requirements.  For example, if you expect the list to grow to a few 
hundred million entries, then you'll need to be very careful about 
layout.  And starting and exiting the program would be very slow, since 
you can do nothing till all the data has been loaded in and converted to 
objects.


Or perhaps you'll want to have another file with additional author data, 
associated with the first by carefully spelling the author's name the 
same in all cases.  In that case, having a separate Author class makes 
great sense.  So if you expect to grow in that direction, then you 
should create the class now, even though it has only one attribute.



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


Re: [Tutor] associating two objects without ORM and processing a text file

2013-02-10 Thread Mitya Sirenef

On 02/11/2013 12:14 AM, neubyr wrote:



> I have a text file with each line in following format:
>
> Book Name, Author Name, Genre, Publication Date
>
> I would like to perform following queries on this file:
> * Get all books written by an author
> * Remove all books of an author
> * Get information about a book (pretty print matching line!)
> * Get books of particular genre
>
> Also, I would like to add and delete entries in this file. I am not 
planning to use any database for this purpose and would like to get 
better grasp on file parsing and classes/OOP. I need some help in 
creating classes and following are my initial thoughts:

>
> # Create a class for Book object
> class Book:
> atributes: name, author_name, genre, publication-date
>
> # Create
> Author:
> attribute(s): name
>
> # Create class for reading and writing to the file
> class Booksfile:
> methods: ??
>
>
> * How do I associate/relate Book and Author classes so that it will 
help me in getting information like 'get list of books written by an 
author'? Data attribute?
> * Should I create a new Booksfile object for reading, writing and 
deleting entries in the file OR add corresponding methods to the book 
object itself?

>
> I am not planning to use SQLite or any database and would like to use 
text file only. Appreciate any help on designing such application.

>
>


Book.author should be author instance,

Author
def books(self):
return [b for b in books if b.author==self]

Get lists by genre etc in a similar way.

To do file processing, look at the standard csv module:

http://docs.python.org/2/library/csv.html


-m

--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The doer alone learneth.  Friedrich Nietzsche

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