Re: Portable code: __import__ demands different string types between 2 and 3
On Sun, Dec 14, 2014 at 11:29 PM, Ben Finney wrote:
> I'm slowly learning about making Python code that will run under both
> Python 2 (version 2.6 or above) and Python 3 (version 3.2 or above).
>
> This entails, I believe, the admonition to ensure text literals are
> Unicode by default::
>
> from __future__ import unicode_literals
Ordinarily, for 2.x/3.3+ code I would suggest not doing this --
instead, b'...' for bytes, u'...' for unicode, and '...' for native
"string" type (bytes on 2.x, unicode on 3.x). This is the main benefit
of the u'...' syntax addition.
For 3.2, you'll have to do b'...' for bytes, '...' for unicode, and
str('...') for platform-specific strings (bytes on 2.x, unicode on
3.x). It is in good taste to make an alias of str so it's less
confusing, e.g. native_str = str.
So for example, it's __import__(str("foo")), and getattr(foo, str("bar"), baz).
-- Devin
--
https://mail.python.org/mailman/listinfo/python-list
Re: is_ as method or property?
On 13 December 2014 at 12:24, Steven D'Aprano wrote: > Mateusz Loskot wrote: > >> On 12 December 2014 at 12:26, Chris Angelico wrote: >>> On Fri, Dec 12, 2014 at 10:21 PM, Mateusz Loskot >>> wrote: I've got several cases which are not obvious to me. For instance, class Foo has a boolean attribute, read-write, which I see a couple of realisations for possible: > [...] >> I mentioned, setting the new value involves more changes to Foo() >> instance, so i's not possible to capture it with just an assignment. >> Hence, the discussion between property vs method. > > If the calculation is cheap and fast and "feels like" getting/setting an > attribute, then use property. > > If the calculation is expensive, or might fail, then use explicit > getter/setter methods. > > I'm afraid that there is no objective way to tell when something "feels > like" an attribute. That depends partly on the class you are dealing with, > and partly on personal taste. That confirms my now updated, thanks to this thread, understanding of that issue. Thanks all! Best regards, -- Mateusz Loskot, http://mateusz.loskot.net -- https://mail.python.org/mailman/listinfo/python-list
Re: "**" in python
In article ,
Skip Montanaro wrote:
>-=-=-=-=-=-
>
>I want to add one more thing to the other responses. People new to Python
>often seem unaware that being an interpreted language, often the best way
>to figure something out is to simply try it at the interpreter prompt. The
>OP saw "var ** 2" in done code. The most obvious thing to me would have
>been to type
>
>var = 42
>var ** 2
>
>and see what happened. It's unlikely to trigger a nuclear meltdown, or even
>crash the interpreter.
>
>Skip
>
>-=-=-=-=-=-
>[Alternative: text/html]
>-=-=-=-=-=-
With some perseverance, you can ask the interpreter what `` ** ''
does:
help(**)
maybe so?
help('**')
Indeed, a whole description.
help(var)
help(42)
also work.
Come on, guys and dolls! Your advice to a newbies is soso,
if in this kind of answer, the help facilitiy is not
mentionned.
Groetjes Albert
--
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst
--
https://mail.python.org/mailman/listinfo/python-list
Re: encoding name mappings in codecs.py with email/charset.py
I played around with changing the names in the aliases.py and locale.py
files (from iso8859 to iso-88559), but this broke mailman.
I ended up changing the charset.py file
input_charset = codecs.lookup(input_charset).name
except LookupError:
pass
if (input_charset == 'iso8859-7'):
input_charset = 'iso-8859-15
if (input_charset == 'iso8859-15'):
input_charset = 'iso-8859-7'
if (input_charset == 'iso8859-1'):
input_charset = 'iso-8859-1'
This seems to work for now.
I really wonder why I'm the only one with this problem. This should affect
all Mailman users with member on MS Exchange 2010 (at least) servers.
Exchange produces
CAT.InvalidContent.Exception: InvalidCharsetException, Character set name
(iso8859-7) is invalid or not installed.; cannot handle content of message
with...
Thanks gst for the input
sk
On Sun, Dec 14, 2014 at 9:53 PM, gst wrote:
>
> Le dimanche 14 décembre 2014 14:10:22 UTC-5, Stefanos Karasavvidis a
> écrit :
> > thanks for replying gst.
> >
> > I've thought already of patching the Charset class, but hoped for a
> cleaner solution.
> >
> >
> > This ALIASES dict has already all the iso names *with* a dash. So it
> must get striped somewhere else.
>
>
> not on my side, modifying this dict with the missing key-value apparently
> does what you want also :
>
> Python 2.7.6 (default, Mar 22 2014, 22:59:56)
> [GCC 4.8.2] on linux2
> Type "copyright", "credits" or "license()" for more information.
> >>>
> >>> import email.charset
> >>> email.charset.ALIASES
> {'latin-8': 'iso-8859-14', 'latin-9': 'iso-8859-15', 'latin-2':
> 'iso-8859-2', 'latin-3': 'iso-8859-3', 'latin-1': 'iso-8859-1', 'latin-6':
> 'iso-8859-10', 'latin-7': 'iso-8859-13', 'latin-4': 'iso-8859-4',
> 'latin-5': 'iso-8859-9', 'euc_jp': 'euc-jp', 'latin-10': 'iso-8859-16',
> 'ascii': 'us-ascii', 'latin_10': 'iso-8859-16', 'latin_1': 'iso-8859-1',
> 'latin_2': 'iso-8859-2', 'latin_3': 'iso-8859-3', 'latin_4': 'iso-8859-4',
> 'latin_5': 'iso-8859-9', 'latin_6': 'iso-8859-10', 'latin_7':
> 'iso-8859-13', 'latin_8': 'iso-8859-14', 'latin_9': 'iso-8859-15', 'cp949':
> 'ks_c_5601-1987', 'euc_kr': 'euc-kr'}
> >>>
> >>> for i in range(1, 16):
> c = 'iso-8859-' + str(i)
> email.charset.ALIASES[c] = c
>
>
> >>>
> >>> iso7 = email.charset.Charset('iso-8859-7')
> >>> iso7
> iso-8859-7
> >>> str(iso7)
> 'iso-8859-7'
> >>>
>
> regards,
>
> gst.
>
> >
> > sk
> >
> >
> >
> > On Sun, Dec 14, 2014 at 7:21 PM, gst wrote:
> > Le vendredi 12 décembre 2014 04:21:14 UTC-5, Stefanos Karasavvidis a
> écrit :
> >
> > > I've hit a wall with mailman which seems to be caused by pyhon's
> character encoding names.
> >
> > >
> >
> > > I've narrowed the problem down to the email/charset.py file. Basically
> the following happens:
> >
> > >
> >
> >
> >
> > Hi,
> >
> >
> >
> > it's all in the email.charset.ALIASES dict.
> >
> >
> >
> > you could also simply patch the __str__ method of Charset :
> >
> >
> >
> > Python 2.7.6 (default, Mar 22 2014, 22:59:56)
> >
> > [GCC 4.8.2] on linux2
> >
> > Type "copyright", "credits" or "license()" for more information.
> >
> > >>>
> >
> > >>> import email.charset
> >
> > >>>
> >
> > >>> c = email.charset.Charset('iso-8859-7')
> >
> > >>> str(c)
> >
> > 'iso8859-7'
> >
> > >>>
> >
> > >>> old = email.charset.Charset.__str__
> >
> > >>>
> >
> > >>> def patched(self):
> >
> > r = old(self)
> >
> > if r.startswith('iso'):
> >
> > return 'iso-' + r[3:]
> >
> > return r
> >
> >
> >
> > >>>
> >
> > >>> email.charset.Charset.__str__ = patched
> >
> > >>>
> >
> > >>> str(c)
> >
> > 'iso-8859-7'
> >
> > >>>
> >
> >
> >
> >
> >
> > regards,
> >
> >
> >
> > gst.
> >
> > --
> >
> > https://mail.python.org/mailman/listinfo/python-list
> >
> >
> >
> >
> > --
> >
> >
> > ==
> > Stefanos Karasavvidis, Electronic & Computer Engineer, M.Sc.
> > e-mail: [email protected], Tel.: (+30) 2821037508, Fax: (+30) 2821037520
> > Technical University of Crete, Campus, Building A1
> --
> https://mail.python.org/mailman/listinfo/python-list
>
--
==
Stefanos Karasavvidis, Electronic & Computer Engineer, M.Sc.
e-mail: [email protected], Tel.: (+30) 2821037508, Fax: (+30)
2821037520
Technical University of Crete, Campus, Building A1
--
https://mail.python.org/mailman/listinfo/python-list
Re: "**" in python
Albert van der Horst wrote:
> With some perseverance, you can ask the interpreter what `` ** ''
> does:
>
> help(**)
>
> maybe so?
> help('**')
> Indeed, a whole description.
Yes! Well spotted!
--
Steven
--
https://mail.python.org/mailman/listinfo/python-list
Re: Portable code: __import__ demands different string types between 2 and 3
Ben Finney wrote:
> Howdy all,
>
> What should I do, in a world where all text literals are Unicode by
> default, to make ‘__import__’ work in both Python 2 and 3?
One approach I frequently use is a conditional import. Off the top of my
head, I'd do something like this:
try:
import builtins # Python 3.x.
except ImportError:
# We're probably running Python 2.x.
import __builtin__ as builtins
# Untested, just to give you an idea of what I mean.
try:
_ = __import__("sys", fromlist=["version"])
except TypeError:
# Shadow the built-in with a patched version.
def __import__(*args, **kwargs):
if "fromlist" in kwargs:
kwargs["fromlist"] = [str(name) for name in kwargs["fromlist"]]
return builtins.__import__(*args, **kwargs)
If you're really brave, you can even monkey-patch builtins with your own
version. Obviously you still need to keep the old version somewhere. A
closure would be perfect for that:
# Again, untested.
def patch_import(original_import=__import__):
def __import__(*args, **kwargs):
if "fromlist" in kwargs:
kwargs["fromlist"] = [str(name) for name in kwargs["fromlist"]]
return original_import(*args, **kwargs)
builtins.__import__ = __import__
Monkey-patching builtins.__import__ is one of the few
not-completely-frowned-upon uses of monkey-patching.
Perhaps a better approach might be to eschew the use of __import__ and see
whether the functions in imputil (deprecated) or importlib do what you
need.
https://docs.python.org/2/library/imputil.html
https://docs.python.org/3/library/importlib.html
Aside: __import__ is not recommended for user code.
"Direct use of __import__() is also discouraged in favor of
importlib.import_module()."
https://docs.python.org/3/library/functions.html#__import__
--
Steven
--
https://mail.python.org/mailman/listinfo/python-list
ANN: Benchmarker 4.0.0 released - small but awesome benchmark utility
I released Benchmarker ver 4.0.0
http://pypi.python.org/pypi/Benchmarker/
http://pythonhosted.org/Benchmarker/
Benchmarker is a small utility to benchmark your code.
*NOTICE* This release doesn't have compatibility with ver 3.x.
Installation
$ sudo pip install Benchmarker
Example
---
example.py::
from benchmarker import Benchmarker
with Benchmarker(1000*1000, width=20) as bench:
s1, s2, s3, s4, s5 = "Haruhi", "Mikuru", "Yuki", "Itsuki", "Kyon"
@bench(None)
def _(bm):
for _ in bm: ## empty loop
pass
@bench("concat")
def _(bm):
for _ in bm:
s = s1 + s2 + s3 + s4 + s5
@bench("join")
def _(bm):
for _ in bm:
s = "".join((s1, s2, s3, s4, s5))
@bench("format")
def _(bm):
for _ in bm:
s = "%s%s%s%s%s" % (s1, s2, s3, s4, s5)
Output example::
$ python example.py -h # show help message.
$ python example.py # or python example.py -n 100
## benchmarker: release 4.0.0 (for python)
## python version: 3.4.1
## python compiler: GCC 4.2.1 Compatible Apple LLVM 6.0
(clang-600.0.51)
## python platform: Darwin-14.0.0-x86_64-i386-64bit
## python executable: /usr/local/bin/python
## cpu model: Intel(R) Core(TM) i7-4650U CPU @ 1.70GHz
## parameters: loop=100, cycle=1, extra=0
##real(total= user+ sys)
(Empty) 0.03350.03000.03000.
concat 0.41920.42000.41000.0100
join0.36740.37000.37000.
format 0.47650.46000.46000.
## Rankingreal
join0.3674 (100.0)
concat 0.4192 ( 87.6) **
format 0.4765 ( 77.1) ***
## Matrix real[01][02][03]
[01] join 0.3674 100.0 114.1 129.7
[02] concat 0.419287.6 100.0 113.7
[03] format 0.476577.188.0 100.0
Notice that empty loop times (real, user, sys and total) are
subtracted from other benchmark times automatically.
For example::
===
benchmark labelreal (second)
---
join 0.3674 (= 0.4009 - 0.0335)
concat 0.4192 (= 0.4527 - 0.0335)
format 0.4765 (= 0.5100 - 0.0335)
===
See http://pythonhosted.org/Benchmarker/ for details.
Have fun!
--
regards,
makoto kuwata
--
https://mail.python.org/mailman/listinfo/python-list
Python {executable templates from XSLT, code generation tool}
Hi, I'm searching a tool to translate an xsl file to executable python code. I know how to execute xslt with python. What I want is to process my xslt rules *in* python. Example : Mr Mrs I would like it to be translated in a python test statement. Does anyone know something like this ? Or at least a code generation tool ? I read about Cog and might use it. Jbb -- https://mail.python.org/mailman/listinfo/python-list
Re: Portable code: __import__ demands different string types between 2 and 3
On 12/14/2014 11:29 PM, Ben Finney wrote:
>
> This entails, I believe, the admonition to ensure text literals are
> Unicode by default::
>
> from __future__ import unicode_literals
>
> and to specify bytes literals explicitly with ‘b'wibble'’ if needed.
For some scripts this works great (I have some), and for some it does not (I
have some of those, too).
> The ‘__import__’ built-in function, though, is tripping up.
One work-around I have used is:
if isinstance(some_var, bytes):
some_var = some_var.decode('ascii')
# at this point some_var is unicode in both Pythons
--
~Ethan~
signature.asc
Description: OpenPGP digital signature
--
https://mail.python.org/mailman/listinfo/python-list
RE: Classes - converting external function to class's method.
Again Thanks for your help. I saw that there was a debate about "namespace" nature. That is what a book says about it(Learning Python 5 Ed. By Mark Lutz): * "Classes and Instances Although they are technically two separate object types in the Python model, the classes and instances we put in these trees are almost identical—each type’s main purpose is to serve as another kind of namespace—a package of variables, and a place where we can attach attributes. If classes and instances therefore sound like modules, they should; however, the objects in class trees also have automatically searched links to other namespace objects, and classes correspond to statements, not entire files." "Customization via inheritance More generally, classes can build up namespace hierarchies, which define names to be used by objects created from classes in the hierarchy. This supports multiple customizable behaviors more directly than other tools." "...classes live in modules and are namespaces as well, but they add an extra component to attribute lookup called inheritance search." "In fact, classes have just three primary distinctions. At a base level, they are mostly just namespaces, much like the modules we studied in Part V. Unlike modules, though, classes also have support for generating multiple objects, for namespace inheritance, and for operator overloading." I'm not pretending to be a "smartass" here, but as I can understand from the context: Classes are namespaces, but they also have an additional capabilities. BR, Ivan > -Original Message- > From: Python-list [mailto:python-list- > [email protected]] On Behalf Of Steven > D'Aprano > Sent: Monday, December 15, 2014 04:01 > To: [email protected] > Subject: Re: Classes - converting external function to class's method. > > Thomas 'PointedEars' Lahn wrote: > > > Ivan Evstegneev wrote: > > > >> I have stuck a bit with this example(took this one from the book). > >> > >> Here are a description steps of what I've done till now: > >> > >> > >> Step 1 - creating an empty namespace: > >> > >class rec: pass > > > > IMHO that is not actually creating a namespace; it is just > > declaring/defining an empty class. > > And classes are namespaces. As are instances. > > One clue is the fact that we use exactly the same syntax for accessing names > in a > namespace regardless of whether the namespace is a package, a module, a class > or an instance: > > import collections.abc # a package namespace math.sin # a module namespace > OrderedDict.fromkeys # a class namespace mystring.upper # an instance > namespace > > I call it a "clue" rather than definitive proof because the syntax is not > quite the > same for all namespaces. Local and global variables also exist in namespaces, > but > you don't use dotted notation for them. > > Another clue is that most of these are implemented by using a __dict__ to > store > the name:value mapping. Again, that's not universal: instances can optionally > use __slots__ instead of __dict__ and packages use the file system. > > Apart from packages, one can use getattr(), setattr() and delattr() on all of > these > objects (modules, classes and instances) to manipulate their attributes. > > Wikipedia says: > > "In general, a namespace is a container for a set of identifiers (also known > as > symbols, names)." > > https://en.wikipedia.org/wiki/Namespace > > and that applies to packages, modules, classes, and instances. > > Last but not least, another clue: in some languages, such as Java, what Python > calls "attributes" are known as *variables*. So per-instance members are > called > "instance variables", per-class members are sometimes called "class variables" > (although not in Java, where I believe they are known as static variables for > technical reasons). Personally, I don't like that terminology, but I do > recognise > that it does reflect a certain connection between names in > local/global/instance/class namespaces. > > > > BTW, the recommended Python 3.x way is > > > > class Rec (object): > > pass > > > I think you mean Python 2 rather than 3. In Python 2, we have legacy "old > style" > or "classic" classes, and "new style" classes which inherit from object. In > Python > 3, classic classes are gone, and inheriting from object is optional. > > > > (whereas “pass” is a placeholder statement, a bit like the yada-yada > > operator of Python) and you should start class identifiers uppercase > > (therefore, “Rec” instead) in order to avoid name collisions with > > built-in class identifiers (“str”, “int” etc.) and make it easier to > > tell apart instantiations from function/method calls. > > Agreed! > > It is good practice to name classes with initial capital letter, and > instances in all > lowercase. > > > > If you
[ANN] pyspread 0.4
pyspread 0.4 Pyspread 0.4 is released. In this release, rendering has switched to Cairo, which enhances quality and performance. Grid content can now be exported into high quality PDF and SVG files. Cells can now display SVG images and text with markups. The nn function now removes None from lists, tuples, etc. About pyspread == Pyspread is a non-traditional spreadsheet application that is based on and written in the programming language Python. The goal of pyspread is to be the most pythonic spreadsheet application. Pyspread is free software. It is released under the GPL v3. Project website: http://manns.github.com/pyspread/ Download page: https://pypi.python.org/pypi/pyspread Enjoy Martin -- https://mail.python.org/mailman/listinfo/python-list
Portable code: ‘from __future__ import unicode_literals’ a good idea? (was: Portable code: __import__ demands different string types between 2 and 3)
Devin Jeanpierre writes: > On Sun, Dec 14, 2014 at 11:29 PM, Ben Finney > wrote: > > from __future__ import unicode_literals > > Ordinarily, for 2.x/3.3+ code I would suggest not doing this -- > instead, b'...' for bytes, u'...' for unicode, and '...' for native > "string" type (bytes on 2.x, unicode on 3.x). This is the main benefit > of the u'...' syntax addition. That latter point would seemingly also apply to ‘from __future__ import unicode_literals’, so is moot in this context. As for the advice to avoid such a declaration, you're arguing against the official guide for porting Python 2 code to 2-and-3 compatible code: For text you should either use the from __future__ import unicode_literals statement or add a u prefix to the text literal. https://docs.python.org/3.4/howto/pyporting.html#text-versus-binary-data> So, the declarative import is specifically recommended. You'll need to present a case for why I shouldn't follow that recommendation. -- \ “I disapprove of what you say, but I will defend to the death | `\ your right to say it.” —Evelyn Beatrice Hall, _The Friends of | _o__) Voltaire_, 1906 | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Portable code: ‘from __future__ import unicode_literals’ a good idea? (was: Portable code: __import__ demands different string types between 2 and 3)
On Mon, Dec 15, 2014 at 4:42 PM, Ben Finney wrote:
> Devin Jeanpierre writes:
>
>> On Sun, Dec 14, 2014 at 11:29 PM, Ben Finney
>> wrote:
>> > from __future__ import unicode_literals
>>
>> Ordinarily, for 2.x/3.3+ code I would suggest not doing this --
>> instead, b'...' for bytes, u'...' for unicode, and '...' for native
>> "string" type (bytes on 2.x, unicode on 3.x). This is the main benefit
>> of the u'...' syntax addition.
>
> That latter point would seemingly also apply to ‘from __future__ import
> unicode_literals’, so is moot in this context.
>
> As for the advice to avoid such a declaration, you're arguing against
> the official guide for porting Python 2 code to 2-and-3 compatible code:
>
> For text you should either use the from __future__ import
> unicode_literals statement or add a u prefix to the text literal.
>
>
> https://docs.python.org/3.4/howto/pyporting.html#text-versus-binary-data>
>
> So, the declarative import is specifically recommended. You'll need to
> present a case for why I shouldn't follow that recommendation.
All the doc is saying there is to use unicode for text, in a way that
works in both 2.x and 3.x. I am saying that the unicode_literals
import is not necessarily the best way to do so.
Python has three categories of strings: things that should be bytes in
2.x and 3.x, things that should be unicode in 2.x and 3.x, and things
that should be bytes on 2.x and unicode on 3.x. The last category
applies mostly to identifiers -- the strings you pass to functions
like getattr or __import__, and the strings that are valid keys in
**kwargs, and so on. You need a way to represent the last kind of
string, whether it's unadorned "..." literals, or function calls like
identifier_string("..."). If you can solve that, you are good. The
official porting guide offers no advice.
-- Devin
--
https://mail.python.org/mailman/listinfo/python-list
Re: Portable code: ‘from __future__ import unicode_literals’ a good idea?
On 12/15/14 7:42 PM, Ben Finney wrote: As for the advice to avoid such a declaration, you're arguing against the official guide for porting Python 2 code to 2-and-3 compatible code: For text you should either use the from __future__ import unicode_literals statement or add a u prefix to the text literal. https://docs.python.org/3.4/howto/pyporting.html#text-versus-binary-data> So, the declarative import is specifically recommended. You'll need to present a case for why I shouldn't follow that recommendation. What's wrong with this part of the recommendation?: "or add a u prefix to the text literal." Also, keep in mind, these recommendations are not infallible. They are sometimes written before there's been broad experience with the solution. Your use of __import__ puts you in a tiny minority of programs, so the recommendation that's good for 99% of code may not work for you. Be flexible. Do what works. -- Ned Batchelder, http://nedbatchelder.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Portable code: __import__ demands different string types between 2 and 3
Ethan Furman writes:
> On 12/14/2014 11:29 PM, Ben Finney wrote:
> > The ‘__import__’ built-in function, though, is tripping up.
>
> One work-around I have used is:
>
> if isinstance(some_var, bytes):
> some_var = some_var.decode('ascii')
> # at this point some_var is unicode in both Pythons
That's not the issue at all. I know how to declare a literal such that
it is Unicode in Python 2 and Python 3 (that's what the ‘from __future__
import unicode_literals’ does).
Rather, the problem is ‘__import__’ having incompatible expectations:
the ‘fromlist’ parameter's items must be bytes in Python 2, and must be
Unicode in Python 3.
The same parameter value can't satisfy both those requirements in a
single 2-and-3 compatible code base, without either using the
bytes-and-text ambiguity of ‘str’, or some kludge over-riding a simple
‘__import__’ call. Both of those are ugly and make for buggy code.
I'm increasingly of the opinion this is a subtle bug in ‘__import__’
that should be fixed instead of worked around. But it will likely be
rejected because the documentation advises against using ‘__import__’.
Bah.
--
\ “Try adding “as long as you don't breach the terms of service – |
`\ according to our sole judgement” to the end of any cloud |
_o__) computing pitch.” —Simon Phipps, 2010-12-11 |
Ben Finney
--
https://mail.python.org/mailman/listinfo/python-list
Re: Portable code: __import__ demands different string types between 2 and 3
On 12/15/2014 05:36 PM, Ben Finney wrote: > > That's not the issue at all. I know how to declare a literal such that > it is Unicode in Python 2 and Python 3 (that's what the ‘from __future__ > import unicode_literals’ does). > > Rather, the problem is ‘__import__’ having incompatible expectations: > the ‘fromlist’ parameter's items must be bytes in Python 2, and must be > Unicode in Python 3. Ah. Well, then you do not want the `unicode_literals` import or it won't be bytes in Python 2 (as I'm sure you know). > The same parameter value can't satisfy both those requirements in a > single 2-and-3 compatible code base, without either using the > bytes-and-text ambiguity of ‘str’, or some kludge over-riding a simple > ‘__import__’ call. Both of those are ugly and make for buggy code. If this is for a large(ish) application, make one module with stuff that needs the ambiguity to work correctly. Comment the heck out of it. ;) > I'm increasingly of the opinion this is a subtle bug in ‘__import__’ > that should be fixed instead of worked around. Of course. But you'll still need to work around it for previous versions, unless you can say you only support 2.7.10+ (maybe 2.7.9+ if it gets fixed quick enough). > But it will likely be rejected because the documentation advises against > using ‘__import__’. Functions that should accept str but barf on unicode have a tendency to get fixed. -- ~Ethan~ signature.asc Description: OpenPGP digital signature -- https://mail.python.org/mailman/listinfo/python-list
Re: Portable code: ‘from __future__ import unicode_literals’ a good idea?
Ned Batchelder writes: > On 12/15/14 7:42 PM, Ben Finney wrote: > > As for the advice to avoid such a declaration, you're arguing against > > the official guide for porting Python 2 code to 2-and-3 compatible code: > > > > For text you should either use the from __future__ import > > unicode_literals statement or add a u prefix to the text literal. > > > > > > https://docs.python.org/3.4/howto/pyporting.html#text-versus-binary-data> > > > > So, the declarative import is specifically recommended. You'll need to > > present a case for why I shouldn't follow that recommendation. > > What's wrong with this part of the recommendation?: "or add a u prefix > to the text literal." Who's saying there's anything wrong with that? Not I. My question is, what's wrong with the first part such that Devin recommends against it? > Also, keep in mind, these recommendations are not infallible. Yes, Devin clears up in a later message that the official guide provides no advice for the case where an API needs ‘bytes’ in Python 2 but Unicode in Python 3. > Be flexible. Do what works. Good advice, but nothing different from what I'm already trying to do. -- \“[R]ightful liberty is unobstructed action, according to our | `\will, within limits drawn around us by the equal rights of | _o__) others.” —Thomas Jefferson, 1819 | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Portable code: __import__ demands different string types between 2 and 3
Ben Finney wrote: > I'm increasingly of the opinion this is a subtle bug in ‘__import__’ > that should be fixed instead of worked around. But it will likely be > rejected because the documentation advises against using ‘__import__’. > Bah. I think its worth raising an issue on the bug tracker and see what the core devs think. If you don't have and won't open an account on the tracker, if you can come up with a minimal example that demonstrates the issue, I'll open an issue for you. (But I'd rather you did it yourself :-) -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Portable code: __import__ demands different string types between 2 and 3
Ethan Furman writes: > On 12/15/2014 05:36 PM, Ben Finney wrote: > > I'm increasingly of the opinion this is a subtle bug in ‘__import__’ > > that should be fixed instead of worked around. And other people agree: https://bugs.python.org/issue21720>. > Of course. But you'll still need to work around it for previous > versions, unless you can say you only support 2.7.10+ (maybe 2.7.9+ if > it gets fixed quick enough). If I can eventually drop the kludge by dropping support for Python <2.7 at some future point (instead of waiting until I can drop Python <3), that would still be an improvement. > Functions that should accept str but barf on unicode have a tendency > to get fixed. I hope you're right. The bug report currently focusses on improving the error message only. -- \ “They who can give up essential liberty to obtain a little | `\temporary safety, deserve neither liberty nor safety.” | _o__) —Benjamin Franklin, 1775-02-17 | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Portable code: __import__ demands different string types between 2 and 3
Steven D'Aprano writes: > If you don't have and won't open an account on the tracker, if you can > come up with a minimal example that demonstrates the issue, I'll open > an issue for you. (But I'd rather you did it yourself :-) Thank you for the offer. Fortunately, the Python bug tracker does not require me to maintain credentials for that site (I can use any OpenID), so I've got an account there. -- \ “Our task must be to free ourselves from our prison by widening | `\our circle of compassion to embrace all humanity and the whole | _o__) of nature in its beauty.” —Albert Einstein | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Neat little programming puzzle
This was a problem posed to me, which I solved in Python. I thought it was neat and enjoyed the exercise of working through it; feel free to ignore. For people looking for little projects to practice their skills with (or a simple distraction), read on. You have a triangle of numbers such that each row has 1 more number than the row before it, like so: 1 32 861 510 15 2 The task is to find the maximum possible sum through the triangle that you can compute by adding numbers that are adjacent to the value chosen in the row above. In this simple example, the solution is 1+3+6+15=25. As the number of rows increases, the possible paths through the triangle grows exponentially (and it's not enough to just look at the max value in each row, since they may not be part of the optimum pathway, like the '8' in row 3 of the above example). The challenge is to write a program to compute the sum of https://gist.github.com/swails/17ef52f3084df708816d. I liked this problem because naive solutions scale as O(2^N), begging for a more efficient approach. Have fun, Jason -- https://mail.python.org/mailman/listinfo/python-list
Re: Neat little programming puzzle
On Mon, Dec 15, 2014 at 10:46 PM, Jason Swails
wrote:
>
> This was a problem posed to me, which I solved in Python. I thought it
was neat and enjoyed the exercise of working through it; feel free to
ignore. For people looking for little projects to practice their skills
with (or a simple distraction), read on.
>
> You have a triangle of numbers such that each row has 1 more number than
the row before it, like so:
>
> 1
> 32
>861
> 510 15 2
>
> The task is to find the maximum possible sum through the triangle that
you can compute by adding numbers that are adjacent to the value chosen in
the row above. In this simple example, the solution is 1+3+6+15=25. As
the number of rows increases, the possible paths through the triangle grows
exponentially (and it's not enough to just look at the max value in each
row, since they may not be part of the optimum pathway, like the '8' in row
3 of the above example).
>
> The challenge is to write a program to compute the sum of
https://gist.github.com/swails/17ef52f3084df708816d.
>
> I liked this problem because naive solutions scale as O(2^N), begging for
a more efficient approach.
This pretty much screams for a dynamic programming solution.
ikelly@hephaestus ~ $ cat triangle_sum.py
#!/usr/bin/env python3
from urllib.request import urlopen
import sys
def main():
triangle = read_triangle(urlopen(sys.argv[1]))
print("Maximum possible sum is", triangle_sum(triangle))
def read_triangle(from_file):
rows = []
for line in from_file:
values = [int(x) for x in line.strip().split()]
rows.append(values)
if len(values) != len(rows):
raise ValueError("Invalid triangle input")
return rows
def triangle_sum(triangle):
dp_row = triangle[-1]
for row in reversed(triangle[:-1]):
dp_row = [row[i] + max(dp_row[i], dp_row[i+1])
for i in range(len(row))]
return dp_row[0]
if __name__ == "__main__":
main()
ikelly@hephaestus ~ $ time python3 triangle_sum.py
https://gist.githubusercontent.com/swails/17ef52f3084df708816d/raw/aae1c494e69f0b3dad1eb6ea818f8f36d05be7a3/gistfile1.txt
Maximum possible sum is 724269
real0m0.582s
user0m0.191s
sys 0m0.013s
--
https://mail.python.org/mailman/listinfo/python-list
