[CentralOH] Syntactic Sugar (or sacharine)?
Issac Kelly
issac.kelly at gmail.com
Fri Aug 12 19:12:36 CEST 2011
You could do something like this:
>>> class Settings(object):
... internal_dict = {
... 'min': 4,
... 'max': 8,
... }
... def __getattr__(self, attr):
... return self.internal_dict[attr]
... def __setattr__(self, attr, value):
... self.internal_dict[attr] = value
...
>>> s = Settings()
>>> s.min
4
>>> s.max
8
>>> s.min = 5
>>> s.min
5
http://stackoverflow.com/questions/42558/python-and-the-singleton-pattern
And then you could make it a singleton if you need (or not)
On Fri, Aug 12, 2011 at 12:55 PM, Brandon Craig Rhodes <
brandon.craig.rhodes at gmail.com> wrote:
> Mark Erbaugh <mark at microenh.com> writes:
>
> > I accidentally initialized the dict with {min:0} rather than
> > {'min':0}, but the former worked as the built-in function min is
> > hashable ... I'm thinking it's marginally faster as there's no string
> > processing involved.
>
> An interesting hypothesis! You should run a test with the "timeit"
> module to see whether it is truly faster.
>
> My guess is that it is *not* actually faster, because all of the strings
> that appear as literals in your Python code are "interned" strings - no
> matter how many times the literal string 'min' appears in your program,
> CPython creates only a single string object that gets used over and
> over. And interned strings are, like functions, compared by identity -
> the check for d['min'] will, just like d[min], be reduced immediately to
> an extremely fast pointer comparison operation.
>
> But run timeit anyway, because I could be wrong! :)
>
> --
> Brandon Craig Rhodes brandon at rhodesmill.org
> http://rhodesmill.org/brandon
> _______________________________________________
> CentralOH mailing list
> CentralOH at python.org
> http://mail.python.org/mailman/listinfo/centraloh
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/mailman/private/centraloh/attachments/20110812/bc4ed297/attachment.html>
More information about the CentralOH
mailing list