Re: Yet another Python textbook

Discussion in 'Python' started by Chris Angelico, Nov 20, 2012.

  1. On Tue, Nov 20, 2012 at 7:02 PM, Pavel Solin <> wrote:
    > Perhaps you are right. Is there any statistics of how many Python
    > programmers are using 2.7 vs. 3? Most of people I know use 2.7.


    If you're teaching Python, the stats are probably about zero for zero.
    Start them off on Py3 and help move the world forward.

    ChrisA
     
    Chris Angelico, Nov 20, 2012
    #1
    1. Advertising

  2. Chris Angelico

    Guest

    Le mardi 20 novembre 2012 09:09:50 UTC+1, Chris Angelico a écrit :
    > On Tue, Nov 20, 2012 at 7:02 PM, Pavel Solin <> wrote:
    >
    > > Perhaps you are right. Is there any statistics of how many Python

    >
    > > programmers are using 2.7 vs. 3? Most of people I know use 2.7.

    >
    >
    >
    > If you're teaching Python, the stats are probably about zero for zero.
    >
    > Start them off on Py3 and help move the world forward.
    >
    >
    >
    > ChrisA


    --------

    Do not count with me.

    The absurd flexible string representation has practically
    borrowed the idea to propose once Python has a teaching tool.

    jmf
     
    , Nov 20, 2012
    #2
    1. Advertising

  3. On Wed, Nov 21, 2012 at 1:57 AM, <> wrote:
    > Le mardi 20 novembre 2012 09:09:50 UTC+1, Chris Angelico a écrit :
    >> On Tue, Nov 20, 2012 at 7:02 PM, Pavel Solin <> wrote:
    >>
    >> > Perhaps you are right. Is there any statistics of how many Python

    >>
    >> > programmers are using 2.7 vs. 3? Most of people I know use 2.7.

    >>
    >>
    >>
    >> If you're teaching Python, the stats are probably about zero for zero.
    >>
    >> Start them off on Py3 and help move the world forward.
    >>
    >>
    >>
    >> ChrisA

    >
    > --------
    >
    > Do not count with me.
    >
    > The absurd flexible string representation has practically
    > borrowed the idea to propose once Python has a teaching tool.


    To the OP: jmf has an unnatural hatred of Python 3.3 and PEP 393
    strings. Take no notice; the rest of the world sees this as a huge
    advantage. Python is now in a VERY small group of languages (I'm aware
    of just one other) that have absolutely proper Unicode handling *and*
    efficient string handling.

    ChrisA
     
    Chris Angelico, Nov 20, 2012
    #3
  4. On 20/11/2012 21:00, Chris Angelico wrote:
    >
    > To the OP: jmf has an unnatural hatred of Python 3.3 and PEP 393
    > strings. Take no notice; the rest of the world sees this as a huge
    > advantage. Python is now in a VERY small group of languages (I'm aware
    > of just one other) that have absolutely proper Unicode handling *and*
    > efficient string handling.
    >
    > ChrisA
    >


    Rather more polite than the response I've had sitting in my drafts
    folder for several hours. I'm so pleased I didn't send it, I can now
    happily delete it and move on :)

    --
    Cheers.

    Mark Lawrence.
     
    Mark Lawrence, Nov 20, 2012
    #4
  5. On Wed, Nov 21, 2012 at 8:55 AM, Mark Lawrence <> wrote:
    > On 20/11/2012 21:00, Chris Angelico wrote:
    >>
    >>
    >> To the OP: jmf has an unnatural hatred of Python 3.3 and PEP 393
    >> strings. Take no notice; the rest of the world sees this as a huge
    >> advantage. Python is now in a VERY small group of languages (I'm aware
    >> of just one other) that have absolutely proper Unicode handling *and*
    >> efficient string handling.
    >>
    >> ChrisA
    >>

    >
    > Rather more polite than the response I've had sitting in my drafts folder
    > for several hours. I'm so pleased I didn't send it, I can now happily
    > delete it and move on :)


    Polite is good :)

    Incidentally, if anyone else knows of a language that fits the
    description above, I'd be most curious. Maybe we're going to see a
    revolution in language design - with everyone adopting this sort of
    string handling - or in language usage - with everyone adopting Python
    or Pike. Hmm. We're having major security issues with Joomla, I wonder
    how hard it'd be to convince our webmaster to switch to a Python-based
    web framework...

    Dreaming-ly yours,

    ChrisA
     
    Chris Angelico, Nov 20, 2012
    #5
  6. Chris Angelico

    Guest

    Le mardi 20 novembre 2012 22:00:49 UTC+1, Chris Angelico a écrit :
    > On Wed, Nov 21, 2012 at 1:57 AM, <> wrote:
    >

    -----

    > To the OP: jmf has an unnatural hatred of Python 3.3 and PEP 393
    >
    > strings.



    No. Not at all. I'm mainly and deeply disappointed.

    jmf
     
    , Nov 21, 2012
    #6
  7. Chris Angelico

    Guest

    Le mardi 20 novembre 2012 22:00:49 UTC+1, Chris Angelico a écrit :
    > On Wed, Nov 21, 2012 at 1:57 AM, <> wrote:
    >

    -----

    > To the OP: jmf has an unnatural hatred of Python 3.3 and PEP 393
    >
    > strings.



    No. Not at all. I'm mainly and deeply disappointed.

    jmf
     
    , Nov 21, 2012
    #7
  8. On 20/11/2012 4:00 PM, Chris Angelico wrote:
    > On Wed, Nov 21, 2012 at 1:57 AM, <> wrote:
    >> Le mardi 20 novembre 2012 09:09:50 UTC+1, Chris Angelico a écrit :
    >>> On Tue, Nov 20, 2012 at 7:02 PM, Pavel Solin <> wrote:
    >>>
    >>>> Perhaps you are right. Is there any statistics of how many Python
    >>>
    >>>> programmers are using 2.7 vs. 3? Most of people I know use 2.7.
    >>>
    >>>
    >>>
    >>> If you're teaching Python, the stats are probably about zero for zero.
    >>>
    >>> Start them off on Py3 and help move the world forward.
    >>>
    >>>
    >>>
    >>> ChrisA

    >>
    >> --------
    >>
    >> Do not count with me.
    >>
    >> The absurd flexible string representation has practically
    >> borrowed the idea to propose once Python has a teaching tool.

    >
    > To the OP: jmf has an unnatural hatred of Python 3.3 and PEP 393
    > strings. Take no notice; the rest of the world sees this as a huge
    > advantage. Python is now in a VERY small group of languages (I'm aware
    > of just one other) that have absolutely proper Unicode handling *and*
    > efficient string handling.
    >
    > ChrisA
    >

    It's interesting to see that someone else finds the format function to
    be a pain. Perhaps the problem lies with the documentation.

    Colin W.
     
    Colin J. Williams, Nov 21, 2012
    #8
  9. Chris Angelico

    Dave Angel Guest

    On 11/21/2012 05:17 PM, Chris Angelico wrote:
    > <snip>
    >
    >
    > That said, though, I'm just glad that %-formatting is staying. It's an
    > extremely expressive string formatting method, and exists in many
    > languages (thanks to C's heritage). Pike's version is insanely
    > powerful, Python's is more like C's, but all three are compact and
    > convenient.
    >
    > str.format(), on the other hand, is flexible. It strikes me as rather
    > more complicated than a string formatting function needs to be, but
    > that may be a cost of its flexibility.
    >
    >


    Some don't realize that one very powerful use for the .format style of
    working is that it makes localization much more straightforward. With
    the curly brace approach, one can translate the format string into
    another language, and if the parameters have to be substituted in
    another order, it's all in one place.

    Twenty years ago, I implemented such a thing for our product (C++), for
    just that reason. I'm sure that by now, the libraries exist somewhere
    in the C++ stdlibs, or at least in Boost.

    --

    DaveA
     
    Dave Angel, Nov 21, 2012
    #9
  10. Chris Angelico

    Ian Kelly Guest

    On Wed, Nov 21, 2012 at 3:58 PM, Dave Angel <> wrote:
    > Some don't realize that one very powerful use for the .format style of
    > working is that it makes localization much more straightforward. With
    > the curly brace approach, one can translate the format string into
    > another language, and if the parameters have to be substituted in
    > another order, it's all in one place.


    It only matters with positional placeholders, though. You can achieve
    the same thing using named placeholders, which both major formatting
    styles support.
     
    Ian Kelly, Nov 21, 2012
    #10
  11. On Wed, 21 Nov 2012 12:03:30 -0500, Colin J. Williams wrote:

    > On 20/11/2012 4:00 PM, Chris Angelico wrote:


    >> To the OP: jmf has an unnatural hatred of Python 3.3 and PEP 393
    >> strings. Take no notice; the rest of the world sees this as a huge
    >> advantage. Python is now in a VERY small group of languages (I'm aware
    >> of just one other) that have absolutely proper Unicode handling *and*
    >> efficient string handling.
    >>
    >> ChrisA
    >>

    > It's interesting to see that someone else finds the format function to
    > be a pain. Perhaps the problem lies with the documentation.


    This is nothing to do with the format function. Chris, and JMF, is
    talking about the internal representation of strings in Python.

    Python 3.3 fixes a long-running design flaw that causes Unicode strings
    to be buggy (the use of so-called "surrogate pairs" for characters
    outside of the Basic Multilingual Plane), *and* saves up to 75% of the
    memory used by strings (reducing it from up to 4 bytes per character to
    as little as 1 byte per character), but at the cost of a trivially small
    slowdown under some circumstances.

    JMF is obsessed with the idea that Python is destroying Unicode for the
    benefit of the Americans. It's quite sad really.


    --
    Steven
     
    Steven D'Aprano, Nov 21, 2012
    #11
  12. On 21/11/2012 23:21, Joshua Landau wrote:
    > On 21 November 2012 22:17, Chris Angelico <> wrote:
    >
    >> On Thu, Nov 22, 2012 at 4:03 AM, Colin J. Williams <> wrote:
    >>> On 20/11/2012 4:00 PM, Chris Angelico wrote:
    >>>> To the OP: jmf has an unnatural hatred of Python 3.3 and PEP 393
    >>>> strings. Take no notice; the rest of the world sees this as a huge
    >>>> advantage. Python is now in a VERY small group of languages (I'm aware
    >>>> of just one other) that have absolutely proper Unicode handling *and*
    >>>> efficient string handling.
    >>>>
    >>>> ChrisA
    >>>>
    >>> It's interesting to see that someone else finds the format function to

    >> be a
    >>> pain. Perhaps the problem lies with the documentation.

    >>
    >> Hang on, what? I'm not sure where the format function comes in. I was
    >> referring to the underlying representation.
    >>
    >> That said, though, I'm just glad that %-formatting is staying. It's an
    >> extremely expressive string formatting method, and exists in many
    >> languages (thanks to C's heritage). Pike's version is insanely
    >> powerful, Python's is more like C's, but all three are compact and
    >> convenient.
    >>
    >> str.format(), on the other hand, is flexible. It strikes me as rather
    >> more complicated than a string formatting function needs to be, but
    >> that may be a cost of its flexibility.
    >>

    >
    > Since we've decided to derail the conversation...
    >
    > "{}".format() is a blessing an "" % () should go. "%" has no relevance to
    > strings, is hard to "get" and has an appalling* syntax. Having two syntaxes
    > just makes things less obvious, and the right choice rarer.
    >
    > str.format is also really easy. I don't understand what makes you disagree.
    >
    > Easy vs easier:
    >
    >>>> "%s %s %s" % (1, 2, 3)

    > '1 2 3'
    >
    >>>> "{} {} {}".format(1, 2, 3)

    > '1 2 3'
    >
    > Easy vs easier:
    >
    >>>> "You have %(spam)s spam and %(eggs)s eggs!" % {"spam": 43, "eggs": 120}

    > 'You have 43 spam and 120 eggs!'
    >
    >>>> "You have {spam} spam and {eggs} eggs!".format(spam=43, eggs=120)

    > <OR>
    >>>> "You have {spam} spam and {eggs} eggs!".format(**{"spam": 43, "eggs":

    > 120})
    > 'You have 43 spam and 120 eggs!'
    >
    > Eh...? vs easy:
    >
    >>>> "Thing %s has state %+o!" % ("#432", 14)

    > 'Thing #432 has state +16!
    >
    >>>> "Thing {} has state {:+o}!".format("#432", 14)

    > 'Thing #432 has state +16!'
    >
    > *Additionally*, a = str.format is much *better* than a = str.__mod__.
    >
    > I have a piece of code like this:
    > "{fuscia}{{category__name}}/{reset}{{name}} {green}{{version}}{reset}:\n
    > {{description}}"
    >
    > Which *would* have looked like this:
    > "%(fuscia)s%%(category__name)s/%(reset)s%%(name)s
    > %(green)s%%(version)s%(reset)s:\n %%(description)s"
    >
    > Which would have parsed to something like:
    > 'FUSCIA{category__name}/RESET{name} GREEN{version}RESET:\n {description}'
    > and
    > 'FUSCIA%(category__name)s/RESET%(name)s GREEN%(version)sRESET:\n
    > %(description)s'
    >
    > Can you seriously say you don't mind the "%(name)s"s in this?
    >
    > * "A {} is in the {}" vs "A %s is in the %s"?
    >
    >
    >


    C %f style formatting is never going to go so live with it. I know as I
    asked maybe two years ago. On Python-dev. I think.

    --
    Cheers.

    Mark Lawrence.
     
    Mark Lawrence, Nov 21, 2012
    #12
  13. Chris Angelico

    Ian Kelly Guest

    On Wed, Nov 21, 2012 at 4:21 PM, Joshua Landau
    <> wrote:
    > "{}".format() is a blessing an "" % () should go. "%" has no relevance to
    > strings, is hard to "get" and has an appalling* syntax. Having two syntaxes
    > just makes things less obvious, and the right choice rarer.
    >
    > str.format is also really easy. I don't understand what makes you disagree.


    I think it mostly depends on where you come from as a programmer. As
    you say, having two syntaxes muddles things up. If you come from C or
    C++, then the %s syntax feels natural and intuitive, and trying to
    learn the sort-of-similar-but-not-really {} syntax on top of it is
    just confusing. Conversely, if you come from Java or C#, then the {}
    syntax comes naturally, and having to learn %s in addition will give
    one a headache. And then there are those who come from Lisp and want
    to know why they can't just use the familiarly easy ~a syntax.

    None of these are really any easier than the others. But they are
    sort of similar at a superficial level, which just makes it that much
    more painful to learn one when you're already accustomed to another.

    I think my favorite example from the str.format documentation is this
    one. Apart from demonstrating the flexibility of the format system,
    it also manages to mix the two systems in a most unholy way:

    >>> import datetime
    >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
    >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)

    '2010-07-04 12:15:58'
     
    Ian Kelly, Nov 22, 2012
    #13
  14. Chris Angelico

    Terry Reedy Guest

    On 11/21/2012 6:21 PM, Joshua Landau wrote:

    > Since we've decided to derail the conversation...
    >
    > "{}".format() is a blessing an "" % () should go. "%" has no relevance
    > to strings, is hard to "get" and has an appalling* syntax. Having two
    > syntaxes just makes things less obvious, and the right choice rarer.
    >
    > str.format is also really easy. I don't understand what makes you disagree.
    >
    > Easy vs easier:
    >
    > >>> "%s %s %s" % (1, 2, 3)

    > '1 2 3'
    >
    > >>> "{} {} {}".format(1, 2, 3)

    > '1 2 3'


    You forgot the cases where % formatting has to be special cased.
    >>> "The answer is {}.".format(1)

    'The answer is 1.'
    >>> "The answer is {}.".format((1,))

    'The answer is (1,).'
    >>> "The answer is %s" % 1

    'The answer is 1'
    >>> "The anwser is %s" % (1,)

    'The answer is 1'
    >>> "The answer is %s" % ((1,),)

    'The answer is (1,)'


    --
    Terry Jan Reedy
     
    Terry Reedy, Nov 22, 2012
    #14
  15. From Yet another Python textbook
    On 21/11/2012 5:17 PM, Chris Angelico wrote:
    > On Thu, Nov 22, 2012 at 4:03 AM, Colin J. Williams <> wrote:
    >> On 20/11/2012 4:00 PM, Chris Angelico wrote:
    >>> To the OP: jmf has an unnatural hatred of Python 3.3 and PEP 393
    >>> strings. Take no notice; the rest of the world sees this as a huge
    >>> advantage. Python is now in a VERY small group of languages (I'm aware
    >>> of just one other) that have absolutely proper Unicode handling *and*
    >>> efficient string handling.
    >>>
    >>> ChrisA
    >>>

    >> It's interesting to see that someone else finds the format function to be a
    >> pain. Perhaps the problem lies with the documentation.

    >
    > Hang on, what? I'm not sure where the format function comes in. I was
    > referring to the underlying representation.

    The OP wrote:
    "The absurd flexible string representation has practically
    borrowed the idea to propose once Python has a teaching tool."

    I perhaps stretched this to refer specifically on one aspect, formatting
    in my comment.
    >
    > That said, though, I'm just glad that %-formatting is staying. It's an
    > extremely expressive string formatting method, and exists in many
    > languages (thanks to C's heritage). Pike's version is insanely
    > powerful, Python's is more like C's, but all three are compact and
    > convenient.
    >
    > str.format(), on the other hand, is flexible. It strikes me as rather
    > more complicated than a string formatting function needs to be, but
    > that may be a cost of its flexibility.
    >
    > ChrisA


    Yes is is complicated.

    From my reading of the docs, it seems to me that the three following
    should be equivalent:

    (a) formattingStr.format(values)
    with
    (b) format(values, formattingStr)
    or
    (c) tupleOfValues.__format__(formattingStr

    Example:
    print('{:-^14f}{:^14d}'.format(-25.61, 95 ))
    print(format((-25.61, 95), '{:-^14f}{:^14d}'))
    (-25.61, 95 ).__format__('{:-^14f}{:^14d}')

    The second fails, perhaps because values can only be a single value.
    The third fails, the reason is unclear.

    Steven D'Aprano earlier said that a better diagnostic tool is planned
    for Python 3.4.

    Should we retreat to %-formatting for now?

    Colin W.



    >
     
    Colin J. Williams, Nov 22, 2012
    #15
  16. Chris Angelico

    Ian Kelly Guest

    On Thu, Nov 22, 2012 at 5:24 AM, Colin J. Williams <> wrote:
    > From my reading of the docs, it seems to me that the three following should
    > be equivalent:
    >
    > (a) formattingStr.format(values)
    > with
    > (b) format(values, formattingStr)
    > or
    > (c) tupleOfValues.__format__(formattingStr
    >
    > Example:
    > print('{:-^14f}{:^14d}'.format(-25.61, 95 ))
    > print(format((-25.61, 95), '{:-^14f}{:^14d}'))
    > (-25.61, 95 ).__format__('{:-^14f}{:^14d}')
    >
    > The second fails, perhaps because values can only be a single value.
    > The third fails, the reason is unclear.


    The latter two (which are more or less equivalent) fail because they are
    intended for invoking the formatting rules of a single value. The
    string argument to each of them is not a format string, but a "format
    specification", which in a format string is only the part that goes
    inside the curly braces and after the optional colon. For example, in
    this format string:

    >>> 'Hello world {0!s:_>4s}'.format(42)

    'Hello world __42'

    The format specifier here is "_>4s":

    >>> format('42', '_>4s')

    '__42'

    The valid format specifiers depend upon the type of the object being formatted:

    >>> format(42, '04x')

    '002a'

    >>> format(datetime(2012, 11, 22, 11, 17, 0), 'The time is %Y %d %m %H:%M:%S')

    'The time is 2012 22 11 11:17:00'

    Custom types can implement custom format specifications by overriding
    the __format__ method:

    >>> class Foo:

    .... def __init__(self, value):
    .... self.value = value
    .... def __format__(self, spec):
    .... if spec == 'a':
    .... return str(self.value)
    .... if spec == 'b':
    .... return ''.join(reversed(str(self.value)))
    .... raise ValueError("Unknown format code {!r}".format(spec))
    ....
    >>> format(Foo(42), 'a')

    '42'
    >>> format(Foo(42), 'b')

    '24'

    The same format specifications can then also be passed to str.format:

    >>> '{0:a} reversed is {0:b}'.format(Foo(42))

    '42 reversed is 24'

    Unfortunately, there does not seem to be a good reference to the
    format specifications available for built-in types beyond basic
    strings and numbers. I only knew about the datetime example because
    it is used in an example in the str.format docs. The
    datetime.__format__ implementation (which seems to be just a thin
    wrapper of datetime.strftime) does not seem to be documented anywhere
    in the datetime module docs.
     
    Ian Kelly, Nov 22, 2012
    #16
  17. Chris Angelico

    Terry Reedy Guest

    On 11/22/2012 7:24 AM, Colin J. Williams wrote:

    > From my reading of the docs, it seems to me that the three following
    > should be equivalent:


    We read differently...
    >
    > (a) formattingStr.format(values)


    Where 'values' is multiple arguments

    > with
    > (b) format(values, formattingStr)


    "format(value[, format_spec])
    Convert a value to a “formatted†representation, as controlled by
    format_spec."

    I notice that you did not pass multiple args, but indeed just one.
    A 'format_spec' is only part of a {} formatting field.

    > or
    > (c) tupleOfValues.__format__(formattingStr


    >>> tuple.__format__

    <method '__format__' of 'object' objects>

    Which of to say, not specific to tuples.

    > Example:
    > print('{:-^14f}{:^14d}'.format(-25.61, 95 ))
    > print(format((-25.61, 95), '{:-^14f}{:^14d}'))


    "The interpretation of format_spec will depend on the type of the value
    argument, however there is a standard formatting syntax that is used by
    most built-in types: Format Specification Mini-Language." (The latter is
    link to the FSML.

    '-^14f' and '^14d' are format_specs.
    '{:-^14f}{:^14d}' is a format string that includes two fields with
    format specs. It is not a format spec in itself and is therefore invalid
    by the doc.

    > (-25.61, 95 ).__format__('{:-^14f}{:^14d}')
    >
    > The second fails, perhaps because values can only be a single value.


    You only passed one, but you did not pass a format spec and indeed there
    is none for tuples. As delivered, format specs only format strings and
    numbers as strings. Collection classes other than str recursively format
    their members using str() or repr() until they reach strings, numbers,
    or customs class instances with custom .__format__ methods.

    > Should we retreat to %-formatting for now?


    Nonsense. The issues above are the same for % formatting. If you try to
    format one object with two % format specs, it will fail for the same
    reason. Try the % equivalent of what failed.

    '%-14f%14d' % ((-25.61, 95 ),)

    --
    Terry Jan Reedy
     
    Terry Reedy, Nov 22, 2012
    #17
  18. On 22/11/2012 1:27 PM, Ian Kelly wrote:
    > On Thu, Nov 22, 2012 at 5:24 AM, Colin J. Williams <> wrote:
    >> From my reading of the docs, it seems to me that the three following should
    >> be equivalent:
    >>
    >> (a) formattingStr.format(values)
    >> with
    >> (b) format(values, formattingStr)
    >> or
    >> (c) tupleOfValues.__format__(formattingStr
    >>
    >> Example:
    >> print('{:-^14f}{:^14d}'.format(-25.61, 95 ))
    >> print(format((-25.61, 95), '{:-^14f}{:^14d}'))
    >> (-25.61, 95 ).__format__('{:-^14f}{:^14d}')
    >>
    >> The second fails, perhaps because values can only be a single value.
    >> The third fails, the reason is unclear.

    >
    > The latter two (which are more or less equivalent) fail because they are
    > intended for invoking the formatting rules of a single value. The
    > string argument to each of them is not a format string, but a "format
    > specification", which in a format string is only the part that goes
    > inside the curly braces and after the optional colon. For example, in
    > this format string:


    Thanks, this is clear. I wish the docs made this clearer.

    You and I used __format__. I understand that the use of double
    underscore functions is deprecated. Is there some regular function
    which can achieve the same result?

    >
    >>>> 'Hello world {0!s:_>4s}'.format(42)

    > 'Hello world __42'
    >
    > The format specifier here is "_>4s":
    >
    >>>> format('42', '_>4s')

    > '__42'
    >
    > The valid format specifiers depend upon the type of the object being formatted:
    >
    >>>> format(42, '04x')

    > '002a'
    >
    >>>> format(datetime(2012, 11, 22, 11, 17, 0), 'The time is %Y %d %m %H:%M:%S')

    > 'The time is 2012 22 11 11:17:00'
    >
    > Custom types can implement custom format specifications by overriding
    > the __format__ method:
    >
    >>>> class Foo:

    > ... def __init__(self, value):
    > ... self.value = value
    > ... def __format__(self, spec):
    > ... if spec == 'a':
    > ... return str(self.value)
    > ... if spec == 'b':
    > ... return ''.join(reversed(str(self.value)))
    > ... raise ValueError("Unknown format code {!r}".format(spec))
    > ...
    >>>> format(Foo(42), 'a')

    > '42'
    >>>> format(Foo(42), 'b')

    > '24'
    >
    > The same format specifications can then also be passed to str.format:
    >
    >>>> '{0:a} reversed is {0:b}'.format(Foo(42))

    > '42 reversed is 24'
    >
    > Unfortunately, there does not seem to be a good reference to the
    > format specifications available for built-in types beyond basic
    > strings and numbers. I only knew about the datetime example because
    > it is used in an example in the str.format docs. The
    > datetime.__format__ implementation (which seems to be just a thin
    > wrapper of datetime.strftime) does not seem to be documented anywhere
    > in the datetime module docs.
    >
     
    Colin J. Williams, Nov 22, 2012
    #18
  19. On Thu, 22 Nov 2012 17:41:22 -0500, Colin J. Williams wrote:

    > You and I used __format__. I understand that the use of double
    > underscore functions is deprecated.


    Double leading and trailing underscore methods are not deprecated, they
    are very much part of the public interface. But they are reserved for
    Python's use, and under normal conditions you should not be using them by
    hand. For example:

    y = x.__add__(1) # NO
    y = x + 1 # YES

    if mylist.__len__() > 2: # NO
    if len(mylist) > 2: # YES


    > Is there some regular function which can achieve the same result?


    The built-in format() function is the public API for calling the dunder
    method __format__. So normally you would write:

    format(value, spec)

    instead of value.__format__(spec).



    --
    Steven
     
    Steven D'Aprano, Nov 23, 2012
    #19
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Kwpolska

    Re: Yet another Python textbook

    Kwpolska, Nov 19, 2012, in forum: Python
    Replies:
    2
    Views:
    160
    Steven D'Aprano
    Nov 20, 2012
  2. Ian Kelly

    Re: Yet another Python textbook

    Ian Kelly, Nov 20, 2012, in forum: Python
    Replies:
    0
    Views:
    139
    Ian Kelly
    Nov 20, 2012
  3. Ian Kelly

    Re: Yet another Python textbook

    Ian Kelly, Nov 20, 2012, in forum: Python
    Replies:
    0
    Views:
    136
    Ian Kelly
    Nov 20, 2012
  4. Terry Reedy

    Re: Yet another Python textbook

    Terry Reedy, Nov 20, 2012, in forum: Python
    Replies:
    0
    Views:
    156
    Terry Reedy
    Nov 20, 2012
  5. Alec Taylor

    Re: Yet another Python textbook

    Alec Taylor, Nov 22, 2012, in forum: Python
    Replies:
    0
    Views:
    125
    Alec Taylor
    Nov 22, 2012
Loading...

Share This Page