Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: self.__dict__ tricks

Reply
Thread Tools

Re: self.__dict__ tricks

 
 
Steven D'Aprano
Guest
Posts: n/a
 
      10-30-2009
On Thu, 29 Oct 2009 21:16:37 -0500, Tim Johnson wrote:

> This is not a request for help but a request for comments: Consider the
> following code and note that 1)The initializer uses the dictionary style
> of arguments 2)The check loop executes before all of the class variables
> are declared


Could you explain what problem you are trying to solve?


> class formLoader():


Idiomatic Python is to use CamelCase for classes.


> def __init__(self,**kw):
> self.fileName = None
> self.record = None
> self.string = None
> ## Uncomment below to see that only fileName, record
> ## and string are recorded by __dict__
> #std.debug("self.__dict__",self.__dict__)
> for k in kw.keys():


In recent versions of Python, this is best written as

for k in kw:

> if k in self.__dict__:
> self.__dict__[k] = kw[k]


Is your intention to ensure that the only keyword arguments allowed are
fileName, record and string?

Perhaps the easiest way to do that is:

for k in kw:
if k not in ('filename', 'record', 'string'):
raise Exception() # whatever...
setattr(self, k) = kw[k]



> else:
> raise AttributeError(


In my opinion, AttributeError is not appropriate here. Passing an invalid
parameter shouldn't raise the same error as failing an attribute look-up.
That's misleading and confusing.


> "%s is not a class member. Use one of ('%
> s')" % (repr(k),"', '".join
> (self.__dict__.keys())))


[Aside: eight space tabs are *WAY* too big for Usenet and email. You
should use four spaces, or even two, when posting here.]

It is idiomatic Python to use "instance attributes" to refer to
attributes attached to instances, and "class attributes" to refer to
those attached to classes. Talking about "class members" will confuse
Python developers who aren't also familiar with Java or C++. (I know it
confuses *me* -- are class members shared by all instances in a class, as
the name implies, or are they individual to the instance, as your code
implies?)

I also should point out that your trick will fail if you are using
__slots__.



> self.tokens =

["form","input","textarea","select","option","f orm"]
> self.inputTypes =
> ["button","checkbox","file","hidden","image","passw ord",
> "radio","reset","submit","text"]
> self.inputValTypes = ["file","hidden","password","text"]
> self.colnames
> = [] ## case-insensitive column names
> self.formIndexes = [] ##
> Index forms in outer list



Is any of that relevant to the trick you are asking for comments for? If
not, why is it here?


> I'd welcome comments - such as any other applications.


Personally, I don't like it. The method signature makes it impossible to
tell what arguments are excepted, and it forces me to use keywords even
if I'd prefer to use positional arguments. I prefer to let the
interpreter check the arguments for me:


class FormLoader():
def __init__(self, fileName=None, record=None, string=None):
self.fileName = fileName
self.record = record
self.string = string

That's all it takes, and you get the benefit of a method signature that
makes it obvious what arguments it takes.



--
Steven
 
Reply With Quote
 
 
 
 
Steven D'Aprano
Guest
Posts: n/a
 
      10-30-2009
On Fri, 30 Oct 2009 15:55:04 +1100, Ben Finney wrote:

> Steven D'Aprano <(E-Mail Removed)> writes:
>
>> On Thu, 29 Oct 2009 21:16:37 -0500, Tim Johnson wrote:
>> > class formLoader():

>>
>> Idiomatic Python is to use CamelCase for classes.

>
> Or rather: Instead of camelCase names, idiomatic Python is to use
> TitleCase names.


Thank you for the correction. I always mix up those two.


--
Steven
 
Reply With Quote
 
 
 
 
MRAB
Guest
Posts: n/a
 
      10-30-2009
Steven D'Aprano wrote:
> On Fri, 30 Oct 2009 15:55:04 +1100, Ben Finney wrote:
>
>> Steven D'Aprano <(E-Mail Removed)> writes:
>>
>>> On Thu, 29 Oct 2009 21:16:37 -0500, Tim Johnson wrote:
>>>> class formLoader():
>>> Idiomatic Python is to use CamelCase for classes.

>> Or rather: Instead of camelCase names, idiomatic Python is to use
>> TitleCase names.

>
> Thank you for the correction. I always mix up those two.
>

Wouldn't it be clearer if they were called dromedaryCase and
BactrianCase?
 
Reply With Quote
 
Tim Golden
Guest
Posts: n/a
 
      10-30-2009
MRAB wrote:
> Steven D'Aprano wrote:
>> On Fri, 30 Oct 2009 15:55:04 +1100, Ben Finney wrote:
>>
>>> Steven D'Aprano <(E-Mail Removed)> writes:
>>>
>>>> On Thu, 29 Oct 2009 21:16:37 -0500, Tim Johnson wrote:
>>>>> class formLoader():
>>>> Idiomatic Python is to use CamelCase for classes.
>>> Or rather: Instead of camelCase names, idiomatic Python is to use
>>> TitleCase names.

>> Thank you for the correction. I always mix up those two.
>>

> Wouldn't it be clearer if they were called dromedaryCase and
> BactrianCase?


It's not often I really get a laugh out of this
mailing list, but that really made me chuckle.

Thanks

TJG
 
Reply With Quote
 
Steven D'Aprano
Guest
Posts: n/a
 
      10-31-2009
On Fri, 30 Oct 2009 11:16:29 -0500, Tim Johnson wrote:

> On 2009-10-30, Steven D'Aprano <(E-Mail Removed)>
> wrote:
>>
>> Could you explain what problem you are trying to solve?
>>
>>
>>> class formLoader():

>
> Hi Steve
> In a nutshell:
> The 'problem' is to parse a form in such a way that tags which are to
> be modified are represented as dictionaries. The 'grunt' work is done.
> This class will probably grow with time.


The standard way of doing this is to list the arguments as parameters,
together with their defaults:

def __init__(self, filename=None, record=None, string=None):
...


Then Python will do the error checking for your, and raise an exception
if the caller passes an unexpected argument. Can you explain why this
isn't enough for your needs, and you need to do something else?


>> Idiomatic Python is to use CamelCase for classes.

> Can you point me to a discussion on Idiomatic Python, CamelCase and
> other matters?


See PEP 8:

http://www.python.org/dev/peps/pep-0008/



>> In my opinion, AttributeError is not appropriate here. Passing an
>> invalid parameter shouldn't raise the same error as failing an
>> attribute look-up. That's misleading and confusing.

>
> What error class or other approach do you recommend?


Unless you have a good reason for doing something different, do what
Python built-ins do:

>>> int('123', parrot=16)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'parrot' is an invalid keyword argument for this function


>> I also should point out that your trick will fail if you are using
>> __slots__.

> ??. Will research that. Elaborate if you wish.


__slots__ are an optimization for making objects smaller than normal if
you have many millions of them:

http://docs.python.org/reference/datamodel.html#slots


> If the class grows - and I expect it will - I'd prefer to stick with
> the keywords approach. That approach also allows me to use a
> dictionary to initialize the object.


You can still do that with named parameters.


>>> class Parrot:

.... def __init__(self, name='Polly', colour='blue',
.... breed='Norwegian'):
.... self.name = name
.... self.colour = colour
.... self.breed = breed
.... def speak(self):
.... print "%s the %s %s says 'Give us a kiss!'" % (
.... self.name, self.colour, self.breed)
....
>>> p = Parrot("Sparky", 'white', "Cockatoo")
>>> p.speak()

Sparky the white Cockatoo says 'Give us a kiss!'
>>>
>>> data = dict(colour='red', name='Fred', foo=1)
>>> p = Parrot(**data) # raise an error with bad input

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument 'foo'
>>>
>>> del data['foo'] # fix the bad input
>>> p = Parrot(**data)
>>> p.speak()

Fred the red Norwegian says 'Give us a kiss!'


--
Steven
 
Reply With Quote
 
Hendrik van Rooyen
Guest
Posts: n/a
 
      10-31-2009
On Friday, 30 October 2009 17:28:47 MRAB wrote:

> Wouldn't it be clearer if they were called dromedaryCase and
> BactrianCase?


Ogden Nash:

The Camel has a single hump-
The Dromedary, two;
Or the other way around-
I'm never sure. - Are You?

- Hendrik


 
Reply With Quote
 
MRAB
Guest
Posts: n/a
 
      10-31-2009
Hendrik van Rooyen wrote:
> On Friday, 30 October 2009 17:28:47 MRAB wrote:
>
>> Wouldn't it be clearer if they were called dromedaryCase and
>> BactrianCase?

>
> Ogden Nash:
>
> The Camel has a single hump-
> The Dromedary, two;
> Or the other way around-
> I'm never sure. - Are You?
>

If you make the first letter a capital:

Dromedary starts with "D", 1 bump, 1 hump.

Bactrian starts with "B", 2 bumps, 2 humps.
 
Reply With Quote
 
Steven D'Aprano
Guest
Posts: n/a
 
      11-01-2009
On Sat, 31 Oct 2009 11:15:48 -0500, Tim Johnson wrote:

> Many programmers I know stay away from 'lists' such as this, because
> they are afraid to show their ignorance. Me, I'm fearless, and I have
> learned a lot that I might not have otherwise.


The only stupid question is the one you are afraid to ask.

Good luck!


--
Steven
 
Reply With Quote
 
Aahz
Guest
Posts: n/a
 
      11-03-2009
In article <02fd0c85$0$1326$(E-Mail Removed)>,
Steven D'Aprano <(E-Mail Removed)> wrote:
>On Sat, 31 Oct 2009 11:15:48 -0500, Tim Johnson wrote:
>>
>> Many programmers I know stay away from 'lists' such as this, because
>> they are afraid to show their ignorance. Me, I'm fearless, and I have
>> learned a lot that I might not have otherwise.

>
>The only stupid question is the one you are afraid to ask.


"There are no stupid questions, only stupid people."
--
Aahz ((E-Mail Removed)) <*> http://www.pythoncraft.com/

[on old computer technologies and programmers] "Fancy tail fins on a
brand new '59 Cadillac didn't mean throwing out a whole generation of
mechanics who started with model As." --Andrew Dalke
 
Reply With Quote
 
Simon Brunning
Guest
Posts: n/a
 
      11-03-2009
2009/11/1 Steven D'Aprano <(E-Mail Removed)>:
>
> The only stupid question is the one you are afraid to ask.


I was once asked, and I quote exactly, "are there any fish in the Atlantic sea?"

That's pretty stupid.

--
Cheers,
Simon B.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
[BF2] Tips/Tricks Silverstrand Gaming 19 09-16-2005 01:41 PM
New Cisco Certification Site - Forums, Tips, Tricks, Network Quizes, all free for CCIE, CCNP, CCNA, etc. Postmaster Cisco 0 08-29-2004 11:48 PM
Hello Help me regarding TOPICS and TRICKS Need INFO ON Certification exams .NET MCSD 7 07-08-2004 04:31 PM
Re: Any Mgt Tricks for 4500/6500's.. spreadsheets or databases? Hansang Bae Cisco 1 07-09-2003 06:55 PM



Advertisments