Re: [Tutor] object attribute validation
On Fri, Feb 22, 2013 at 10:31 PM, Steven D'Aprano wrote: > On 23/02/13 10:50, neubyr wrote: > >> I would like to validate data attributes before the object is instantiated >> or any changes thereafter. For example, following is a simple Person class >> with name and age attributes. I would like to validate whether age is an >> integer before it is added/changed in the object's dictionary. I have >> taken >> a simple integer validation example, but it could be something like >> DateField validation or X509 certificate validation as well. Following is >> my example code: >> >> >> class Person(object): >>def __init__(self,name,age): >> self.name = name >> self.age = age >> >>def get_age(self): >> return self._age >> >>def set_age(self,val): >> try: >>int(val) >>self._age = val >> except ValueError: >> raise Exception('Invalid value for age') >> > > The setter is unnecessarily complicated. Just let the ValueError, or > TypeError, or any other error, propagate: > > def set_age(self,val): > self._age = int(val) > > > This will allow the user to pass ages as strings, which I assume you want > because that's what your code above does. instance.age = "6" will set the > age to the int 6. If all you want to accept are ints, and nothing else: > > > def set_age(self,val): > if isinstance(val, int): > self._age = val > else: > raise TypeError('expected an int, but got %r' % val) > > > > > def del_age(self): >> del self._age >> >>age = property(get_age,set_age,del_**age) >> > > > In general, you would leave out the property deleter. I find that in > general if you're validating attributes, you want them to be present and > valid, so deleting should be an error. > > > -- > Steven > > Thank you for your comments Steven. Yes, I think I should remove property deleter in this case. I would like to use this Person class in another class. For example, if Person class is 'model' in a small MVC-style web application, then where should I place my validation. A view form will be passing parameters to a controller which will create and write Person objects/models. Should the validation be in place at all three levels? I am inclined towards adding integer validation in views, but I am not sure where should I add it in a controller class. Also, it's easy to add integer validation in view form (javascript), but what if I have a more complex format - X509 certificate or some other file-type related validation? Is it OK to validate them only in property setter methods? -- N ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] object attribute validation
I would like to validate data attributes before the object is instantiated or any changes thereafter. For example, following is a simple Person class with name and age attributes. I would like to validate whether age is an integer before it is added/changed in the object's dictionary. I have taken a simple integer validation example, but it could be something like DateField validation or X509 certificate validation as well. Following is my example code: class Person(object): def __init__(self,name,age): self.name = name self.age = age def get_age(self): return self._age def set_age(self,val): try: int(val) self._age = val except ValueError: raise Exception('Invalid value for age') def del_age(self): del self._age age = property(get_age,set_age,del_age) a = Person('John',6) b = Person('Johny','Six') Is this a good approach? Any suggestions for improving the code or alternative approaches would be helpful. -- thanks, neubyr ___ 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
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/pickle/index.html> >>>> http://www.doughellmann.com/**PyMOTW/shelve/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
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
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
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
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<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
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
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<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
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<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
[Tutor] associating two objects without ORM and processing a text file
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. thanks, N ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] classes : post-declaration attributes
On Sat, Feb 9, 2013 at 3:24 AM, Alan Gauld wrote: > On 09/02/13 07:01, neubyr wrote: > >> >> I am learning Python 2.7 classes and objects. It seems like attributes >> (data attributes and methods) can be added to a class/object even after >> it's first declaration. For example, >> > > You can do that, but mostly you shouldn't. > > Usually when classes/objects are used like that its where the object is > just being used as a data container rather than a true object (with > behaviour and supporting data). Often a straight dictionary is a better > option. > > Python allows us lots of freedom in how we use it with many unusual > features. Not all of those things are advisable to use in day to day > programming. But very occasionally you find a case where they help. > In general, beginners should avoid them. > > > Thanks for the reply Alan, Steven and Mitya. That's helpful. -- N ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] classes : post-declaration attributes
I am learning Python 2.7 classes and objects. It seems like attributes (data attributes and methods) can be added to a class/object even after it's first declaration. For example, class A(object): def __init__(self,arg): self.val1 = arg a = A(1) print a.val1 Now another data attribute val2 can be added as: a.val2 = 2 A.val2 = 22 I understand that all attributes are stored in a dictionary, but I am not following when adding an attribute after initial declaration approach should be used. The official documentation also suggests that valid attributes are all the names present when the class object was created [1]. So does it mean post-declaration attributes are invalid? Why are they allowed to be created then (any special use cases/examples)? 1. http://docs.python.org/2/tutorial/classes.html -- thanks, N ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] importing modules and packages
On Mon, Oct 31, 2011 at 4:38 AM, Steven D'Aprano wrote: > neubyr wrote: >> >> Is it possible to tell whether import statement is importing a module >> or package? I am going through some example code with some import >> statements - like 'import os, sys, time', 'import packed'. I know os, >> sys and time are (built-in) modules and 'packed' is a package here . >> But can I determine whether it's a package or module using any >> command/method or by following some naming convention? > > Consider: > >>>> import curses # A package. >>>> curses.__file__ > '/usr/lib/python2.5/curses/__init__.pyc' >>>> curses.__path__ > ['/usr/lib/python2.5/curses'] > > > Compare to: > >>>> import string # A plain module. >>>> string.__file__ > '/usr/lib/python2.5/string.pyc' >>>> string.__path__ > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute '__path__' > > > > Does this help? > > That's helpful. Thanks a lot.. - neuby.r ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] importing modules and packages
Is it possible to tell whether import statement is importing a module or package? I am going through some example code with some import statements - like 'import os, sys, time', 'import packed'. I know os, sys and time are (built-in) modules and 'packed' is a package here . But can I determine whether it's a package or module using any command/method or by following some naming convention? - thanks, neuby.r ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor