Re: Is there a simpler way to modify all arguments in a function before using the arguments?
Miki Tebeka wrote:
>> Is there a simpler way to modify all arguments in a function before using
>> the arguments?
> You can use a decorator:
>
> from functools import wraps
>
> def fix_args(fn):
> @wraps(fn)
> def wrapper(*args):
> args = (arg.replace('_', '') for arg in args)
> return fn(*args)
>
> return wrapper
>
> @fix_args
> def foo(x, y):
> print(x)
> print(y)
I was tempted to post that myself, but he said /simpler/ ;)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Want to add dictionary keys to namespace?
Jeff Jeffries wrote:
> Smart people, Is there a way I can add a dictionaries keys to the python
> namespace? It would just be temporary as I am working with a large
> dictionary, and it would speed up work using an IDE. I look and find
> nothing... none of the keys have spaces and none are common names within
> the module.
>
> http://stackoverflow.com/questions/2597278/python-load-variables-in-a-
dict-into-namespace
>
> I do this:
>
> #Do this?
> dictionary = {"AppleSeed": None, "Has": None,"Horrible" :None,"Art"}
> for key in dictionary.keys():
> eval("%s=None"%key)
>
> #or do this?
> locals().update(dictionary)
>
> Any ideas?
You could instead use a dict subclass that lets you access values as
attributes:
>>> class Dict(dict):
... def __getattr__(self, name):
... return self[name]
... def __setattr__(self, name, value):
... self[name] = value
...
>>> d = Dict({"AppleSeed": None, "Has": None, "Horrible" : None, "Art": 42})
>>> d.Art
42
>>> d.AppleSeed
>>> d.AppleSeed = "spam"
>>> d
{'Has': None, 'Art': 42, 'AppleSeed': 'spam', 'Horrible': None}
--
http://mail.python.org/mailman/listinfo/python-list
Re: Is there a simpler way to modify all arguments in a function before using the arguments?
On Sat, Nov 10, 2012 at 3:05 PM, Paul Rubin wrote: > Chris Angelico writes: >> Contrived example: >> def send_email(from, to, subj, body, whatever, other, headers, you, like): > > That should be a dictionary with the header names as indexes. In fact > there are already some email handling modules in the stdlib that > represent headers that way. That's also plausible, but keyword arguments do make sense. And this was a top-of-the-head contrived example; I'm sure there are plenty of good use-cases. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing characters outside of the ASCII range
Le vendredi 9 novembre 2012 18:17:54 UTC+1, danielk a écrit :
> I'm converting an application to Python 3. The app works fine on Python 2.
>
>
>
> Simply put, this simple one-liner:
>
>
>
> print(chr(254))
>
>
>
> errors out with:
>
>
>
> Traceback (most recent call last):
>
> File "D:\home\python\tst.py", line 1, in
>
> print(chr(254))
>
> File "C:\Python33\lib\encodings\cp437.py", line 19, in encode
>
> return codecs.charmap_encode(input,self.errors,encoding_map)[0]
>
> UnicodeEncodeError: 'charmap' codec can't encode character '\xfe' in position
> 0: character maps to
>
>
>
> I'm using this character as a delimiter in my application.
>
>
>
> What do I have to do to convert this string so that it does not error out?
-
There is nothing wrong in having the character with
the code point 0xfe in the cp437 coding scheme as
a delimiter.
If it is coming from a byte string, you should
decode it properly
>>> b'=\xfe=\xfe='.decode('cp437')
'=■=■='
or you can use directly the unicode equivalent
>>> '=\u25a0=\u25a0='
'=■=■='
That's for "input". For "output" see:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/c29f2f7f5a4962e8#
The choice of that character as a delimiter is not wrong.
It's a little bit unfortunate, because it falls high in
the "unicode table".
>>> import fourbiunicode as fu
>>> fu.UnicodeBlock('\u25a0')
'Geometric Shapes'
>>>
>>> fu.UnicodeBlock(b'\xfe'.decode('cp437'))
'Geometric Shapes'
(Another form of explanation)
jmf
--
http://mail.python.org/mailman/listinfo/python-list
Format specification mini-language for list joining
Hello
Lately I have been writing a lot of list join() operations variously including
(and included in) string format() operations.
For example:
temps = [24.369, 24.550, 26.807, 27.531, 28.752]
out = 'Temperatures: {0} Celsius'.format(
', '.join('{0:.1f}'.format(t) for t in temps)
)
# => 'Temperatures: 24.4, 24.6, 26.8, 27.5, 28.8 Celsius'
This is just a simple example, my actual code has many more join and format
operations, split into local variables as needed for clarity.
Then I remembered that Ye Old Common Lisp's format operator had built-in list
traversing capabilities[1]:
(format t "Temperatures: ~{~1$~^, ~} Celsius" temps)
That format string (the part in the middle that looks like line noise) is
admittedly arcane, but it's parsed like this:
~{take next argument (temp) and start iterating over its contents
~1$ output a floating point number with 1 digit precision
~^break the loop if there are no more items available
", " (otherwise) output a comma and space
~}end of the loop body
Now, as much as I appreciate the heritage of Lisp, I won't deny than its format
string mini-language is EVIL. As a rule, format string placeholders should not
include *imperative statements* such as for, break, continue, and if. We don't
need a Turing-complete language in our format strings. Still, this is the
grand^n-father of Python's format strings, so it's interesting to look at how
it used to approach the list joining issue.
Then I asked myself: can I take the list joining capability and port it over to
Python's format(), doing away with the overall ugliness?
Here is what I came up with:
out = 'Temperatures: {0:", ":.1f} Celsius'.format(temps)
# => 'Temperatures: 24.4, 24.6, 26.8, 27.5, 28.8 Celsius'
Here ", " is the joiner between the items and <.1f> is the format string for
each item.
The way this would work is by defining a specific Format Specification
Mini-Language for sequences (such as lists, tuples, and iterables).
A Format Specification Mini-Language (format_spec) is whatever follows the
first colon in a curly brace placeholder, and is defined by the argument's
class, so that it can vary wildly among different types.[2]
The root class (object) defines the generic format_spec we are accustomed to[3]:
[[fill]align][sign][#][0][width][,][.precision][type]
But that doesn't mean that more complex types should not define extensions or
replacements. I propose this extended format_spec for sequences:
seq_format_spec ::= join_string [":" item_format_spec] | format_spec
join_string ::= '"' join_string_char* '"' | "'" join_string_char* "'"
join_string_char ::=
item_format_spec ::= format_spec
That is, if the format_spec for a sequence starts with ' or " it would be
interpreted as a join operation (eg. {0:", "} or {0:', '}) optionally followed
by a format_spec for the single items: {0:", ":.1f}
If the format_spec does not start with ' or ", of if the quote is not balanced
(does not appear again in the format_spec), then it's assumed to be a generic
format string and the implementation would call super(). This is meant for
backwards compatibility with existing code that may be using the generic
format_spec over various sequences.
I do think that would be quite readable and useful. Look again at the example:
out = 'Temperatures: {0:", ":.1f} Celsius'.format(temps)
As a bonus, it allows nested joins, albeit only for simple cases. For example
we could format a dictionary's items:
temps = {'Rome': 26, 'Paris': 21, 'New York': 18}
out = 'Temperatures: {0:", ":" ":s}'.format(temps.items())
# => 'Temperatures: Rome 26, Paris 21, New York 18'
Here the format_spec for temps.items() is <", ":" ":s>. Then ", " would be used
as a joiner between the item tuples and <" ":s> would be passed over as the
format_spec for each tuple. This in turn would join the tuple's items using a
single space and output each item with its simple string format. This could go
on and on as needed, adding a colon and joiner string for each nested join
operation.
A more complicated mini-language would be needed to output dicts using
different format strings for keys and values, but I think that would be veering
over to unreadable territory.
What do you think?
I plan to write this as a module and propose it to Python's devs for inclusion
in the main tree, but any criticism is welcome before I do that.
-Tobia
[1] http://www.gigamonkeys.com/book/a-few-format-recipes.html
[2] http://docs.python.org/3/library/string.html#formatstrings
[3] http://docs.python.org/3/library/string.html#formatspec
--
http://mail.python.org/mailman/listinfo/python-list
Re: Numpy combine channels
On 11/09/2012 11:30 PM, Aahz wrote: > In article , > MRAB wrote: >> >> >> But should they be added together to make mono? >> >> Suppose, for example, that both channels have a maximum value. Their >> sum would be _twice_ the maximum. >> >> Therefore, I think that it should probably be the average. >> > (a[:, 0] + a[:, 1]) / 2 >> array([1, 1, 2]) > I'd actually think it should be the max. Consider a stereo where one > side is playing a booming bass while the other side is playing a rest > note -- should the mono combination be half as loud as as the bass? max would sound awful. The right answer is to add them with weighting, then scale the whole waveform according to a new calculation of clipping. Just like a mixer, you have level controls on each input, then an overall gain. So if the inputs were x and y, the output would be gain *( x_scale * x + y_scale * y), but it'd normally be done in two passes, so as to minimize the places that are clipped, while maximizing the average. it's also possible to have gain vary across the time axis, like an agc. But you wouldn't want that as a default, as it'd destroy the dynamics of a musical piece. One more consideration. If these are unsigned values (eg. 0 to 255), then you should adjust both signals by 128 before storing them as signed values, do your arithmetic, and then adjust again by adding 128. You could do the algebraic equivalent, but the programming would be much simpler on signed values. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a simpler way to modify all arguments in a function before using the arguments?
On Friday, November 9, 2012 8:16:12 PM UTC-5, Steven D'Aprano wrote: > On Fri, 09 Nov 2012 20:05:26 -0500, Roy Smith wrote: > > > > > In article <[email protected]>, > > > [email protected] wrote: > > > > > >> Is there a simpler way to modify all arguments in a function before > > >> using the arguments? > > >> > > >> For example, can the below code, in the modify arguments section be > > >> made into a few statements? > > >> > > >> def someComputation (aa, bb, cc, dd, ee, ff, gg, hh): > > >># modify arguments > > >># -- > > >> aa = aa.replace (³_² , ³²) > > >> bb= bb.replace (³_² , ³²) > > >> cc = cc.replace (³_² , ³²) > > >> dd = dd.replace (³_² , ³²) > > >> ee = ee.replace (³_² , ³²) > > >> ff = ff.replace (³_² , ³²) > > >> gg = gg.replace (³_² , ³²) > > >> hh = hh.replace (³_² , ³²) > > >> > > >># use the arguments > > >># - > > >># > > > > > > You could do something like (not error checked)... > > > > > > def someComputation(*args): > > > new_args = [arg.replace("_", "") for arg in args] aa, bb, cc, dd, > > > ee, ff, gg, hh = new_args > > > > > > but that's pretty weird. I suspect you just want to pass a list instead > > > of a bunch of discrete arguments. > > > > > > I agree with everything you say except that it is pretty weird. As far as > > I am concerned, it isn't weird at all. > > > > If you need named parameters: > > > > def someComputation(aa, bb, cc, dd, ee, ff, gg, hh): > > aa, bb, cc, dd, ee, ff, gg, hh = [arg.replace("_", "") > > for arg in (aa. bb, cc, dd, ee, ff, gg, hh)] > > ... > > > > > > > > -- > > Steven Thanks to all. Steve's example is the one I will try next week. Passing in lists, will work but it requires extra coding from the calling routines to build the list. Discrete arguments make sense. Also, what is the problem passing in 7 or more arguments? Thanks, Bruce -- http://mail.python.org/mailman/listinfo/python-list
Re: How to print python commands automatically?
On Nov 9, 10:41 pm, Peng Yu wrote: > I have to explicitly specify the modules I want to ignore. Is there a > way to ignore all the modules by default? Is this your problem? http://bugs.python.org/issue10685 -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a simpler way to modify all arguments in a function before using the arguments?
In article , Peter Otten <[email protected]> wrote: >Miki Tebeka wrote: > >>> Is there a simpler way to modify all arguments in a function before using >>> the arguments? >> >> You can use a decorator: >> >> from functools import wraps >> >> def fix_args(fn): >> @wraps(fn) >> def wrapper(*args): >> args = (arg.replace('_', '') for arg in args) >> return fn(*args) >> >> return wrapper >> >> @fix_args >> def foo(x, y): >> print(x) >> print(y) > >I was tempted to post that myself, but he said /simpler/ ;) >From my POV, that *is* simpler. When you change the parameters for foo, you don't need to change the arg pre-processing. Also allows code reuse, probably any program needing this kind of processing once will need it again. -- Aahz ([email protected]) <*> http://www.pythoncraft.com/ "Normal is what cuts off your sixth finger and your tail..." --Siobhan -- http://mail.python.org/mailman/listinfo/python-list
Re: Single leading dash in member variable names?
In article , Ian Kelly wrote: >On Tue, Sep 11, 2012 at 12:45 PM, wrote: >> >> Python noob here. Trying to understand a particular syntax: >> >> class stuff: >> def __init__(self): >> self._bongo = "BongoWorld" >> >> What is the significance of the leading underscore in "self._bongo"? >> I've seen this a few times and, after looking through PEP 8, I didn't >> see anything relevant, but I could have missed it. > >Single leading underscore is a convention indicating that the name >should be considered private and not used externally. It's a softer >version of the double leading underscore that means basically the same >thing but has syntactic significance. Note that the convention is rooted in an actual semantic meaning for single underscore: ``from foo import *`` ignores any module global names in foo that start with a single leading underscore. Obviously, this has little effect for most Python programs because you DON'T USE ``import *``. -- Aahz ([email protected]) <*> http://www.pythoncraft.com/ "Normal is what cuts off your sixth finger and your tail..." --Siobhan -- http://mail.python.org/mailman/listinfo/python-list
Re: Python3.3 str() bug?
On 9 November 2012 11:08, Helmut Jarausch wrote:
> On Fri, 09 Nov 2012 10:37:11 +0100, Stefan Behnel wrote:
>
>> Helmut Jarausch, 09.11.2012 10:18:
>>> probably I'm missing something.
>>>
>>> Using str(Arg) works just fine if Arg is a list.
>>> But
>>> str([],encoding='latin-1')
>>>
>>> gives the error
>>> TypeError: coercing to str: need bytes, bytearray or buffer-like object,
>>>list found
>>>
>>> If this isn't a bug how can I use str(Arg,encoding='latin-1') in general.
>>> Do I need to flatten any data structure which is normally excepted by str()
>>> ?
>>
>> Funny idea to call this a bug in Python. What your code is asking for is to
>> decode the object you pass in using the "latin-1" encoding. Since a list is
>> not something that is "encoded", let alone in latin-1, you get an error,
>> and actually a rather clear one.
>>
>> Note that this is not specific to Python3.3 or even 3.x. It's the same
>> thing in Py2 when you call the equivalent unicode() function.
>>
>
> For me it's not funny, at all.
I think the problem is that the str constructor does two fundamentally
different things depending on whether you have supplied the encoding
argument. From help(str) in Python 3.2:
| str(object[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
So str(obj) returns obj.__str__() but str(obj, encoding='xxx') decodes
a byte string (or a similar object) using a given encoding. In most
cases obj will be a byte string and it will be equivalent to using
obj.decode('xxx').
I think the help text is a little confusing. It says that encoding
defaults to sys.getdefaultencoding() but doesn't clarify but this only
applies if errors is given as a keyword argument since otherwise no
decoding is performed. Perhaps the help text would be clearer if it
listed the two operations as two separate cases e.g.:
str(object)
Returns a string object from object.__str__() if it is defined or
otherwise object.__repr__(). Raises TypeError if the returned result
is not a string object.
str(bytes, [encoding[, errors]])
If either encoding or errors is supplied, creates a new string
object by decoding bytes with the specified encoding. The bytes
argument can be any object that supports the buffer interface.
encoding defaults to sys.getdefaultencoding() and errors defaults to
'strict'.
> Whenever Python3 encounters a bytestring it needs an encoding to convert it to
> a string.
Well actually Python 3.3 will happily convert it to a string using
bytes.__repr__ if you don't supply the encoding argument:
>>> str(b'this is a byte string')
"b'this is a byte string'"
> If I feed a list of bytestrings or a list of list of bytestrings to
> 'str' , etc, it should use the encoding for each bytestring component of the
> given data structure.
You can always do:
[str(obj, encoding='xxx') for obj in list_of_byte_strings]
> How can I convert a data strucure of arbitrarily complex nature, which
> contains
> bytestrings somewhere, to a string?
Using str(obj) or repr(obj). Of course this relies on the author of
type(obj) defining the appropriate methods and writing the code that
actually converts the object into a string.
> This problem has arisen while converting a working Python2 script to
> Python3.3.
> Since Python2 doesn't have bytestrings it just works.
In Python 2 ordinary strings are byte strings.
> Tell me how to convert str(obj) from Python2 to Python3 if obj is an
> arbitrarily complex data structure containing bytestrings somewhere
> which have to be converted to strings with a given encoding?
The str function when used to convert a non-string object into a
string knows nothing about the object you provide except whether it
has __str__ or __repr__ methods. The only processing that is done is
to check that the returned result was actually a string:
>>> class A:
... def __str__(self):
... return []
...
>>> a = A()
>>> str(a)
Traceback (most recent call last):
File "", line 1, in
TypeError: __str__ returned non-string (type list)
Perhaps it would help if you would explain why you want the string
object. I would only use str(complex_object) as something to print for
debugging so I would actually want it to show me which strings were
byte strings by marking them with a 'b' prefix and I would also want
it to show non-ascii characters with a \x hex code as it already does:
>>> a = [1, 2, b'caf\xe9']
>>> str(a)
"[1, 2, b'caf\\xe9']"
If I wanted to convert the object to a string in order to e.g. save it
to a file or database then I would write a function to create the
string that I wanted. I would only use str() to convert elementary
types like int and
Re: Format specification mini-language for list joining
Tobia Conforto writes: > Now, as much as I appreciate the heritage of Lisp, I won't deny than > its format string mini-language is EVIL. ... Still, this is the > grand^n-father of Python's format strings... Without having yet read the rest of your post carefully, I wonder the particular historical point above is correct. Python's format strings are pretty much the same as C's format strings, which go back to the beginnings of C in the 1970's, maybe even to some forerunner of C, like maybe FOCAL or something like that. It's possible that Common Lisp's format strings came from some earlier Lisp, but Common Lisp itself was a 1980's thing. Maybe some Lisp historian would know. -- http://mail.python.org/mailman/listinfo/python-list
Re: Format specification mini-language for list joining
On Sat, 10 Nov 2012 02:26:28 -0800, Tobia Conforto wrote:
> Hello
>
> Lately I have been writing a lot of list join() operations variously
> including (and included in) string format() operations.
>
> For example:
>
> temps = [24.369, 24.550, 26.807, 27.531, 28.752]
>
> out = 'Temperatures: {0} Celsius'.format(
> ', '.join('{0:.1f}'.format(t) for t in temps)
> )
>
> # => 'Temperatures: 24.4, 24.6, 26.8, 27.5, 28.8 Celsius'
>
> This is just a simple example, my actual code has many more join and
> format operations, split into local variables as needed for clarity.
Good plan! But then you suggest:
> Here is what I came up with:
> out = 'Temperatures: {0:", ":.1f} Celsius'.format(temps)
> # => 'Temperatures: 24.4, 24.6, 26.8, 27.5, 28.8 Celsius'
>
> Here ", " is the joiner between the items and <.1f> is the format string
> for each item.
And there goes all the clarity.
Is saving a few words of Python code so important that you would prefer
to read and write an overly-terse, cryptic mini-language?
If you're worried about code re-use, write a simple helper function:
def format_items(format, items):
template = '{0:%s}' % format
return ', '.join(template.format(item) for item in items)
out = 'Temperatures: {0} Celsius'.format( format_items('.1f, temps) )
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: Format specification mini-language for list joining
On Sat, Nov 10, 2012 at 5:51 PM, Paul Rubin wrote:
> […] Python's format strings are pretty much the same as C's format strings […]
You’re thinking about the old % syntax, 'Hello %s!' % 'world'. The OP
meant the new str.format syntax ('Hello {}!'.format('world')).
---
IMO, the idea is useless. First of, format() exists since 2.6, which
was released in 2008. So, it would be hard to use it anyways. Second
of, which is more readable:
out = 'Temperatures: {0:", ":.1f} Celsius'.format(temps)
or
out = 'Temperatures: {} Celsius'.format(', '.join(temps))
101% of the Python community would opt for the second format. Because
your format is cryptic. The current thing is already
not-quite-easy-to-understand when you use magic (aligning, type
converting etc.), but your proposition is much worse. And I hate to
consult the docs while working on something. As I said, it’s hard to
even get this one changed because str.format is 4 years old.
--
Kwpolska
stop html mail | always bottom-post
www.asciiribbon.org | www.netmeister.org/news/learn2quote.html
GPG KEY: 5EAAEA16
--
http://mail.python.org/mailman/listinfo/python-list
How to install libxml2-devel and libxslt-devel in Windows ?
Hi, I have Windows XP and Python 2.7.x I download and install libxml2-python-2.7.7.win32-py2.7.exe, From here: http://users.skynet.be/sbi/libxml-python/ This file has both libxml2 AND libxslt. But, I also need libxml2-devel and libxslt-devel for python 2.7. Are binaries for win32 available for that? How do I to get these devel files? In Ubuntu fro example this is all in the repositories. But I guess I don't understand how to get this in Windows... Thank you very much. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a simpler way to modify all arguments in a function before using the arguments?
All, I never used decorators before. I saw Miki Tebeka's sample code and your rationale (Aahz) and I like it. For my application problem, decorators seem like a good solution. Thanks to all, Bruce On Saturday, November 10, 2012 10:35:12 AM UTC-5, Aahz wrote: > In article , > > Peter Otten <[email protected]> wrote: > > >Miki Tebeka wrote: > > > > > >>> Is there a simpler way to modify all arguments in a function before using > > >>> the arguments? > > >> > > >> You can use a decorator: > > >> > > >> from functools import wraps > > >> > > >> def fix_args(fn): > > >> @wraps(fn) > > >> def wrapper(*args): > > >> args = (arg.replace('_', '') for arg in args) > > >> return fn(*args) > > >> > > >> return wrapper > > >> > > >> @fix_args > > >> def foo(x, y): > > >> print(x) > > >> print(y) > > > > > >I was tempted to post that myself, but he said /simpler/ ;) > > > > From my POV, that *is* simpler. When you change the parameters for foo, > > you don't need to change the arg pre-processing. Also allows code reuse, > > probably any program needing this kind of processing once will need it > > again. > > -- > > Aahz ([email protected]) <*> http://www.pythoncraft.com/ > > > > "Normal is what cuts off your sixth finger and your tail..." --Siobhan -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a simpler way to modify all arguments in a function before using the arguments?
On Sun, Nov 11, 2012 at 12:15 AM, wrote:
> Thanks to all.
> Steve's example is the one I will try next week.
> Passing in lists, will work but it requires extra coding from the calling
> routines to build the list.
Not necessarily! Watch:
def foo(*args):
print(repr(args))
foo("Hello","world","!")
('Hello', 'world', '!')
Okay, that's not technically a list, it's a tuple, but same diff. Your
callers still see you as taking separate arguments, but you take them
as a single collection.
ChrisA
--
http://mail.python.org/mailman/listinfo/python-list
Method default argument whose type is the class not yet defined
What is the best solution to solve the following problem in Python 3.3? import math >>> class Point: ... def __init__(self, x=0, y=0): ... self.x = x ... self.y = y ... def __sub__(self, other): ... return Point(self.x - other.x, self.y - other.y) ... def distance(self, point=Point()): ... """Return the distance from `point`.""" ... return math.sqrt((self - point).x ** 2 + (self - point).y ** 2) ... Traceback (most recent call last): File "", line 1, in File "", line 5, in Point NameError: name 'Point' is not defined I propose three solutions. The first one: >>> class Point: ... def __init__(self, x=0, y=0): ... self.x = x ... self.y = y ... def __sub__(self, other): ... return Point(self.x - other.x, self.y - other.y) ... def distance(self, point=None): ... p = point if point else Point() ... return math.sqrt((self - p).x ** 2 + (self - p).y ** 2) ... >>> p = Point() >>> p.distance() 0.0 >>> p.distance(Point(3, 4)) 5.0 The second one: >>> class Point: ... def __init__(self, x=0, y=0): ... self.x = x ... self.y = y ... def __sub__(self, other): ... return Point(self.x - other.x, self.y - other.y) ... >>> def distance(self, point=Point()): ... return math.sqrt((self - point).x ** 2 + (self - point).y ** 2) ... >>> Point.distance = distance >>> p = Point() >>> p.distance(Point(3, 4)) 5.0 The last one: >>> class Point: ... def __init__(self, x=0, y=0): ... self.x = x ... self.y = y ... Point.distance = distance ... def __sub__(self, other): ... return Point(self.x - other.x, self.y - other.y) ... >>> def distance(self, point=Point()): ... return math.sqrt((self - point).x ** 2 + (self - point).y ** 2) ... >>> p = Point() >>> p.distance(Point(3, 4)) 5.0 Is there a better solution? -- Jennie -- http://mail.python.org/mailman/listinfo/python-list
Re: Method default argument whose type is the class not yet defined
On Sun, Nov 11, 2012 at 6:33 AM, Jennie wrote: > ... def distance(self, point=None): > ... p = point if point else Point() I'd go with this one. Definitely not the third one, which mutates the class according to a current global every time a Point is instantiated - could be *extremely* confusing if the name distance were ever rebound. You could also fiddle with the default args: >>> class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __sub__(self, other): return Point(self.x - other.x, self.y - other.y) def distance(self, point="Point()"): return math.sqrt((self - p).x ** 2 + (self - p).y ** 2) >>> Point.distance.__defaults__=Point(), # has to be a tuple ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Method default argument whose type is the class not yet defined
On 11/10/2012 2:33 PM, Jennie wrote: What is the best solution to solve the following problem in Python 3.3? import math >>> class Point: ... def __init__(self, x=0, y=0): ... self.x = x ... self.y = y ... def __sub__(self, other): ... return Point(self.x - other.x, self.y - other.y) ... def distance(self, point=Point()): ... """Return the distance from `point`.""" ... return math.sqrt((self - point).x ** 2 + (self - point).y ** 2) ... Traceback (most recent call last): File "", line 1, in File "", line 5, in Point NameError: name 'Point' is not defined I propose three solutions. The first one: >>> class Point: ... def __init__(self, x=0, y=0): ... self.x = x ... self.y = y ... def __sub__(self, other): ... return Point(self.x - other.x, self.y - other.y) ... def distance(self, point=None): ... p = point if point else Point() ... return math.sqrt((self - p).x ** 2 + (self - p).y ** 2) ... >>> p = Point() >>> p.distance() 0.0 >>> p.distance(Point(3, 4)) 5.0 What I do not like about this one is that it creates a new 0 point each time one is needed. Two solutions: change Point() to point0 in the distance function and create point0 = Point() after the class. -or- instead of p = line, px,py = point.x, point.y if point else 0.0, 0.0 The second one: >>> class Point: ... def __init__(self, x=0, y=0): ... self.x = x ... self.y = y ... def __sub__(self, other): ... return Point(self.x - other.x, self.y - other.y) ... >>> def distance(self, point=Point()): ... return math.sqrt((self - point).x ** 2 + (self - point).y ** 2) ... >>> Point.distance = distance >>> p = Point() >>> p.distance(Point(3, 4)) 5.0 my first thought The last one: >>> class Point: ... def __init__(self, x=0, y=0): ... self.x = x ... self.y = y ... Point.distance = distance ... def __sub__(self, other): ... return Point(self.x - other.x, self.y - other.y) ... >>> def distance(self, point=Point()): ... return math.sqrt((self - point).x ** 2 + (self - point).y ** 2) ... >>> p = Point() >>> p.distance(Point(3, 4)) 5.0 Is there a better solution? -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Method default argument whose type is the class not yet defined
On 11/10/2012 09:29 PM, Terry Reedy wrote: On 11/10/2012 2:33 PM, Jennie wrote: I propose three solutions. The first one: >>> class Point: ... def __init__(self, x=0, y=0): ... self.x = x ... self.y = y ... def __sub__(self, other): ... return Point(self.x - other.x, self.y - other.y) ... def distance(self, point=None): ... p = point if point else Point() ... return math.sqrt((self - p).x ** 2 + (self - p).y ** 2) What I do not like about this one is that it creates a new 0 point each time one is needed. Two solutions: change Point() to point0 in the distance function and create point0 = Point() after the class. -or- instead of p = line, px,py = point.x, point.y if point else 0.0, 0.0 Thanks, I like the second one :) -- Jennie -- http://mail.python.org/mailman/listinfo/python-list
Re: Format specification mini-language for list joining
Kwpolska wrote:
> > out = 'Temperatures: {0:", ":.1f} Celsius'.format(temps)
>
> [...] your format is cryptic.
Thank you for your criticism, I'll think it over. The reason I find it readable
(-enough) is because even without knowing what format language is supported by
the temps object, you can tell that "it" (the 0th argument in this case) is
what's going to be serialized in that place.
Everything after the first colon is game anyways, meaning you'll have to look
it up in the docs, because it's defined somewhere in the class hierarchy of the
object being serialized. The fact that 99% of classes don't define a __format__
method and thus fall back on object's implementation, with it's alignment and
padding operators, is IMHO irrelevant. It's still something you can't pretend
to know out of the box, because it's supposed to be customizable by classes.
Knowing this, if you know that the temps object is a list of floats, then I
think it'd be pretty obvious what the ", " and the :.1f should do.
> As I said, it’s hard to even get this one changed
> because str.format is 4 years old.
Again, I beg to differ. I'm not proposing any change to format (that would be
madness). What I'm proposing is the addition of a customized __format__ method
to a few types, namely lists and sequences, that currently lack it (as do 99%
of classes) and fall back to object's implementation. Which is kind of
pointless with lists, as joining is by far the thing most often done to them
when formatting.
Tobia
--
http://mail.python.org/mailman/listinfo/python-list
Re: Py3k Signal Handling
Jonathan Hayward pobox.com> writes: > > What needs changing here and how should I change it so that handle_signal() > is called and then things keep on ticking? So that it is called when exactly? Your message isn't clear as to what isn't working for you. Regards Antoine. -- http://mail.python.org/mailman/listinfo/python-list
Re: Method default argument whose type is the class not yet defined
On 11/10/2012 03:51 PM, Jennie wrote: > On 11/10/2012 09:29 PM, Terry Reedy wrote: > >> On 11/10/2012 2:33 PM, Jennie wrote: >>> >>> I propose three solutions. The first one: >>> >>> >>> class Point: >>> ... def __init__(self, x=0, y=0): >>> ... self.x = x >>> ... self.y = y >>> ... def __sub__(self, other): >>> ... return Point(self.x - other.x, self.y - other.y) >>> ... def distance(self, point=None): >>> ... p = point if point else Point() >>> ... return math.sqrt((self - p).x ** 2 + (self - p).y ** 2) > >> What I do not like about this one is that it creates a new 0 point each >> time one is needed. Two solutions: >> >> change Point() to point0 in the distance function and create >> point0 = Point() >> after the class. >> >> -or- >> instead of p = line, >> px,py = point.x, point.y if point else 0.0, 0.0 > > Thanks, I like the second one :) > I like the first, once you fix the minor inefficiency in it; add the qualifier "is None" ... def distance(self, point=None): ... p = point if point is None else Point() ... return math.sqrt((self - p).x ** 2 + (self - p).y ** 2) The advantage it then has over the second one is that the whole class is defined inside the class. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
A gnarly little python loop
I'm trying to pull down tweets with one of the many twitter APIs. The particular one I'm using (python-twitter), has a call: data = api.GetSearch(term="foo", page=page) The way it works, you start with page=1. It returns a list of tweets. If the list is empty, there are no more tweets. If the list is not empty, you can try to get more tweets by asking for page=2, page=3, etc. I've got: page = 1 while 1: r = api.GetSearch(term="foo", page=page) if not r: break for tweet in r: process(tweet) page += 1 It works, but it seems excessively fidgety. Is there some cleaner way to refactor this? -- http://mail.python.org/mailman/listinfo/python-list
Re: A gnarly little python loop
On Sat, Nov 10, 2012 at 3:58 PM, Roy Smith wrote:
> I'm trying to pull down tweets with one of the many twitter APIs. The
> particular one I'm using (python-twitter), has a call:
>
> data = api.GetSearch(term="foo", page=page)
>
> The way it works, you start with page=1. It returns a list of tweets.
> If the list is empty, there are no more tweets. If the list is not
> empty, you can try to get more tweets by asking for page=2, page=3, etc.
> I've got:
>
> page = 1
> while 1:
> r = api.GetSearch(term="foo", page=page)
> if not r:
> break
> for tweet in r:
> process(tweet)
> page += 1
>
> It works, but it seems excessively fidgety. Is there some cleaner way
> to refactor this?
I'd do something like this:
def get_tweets(term):
for page in itertools.count(1):
r = api.GetSearch(term, page)
if not r:
break
for tweet in r:
yield tweet
for tweet in get_tweets("foo"):
process(tweet)
--
http://mail.python.org/mailman/listinfo/python-list
Re: A gnarly little python loop
On Sat, 10 Nov 2012 17:58:14 -0500, Roy Smith wrote: > The way it works, you start with page=1. It returns a list of tweets. > If the list is empty, there are no more tweets. If the list is not > empty, you can try to get more tweets by asking for page=2, page=3, etc. > I've got: > > page = 1 > while 1: > r = api.GetSearch(term="foo", page=page) > if not r: > break > for tweet in r: > process(tweet) > page += 1 > > It works, but it seems excessively fidgety. Is there some cleaner way > to refactor this? Seems clean enough to me. It does exactly what you need: loop until there are no more tweets, process each tweet. If you're allergic to nested loops, move the inner for-loop into a function. Also you could get rid of the "if r: break". page = 1 r = ["placeholder"] while r: r = api.GetSearch(term="foo", page=page) process_all(tweets) # does nothing if r is empty page += 1 Another way would be to use a for list for the outer loop. for page in xrange(1, sys.maxint): r = api.GetSearch(term="foo", page=page) if not r: break process_all(r) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Method default argument whose type is the class not yet defined
On Sat, 10 Nov 2012 20:33:05 +0100, Jennie wrote: [...] > I propose three solutions. The first one: > > >>> class Point: > ... def __init__(self, x=0, y=0): > ... self.x = x > ... self.y = y > ... def __sub__(self, other): > ... return Point(self.x - other.x, self.y - other.y) Don't do this, because it breaks subclassing. Your instance should dynamically get it's own class, not hard-code the name of Point. return self.__class__(self.x - other.x, self.y - other.y) That way, when you subclass Point, you can do arithmetic on the subclass instances and they will do the Right Thing. Note: Python's builtin numeric types don't do this, and it is a damned nuisance: py> class MyInt(int): ... pass ... py> a, b = MyInt(23), MyInt(42) py> assert type(a) is MyInt and type(b) is MyInt py> type(a + b) Back to your class: > ... def distance(self, point=None): > ... p = point if point else Point() > ... return math.sqrt((self - p).x ** 2 + (self - p).y ** 2) Almost but not quite. I assume that, in a full Point class, you would want Point(0, 0) to count as false in a boolean context. (A "falsey" value, like None, [], 0.0, etc.) So change the test to an explicit test for None, not just any falsey value: if point is None: point = self.__class__() # Allow subclassing to work. > The second one: > > >>> class Point: > ... def __init__(self, x=0, y=0): > ... self.x = x > ... self.y = y > ... def __sub__(self, other): > ... return Point(self.x - other.x, self.y - other.y) > ... > >>> def distance(self, point=Point()): > ... return math.sqrt((self - point).x ** 2 + (self - point).y ** 2) > ... > >>> Point.distance = distance Cute, but ugly and messy. You can inject methods into a class, of course, but that's an awfully big hammer to crack this tiny little nut. Your first solution is better. Here is a variation which, according to your tastes, may count as more or less ugly: inject the default value into the method: class Point: def distance(self, other=None): # None is a placeholder delta = self - other return math.sqrt(delta.x ** 2 + delta.y ** 2) Point.distance.__defaults__ = (Point(),) # In Python 2, use: # Point.distance.__func__.func_defaults = (Point(),) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Method default argument whose type is the class not yet defined
On 10 November 2012 19:33, Jennie wrote:
> What is the best solution to solve the following problem in Python 3.3?
>
> import math
class Point:
> ... def __init__(self, x=0, y=0):
> ... self.x = x
> ... self.y = y
> ... def __sub__(self, other):
> ... return Point(self.x - other.x, self.y - other.y)
> ... def distance(self, point=Point()):
> ... """Return the distance from `point`."""
> ... return math.sqrt((self - point).x ** 2 + (self - point).y ** 2)
> ...
> Traceback (most recent call last):
> File "", line 1, in
> File "", line 5, in Point
> NameError: name 'Point' is not defined
I would use namedtuple and make it so that an ordinary tuple could be
used as in place of a Point instance:
>>> import math
>>> from collections import namedtuple
>>> class Point(namedtuple('Point', ['x', 'y'])):
... def distance(self, other=(0, 0)):
... (myx, myy), (theirx, theiry) = self, other
... return math.sqrt((myx - theirx) ** 2 + (myy - theiry) ** 2)
...
>>> p = Point(3, 4)
>>> p.distance()
5.0
>>> p2 = Point(4, 5)
>>> p.distance(p2)
1.4142135623730951
Oscar
--
http://mail.python.org/mailman/listinfo/python-list
Re: Method default argument whose type is the class not yet defined
On Sun, Nov 11, 2012 at 12:13 PM, Steven D'Aprano wrote: > Almost but not quite. I assume that, in a full Point class, you would > want Point(0, 0) to count as false in a boolean context. (A "falsey" > value, like None, [], 0.0, etc.) I would not assume that. The origin is a point, just like any other. With a Line class, you could deem a zero-length line to be like a zero-element list, but Point(0,0) is more like the tuple (0,0) which is definitely True. In any case, this would not even matter, beyond unnecessary work; the bug would occur only if you seek the distance to Point(0,0), at which point[1] the code would throw out the incoming Point and go with the default of 0,0. So it'd result in the same distance. ChrisA [1] Sorry, couldn't resist -- http://mail.python.org/mailman/listinfo/python-list
Re: Method default argument whose type is the class not yet defined
On Sat, Nov 10, 2012 at 7:13 PM, Chris Angelico wrote: > I would not assume that. The origin is a point, just like any other. > With a Line class, you could deem a zero-length line to be like a > zero-element list, but Point(0,0) is more like the tuple (0,0) which > is definitely True. It's more like the number 0 than the tuple (0,0). 0 is the origin on a 1-dimensional number line. (0,0) is the origin on a 2-dimensional number plane. In fact, it might be pointed out that Point(0, 0) is a generalization of 0+0j, which is equal to 0. -- http://mail.python.org/mailman/listinfo/python-list
Re: Method default argument whose type is the class not yet defined
On Sun, Nov 11, 2012 at 1:43 PM, Ian Kelly wrote: > On Sat, Nov 10, 2012 at 7:13 PM, Chris Angelico wrote: >> I would not assume that. The origin is a point, just like any other. >> With a Line class, you could deem a zero-length line to be like a >> zero-element list, but Point(0,0) is more like the tuple (0,0) which >> is definitely True. > > It's more like the number 0 than the tuple (0,0). > > 0 is the origin on a 1-dimensional number line. > (0,0) is the origin on a 2-dimensional number plane. > > In fact, it might be pointed out that Point(0, 0) is a generalization > of 0+0j, which is equal to 0. Ah, good point. In any case, though, it'd be an utterly inconsequential bug. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Method default argument whose type is the class not yet defined
In article , Ian Kelly wrote: > On Sat, Nov 10, 2012 at 7:13 PM, Chris Angelico wrote: > > I would not assume that. The origin is a point, just like any other. > > With a Line class, you could deem a zero-length line to be like a > > zero-element list, but Point(0,0) is more like the tuple (0,0) which > > is definitely True. > > It's more like the number 0 than the tuple (0,0). > > 0 is the origin on a 1-dimensional number line. > (0,0) is the origin on a 2-dimensional number plane. > In fact, it might be pointed out that Point(0, 0) is a generalization > of 0+0j, which is equal to 0. If (0,0) is the origin on a plane, then (0,) should be the origin on a line. If you consider 0 + 0j to be the origin of a plane, then 0 is the origin of a line. Either way is plausible, but you need to be consistent. -- http://mail.python.org/mailman/listinfo/python-list
Re: A gnarly little python loop
On Nov 10, 2:58 pm, Roy Smith wrote: > I'm trying to pull down tweets with one of the many twitter APIs. The > particular one I'm using (python-twitter), has a call: > > data = api.GetSearch(term="foo", page=page) > > The way it works, you start with page=1. It returns a list of tweets. > If the list is empty, there are no more tweets. If the list is not > empty, you can try to get more tweets by asking for page=2, page=3, etc. > I've got: > > page = 1 > while 1: > r = api.GetSearch(term="foo", page=page) > if not r: > break > for tweet in r: > process(tweet) > page += 1 > > It works, but it seems excessively fidgety. Is there some cleaner way > to refactor this? I think your code is perfectly readable and clean, but you can flatten it like so: def get_tweets(term, get_page): page_nums = itertools.count(1) pages = itertools.imap(api.getSearch, page_nums) valid_pages = itertools.takewhile(bool, pages) tweets = itertools.chain.from_iterable(valid_pages) return tweets -- http://mail.python.org/mailman/listinfo/python-list
Re: Method default argument whose type is the class not yet defined
On Sat, Nov 10, 2012 at 7:53 PM, Roy Smith wrote: > In article , > Ian Kelly wrote: > >> On Sat, Nov 10, 2012 at 7:13 PM, Chris Angelico wrote: >> > I would not assume that. The origin is a point, just like any other. >> > With a Line class, you could deem a zero-length line to be like a >> > zero-element list, but Point(0,0) is more like the tuple (0,0) which >> > is definitely True. >> >> It's more like the number 0 than the tuple (0,0). >> >> 0 is the origin on a 1-dimensional number line. >> (0,0) is the origin on a 2-dimensional number plane. > >> In fact, it might be pointed out that Point(0, 0) is a generalization >> of 0+0j, which is equal to 0. > > > If (0,0) is the origin on a plane, then (0,) should be the origin on a > line. If you consider 0 + 0j to be the origin of a plane, then 0 is the > origin of a line. Either way is plausible, but you need to be > consistent. Where I wrote "(0,0) is the origin" above I was not referring to a point, not a tuple, but I can see how that was confusing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Method default argument whose type is the class not yet defined
On Sat, Nov 10, 2012 at 11:43 PM, Ian Kelly wrote: > Where I wrote "(0,0) is the origin" above I was not referring to a > point, not a tuple, but I can see how that was confusing. What I meant to say is I *was* referring to a point. Gah! -- http://mail.python.org/mailman/listinfo/python-list
Re: How to install libxml2-devel and libxslt-devel in Windows ?
goldtech, 10.11.2012 18:12: > I have Windows XP and Python 2.7.x > > I download and install libxml2-python-2.7.7.win32-py2.7.exe, From > here: http://users.skynet.be/sbi/libxml-python/ > > This file has both libxml2 AND libxslt. > > But, I also need libxml2-devel and libxslt-devel for python 2.7. Are > binaries for win32 available for that? > > How do I to get these devel files? In Ubuntu fro example this is all > in the repositories. But I guess I don't understand how to get this in > Windows... Assuming that you are actually looking for lxml rather than the plain libxml2/libxslt Python bindings and seeing that you don't fear installing software from arbitrary web pages, you should try this binary installer: http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml Stefan -- http://mail.python.org/mailman/listinfo/python-list
