Re: Compare source code
On Nov 5, 8:25 am, Terry Reedy wrote: > On 11/4/2010 10:47 PM, Rustom Mody wrote: > > > As far as I am concerned python would not be python if its > > indentation=structure went. However the original question -- mixing > > tabs and spaces is bad -- has got lost in the flames. Do the most > > die-hard python fanboys deny this? > > Of course not. Not mixing tabs and spaces has been the recommendation > for perhaps a decade. > > > And if not is it asking too much (say in python3) that mixing tabs and > > spaces > > > be flagged as an error or at least warning? > > Making all mixture an error was considered but rejected as causing too > much gratuitous breakage. One reason: you cut code from some source with > the 'other' style and paste into code with 'your' style. Should you be > *forced* (rather than merely advised) to convert before running the > result even once. Guido decided that there was enough breakage from > important things like unicode text and all new-style classes. That means that obvious and easily repairable-with-trivial-tools breakage is being traded for more insidious breakage > > On the other hand, someone said that ambiguous mixtures now are prohibited. > Not sure I understand the issues here. -- http://mail.python.org/mailman/listinfo/python-list
Re: Final state of underlying sequence in islice
> Shashank Singh wrote: > > > Are there any promises made with regard to final state of the underlying > > sequence that islice slices? Currently, there are no promises or guarantees about the final state of the iterator. To the extent the pure Python version in the docs differs from the CPython implementation in this regard, it is an accidental implementation detail. That being said, we could introduce some guarantees (earliest possible stop point, latest possible stop point, or decide to leave it undefined). I'm curious about your use case, as it might guide the decision. Are there any useful invariants that might arise from one choice or the other? The case is question seems a bit rare (the stop argument indexes an element before the iterator terminates, the step argument is more than one, the stop argument is not at the start plus an exact multiple of step, and you care about where the iterator is afterwards). The question is why you would have all of those conditions and not have stop==start+n*step. For regular slices, you seem to get useful invariants only when stop falls along the natural boundaries: s[a:b:step] + s[b:c:step] == s[a:c:step] # only when b == a+n*step So, it's not obvious what the semantics should be when b != a+n*step. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: functions, list, default parameters
On Thu, 04 Nov 2010 22:34:07 +, Mark Wooding wrote: > (Based on experience with other languages, I suspect that evaluating the > default expression afresh for each call where it's needed would be more > useful; but it's way too late to change that now.) Let's call the two strategies: defaults initialise on function definition (DID) defaults initialise on function call (DIC) I claim that when designing a general purpose language, DID (Python's existing behaviour) is better than DIC: (1) most function defaults only need to be set once; (2) it's easy to get DIC if the language uses DID, but hard the other way; (3) DIC is needless wasteful for common function definitions; (4) DIC can lead to surprising bugs. That last isn't a big concern, since DID can lead to surprising bugs as well *wink*, but it's worth mentioning the failure mode. #1 Most default values are things like True, False, None, integer or string literals. Since they're literals, they will never change, so you only need to set them once. #2 It's easy to get default values to initialise on function call in a language that uses initialisation on function definition semantics: just move the initialisation into the function body. Python has a particularly short and simple idiom for it: def f(x=None): if x is None: x = some_expression() But if the situations were reversed, it's hard to get the DID semantics: def f(x=None): if x is None: global _f_default_arg try: x = _f_default_arg except NameError: _f_default_arg = x = default_calculation() #3 Re-initialising default values is wasteful for many functions, perhaps the majority of them. (Of course, if you *need* DIC semantics, it isn't wasteful, but I'm talking about the situations where you don't care either way.) In current Python, nobody would write code like this: def f(x=None, y=None, z=None): if x is None: x = 1 if y is None: y = 2 if z is None: z = 3 but that's what the DIC semantics effectively does. When you need it, it's useful, but most of the time it's just a performance hit for no good reason. A smart compiler would factor out the assignment to a constant and do it once, when the function were defined -- which is just what DID semantics are. If you're unconvinced about this being a potential performance hit, consider: def expensive_function(): time.sleep(30) # simulate a lot of computation return 1.23456789 def f(x=expensive_function()): ... What would you prefer, the default value to be calculated once, or every time you called f()? #4 Just as DID leads to surprising behaviour with mutable defaults, so DIC can lead to surprising behaviour: def f(x=expression): do_something_with(x) If expression is anything except a literal, it could be changed after f is defined but before it is called. If so, then f() will change it's behaviour. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Hello, Everyone. I have a problem when using Pexpect module.
maybe i found why pexpect doesn't work in my environment. (but still, i
don't know how solve it)
my machine is actually a xen domain U, whose kernel is host's kernel.
when I test pexpect module directly on host machine, it works pretty fine.
and that's all I can do about it, maybe pexpect use pseudo-terminal, and
domain U doesn't support this well.
maybe nobody here has encountered this problem before, and i write here just
for everyone's information.
On Fri, Nov 5, 2010 at 2:46 PM, dachuan wrote:
> hi, everyone.
> When I use Pexpect Module, I met the following problem and don't know how
> to handle it.
> Any advice is appreciated !
>
> My environment:
> Linux node08_xen3.4.3_rhel5_1 2.6.18.8-xen #1 SMP Wed Jul 14 17:20:01 CST
> 2010 i686 i686 i386 GNU/Linux (FYI: this is a virtual machine.)
> Python 2.5.5
>
> and by the way, I have installed pexpect in another machine, and it works
> pretty well, its environment is:
> Linux WEB1 2.6.9-42.ELlargesmp #1 SMP Wed Jul 12 23:46:39 EDT 2006 x86_64
> x86_64 x86_64 GNU/Linux
> Python 2.5.5
>
>
> -bash-3.1$ ./ssh_mutual_trust.py -n
> Traceback (most recent call last):
> File "./ssh_mutual_trust.py", line 427, in
> start(sys.argv[1:])
> File "./ssh_mutual_trust.py", line 405, in start
> sshkeygen()
> File "./ssh_mutual_trust.py", line 137, in sshkeygen
> keygen_child = pexpect.spawn(new_keygen_cmd)
> File "/usr/local/lib/python2.5/site-packages/pexpect.py", line 430, in
> __init__
> self._spawn (command, args)
> File "/usr/local/lib/python2.5/site-packages/pexpect.py", line 530, in
> _spawn
> raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e))
> pexpect.ExceptionPexpect: Error! pty.fork() failed: out of pty devices
> -bash-3.1$
>
>
> --
> Dachuan Huang, Graduate Candidate
> ---
> Cluster and Grid Computing Lab
> Services Computing Technology and System Lab
> Huazhong University of Science and Technology
> Wuhan, 430074, China
> Tel: +86-15902733227
>
> Email: [email protected]
>
--
Dachuan Huang, Graduate Candidate
---
Cluster and Grid Computing Lab
Services Computing Technology and System Lab
Huazhong University of Science and Technology
Wuhan, 430074, China
Tel: +86-15902733227
Email: [email protected]
--
http://mail.python.org/mailman/listinfo/python-list
Re: Popen Question
In article <891a9a80-c30d-4415-ac81-bddd0b564...@g13g2000yqj.googlegroups.com>
moogyd wrote:
>[sde:st...@lbux03 ~]$ python
>Python 2.6 (r26:66714, Feb 21 2009, 02:16:04)
>[GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
>Type "help", "copyright", "credits" or "license" for more information.
import os, subprocess
os.environ['MYVAR'] = "myval"
p = subprocess.Popen(['echo', '$MYVAR'],shell=True)
Alain Ketterlin has already explained these to some extent.
Here is a bit more.
This runs, underneath:
['/bin/sh', '-c', 'echo', '$MYVAR']
(with arguments expressed as a Python list). /bin/sh takes the
string after '-c' as a command, and the remaining argument(s) if
any are assigned to positional parameters ($0, $1, etc).
If you replace the command with something a little more explicit,
you can see this:
>>> p = subprocess.Popen(
...[r'echo \$0=$0 \$1=$1', 'arg0', '$MYVAR'], shell=True)
>>> $0=arg0 $1=$MYVAR
p.wait()
0
>>>
(I like to call p.communicate() or p.wait(), although p.communicate()
is pretty much a no-op if you have not done any redirecting. Note that
p.communicate() does a p.wait() for you.)
p = subprocess.Popen(['echo', '$MYVAR'])
$MYVAR
This time, as Alain noted, the shell does not get involved so no
variable expansion occurs. However, you could do it yourself:
>>> p = subprocess.Popen(['echo', os.environ['MYVAR']])
>>> myval
p.wait()
0
>>>
p = subprocess.Popen('echo $MYVAR',shell=True)
myval
(here /bin/sh does the expansion, because you invoked it)
p = subprocess.Popen('echo $MYVAR')
>Traceback (most recent call last):
> File "", line 1, in
> File "/usr/lib64/python2.6/subprocess.py", line 595, in __init__
>errread, errwrite)
> File "/usr/lib64/python2.6/subprocess.py", line 1106, in
>_execute_child
>raise child_exception
>OSError: [Errno 2] No such file or directory
This attempted to run the executable named 'echo $MYVAR'. It did
not exist so the underlying exec (after the fork) failed. The
exception was passed back to the subprocess module, which raised
it in the parent for you to see.
If you were to create an executable named 'echo $MYVAR' (including
the blank and dollar sign) somewhere in your path (or use an explicit
path to it), it would run. I will also capture the actual output
this time:
$ cat '/tmp/echo $MYVAR'
#! /usr/bin/awk NR>1{print}
this is a self-printing file
anything after the first line has NR > 1, so gets printed
$ chmod +x '/tmp/echo $MYVAR'
$ python
Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> p = subprocess.Popen('/tmp/echo $MYVAR', stdout=subprocess.PIPE)
>>> print p.communicate()[0]
this is a self-printing file
anything after the first line has NR > 1, so gets printed
>>> p.returncode
0
>>>
Incidentally, fun with #!: you can make self-renaming scripts:
sh-3.2$ echo '#! /bin/mv' > /tmp/selfmove; chmod +x /tmp/selfmove
sh-3.2$ ls /tmp/*move*
/tmp/selfmove
sh-3.2$ /tmp/selfmove /tmp/I_moved
sh-3.2$ ls /tmp/*move*
/tmp/I_moved
sh-3.2$
or even self-removing scripts:
sh-3.2$ echo '#! /bin/rm' > /tmp/rmme; chmod +x /tmp/rmme
sh-3.2$ /tmp/rmme
sh-3.2$ /tmp/rmme
sh: /tmp/rmme: No such file or directory
(nothing to do with python, just the way #! interpreter lines work).
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: gmail (figure it out) http://web.torek.net/torek/index.html
--
http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
Terry Reedy writes: > If you add the normally redundant information in the form of explicit > dedents (anything starting with '#' and distinguishable from normal > comments), then it is not too hard to re-indent even after all indents > have been removed. I actually use such a trick in emacs, not with comments but with "pass" (emacs' python mode knows that pass end return end the current block). It's extrememly useful in heavily nested code, or if I need to paste some piece of code from one level to another. This lets my editor's auto-indenter do the right thing. And I see immediately if/when I did the nesting wrong. I really like "indentation as structure" (code is more compact and clearer), but I really hate that it relies on me putting the right spaces at the right place. I would love to be able to put, e.g., a period at the end of a line, to indicate that the next line is one level upper. Something like: for i in ... : for j in ... : whatever(i,j). . No lost vertical space (except when I decide it), no ambiguity. It looks to me like the exact opposite of ':'. End-of-line periods (or exclamation marks) would let tools reindent correctly in all cases. I don't think it conflicts with any other syntax. -- Alain. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On Fri, 05 Nov 2010 11:21:57 +0100, Alain Ketterlin wrote: > I really like "indentation as structure" (code is more compact and > clearer), but I really hate that it relies on me putting the right > spaces at the right place. Er what? You really like indentation as structure, but you don't like putting in the indentation? > I would love to be able to put, e.g., a > period at the end of a line, to indicate that the next line is one level > upper. Something like: > > for i in ... : > for j in ... : > whatever(i,j). > . How is that different from this? for i in ... : for j in ... : whatever(i,j) What's the point of the dots? Is that just to save you from having to hit shift-tab (or whatever your editor's decrease-indent command is)? > No lost vertical space (except when I decide it), no ambiguity. What lost vertical space are you worried about? > It looks > to me like the exact opposite of ':'. End-of-line periods (or > exclamation marks) would let tools reindent correctly in all cases. I > don't think it conflicts with any other syntax. for i in ... : for j in ... : n = 2. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On Thu, 04 Nov 2010 21:47:59 +, Tim Harig wrote: > I have seen huge patches caused by nothing more then some edit that > accidently added a trailing space to a large number of lines. White > space mangling happens all the time without people even knowing about > it. How does an edit accidentally add a trailing space to a large number of lines? (1) The programmer shifted the cursor to the end of the line, pressed space, moved down a line, shift to eol, press space, repeat a large number of times. I don't call that an "accident". (2) Some programmer used a tool that thought it was okay to add whitespace to the end of lines without being told to. I don't call that an accident either, I call that using a broken tool. So we keep coming back to work-arounds for tools that mangle your data for no good reason... -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On Thu, 04 Nov 2010 20:17:35 +, Seebs wrote: >> * I /do/ have a significant problem with cutting and pasting code in >> Python. In most languages, I can haul a chunk of code about, hit >> C-M-q, and Emacs magically indents the result properly. This is, >> unfortunately, impossible with Python. It has caused me real bugs, >> and I have to be extra careful to fix the indentation up. > > That was the thing which bit me the worst. I had a fairly large block > of code in a first-pass ugly program. I wanted to start refactoring it, > so I moved a big hunk of code into a method (with plans to further > refactor). It took about fifteen minutes to redo the logic. Well there's your problem -- you are relying on tools that operate by magic. Rather than re-create the logic, why not just hit Undo and then re-paste the code *without* the magic auto-reformat? Half a second, to undo and re- paste, followed by 10 or 20 seconds to select the appropriate lines and *explicitly* re-indent the lines to the correct level. For somebody who keeps tossing around the mantra that "explicit is better than implicit", you're amazingly reliant on a tool that performs massive, apparently irreversible formatting operations implicitly. And then rather than accept that your magic DWIM tool is unsuitable for the task you are putting it to, you then blame the data for not having error-correction codes that would allow *another* magic tool to fix the breakage caused by the first magic tool! -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Tools for turning Python code into XMI?
Hi Lawrence, I missed your answer because I didn't expect someone to respond after all this time. :-) On 2010-10-30 04:07, Lawrence D'Oliveiro wrote: >> I'm looking for a tool which can read Python files and write >> a corresponding XMI file for import into UML tools. > > UML ... isn’t that something more in vogue among the > Java/DotNet corporate-code-cutter-drone crowd? I don't know, that may well be. I still find it useful from time to time. I don't mind using tools I find useful, regardless who else uses them. :-) > Specifically, you’re asking for something that can parse a > dynamic language and generate a static structural > description of that code. I don’t think it’s possible, in > general. The tools I described in my previous post go a great length towards extracting the necessary information. But of course it's not reliably possible to extract all information, for example dynamically generated methods. But few Python programs use this extensively, and a good tool will extract most of the information interesting for me. I'm always surprised about what Pylint finds out about my source code. :) Given the existing open source tools, the problem rather seems to be the effort of implementing XMI generation than to get the information out of the Python code in the first place. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
Steven D'Aprano writes: >> I really like "indentation as structure" (code is more compact and >> clearer), but I really hate that it relies on me putting the right >> spaces at the right place. > > Er what? You really like indentation as structure, but you don't like > putting in the indentation? Exactly. I want the extra safety belt of not relying on spaces only. >> for i in ... : >> for j in ... : >> whatever(i,j). >> . > > How is that different from this? > > for i in ... : > for j in ... : > whatever(i,j) At this point exactly, there's no way to know what the indentation of the next line should be. My example above explicitely indicates the next line should be at the same level as "for j ...". Now suppose that, at this very place, you have to paste some other if/for/while block whose original indentation is not exactly aligned with the fragment above. No way to decide automatically how to align it (under "for j"? under "whatever"?). The dots I suggest are nothing more than tiny closing braces. > What's the point of the dots? Is that just to save you from having to hit > shift-tab (or whatever your editor's decrease-indent command is)? Redundancy. I often have deeply nested constructs, that I sometimes need to move around. A real pain, compared to brace-based languages, where constructs are explicitely terminated (i.e., not implicitely by the start of the next construct). Have automatically indented source is a useful and quick check. >> No lost vertical space (except when I decide it), no ambiguity. > > What lost vertical space are you worried about? You've cut the part of my message where I say that python's (vertical) compactness is one of its strong points. >> It looks to me like the exact opposite of ':'. End-of-line periods >> (or exclamation marks) would let tools reindent correctly in all >> cases. I don't think it conflicts with any other syntax. > for i in ... : > for j in ... : > n = 2. You're right, I forgot this one (probably because I never use this kind of elision). No big deal: for i in ... : for j in ... : n = 2. m = 3. . for j in ... : f = 2 . ... -- Alain. -- http://mail.python.org/mailman/listinfo/python-list
Re: functions, list, default parameters
Steven D'Aprano writes: > defaults initialise on function definition (DID) > defaults initialise on function call (DIC) > > I claim that when designing a general purpose language, DID (Python's > existing behaviour) is better than DIC: > > #1 Most default values are things like True, False, None, integer or > string literals. Since they're literals, they will never change, so you > only need to set them once. Right; so a half-decent compiler can notice this and optimize appropriately. Result: negligible difference. > #2 It's easy to get default values to initialise on function call in a > language that uses initialisation on function definition semantics: just > move the initialisation into the function body. Python has a particularly > short and simple idiom for it: > > def f(x=None): > if x is None: > x = some_expression() That's actually rather clumsy. Also, it's using in-band signalling: you've taken None and used it as a magic marker meaning `not supplied'. Suppose you want to distinguish /any/ supplied value from a missing argument: how do you do this /correctly/? The approaches I see are (a) to invent some unforgeable token or (b) emulate the argument processing by rifling through * and ** arguments. Solution (a) looks like this: _missing = ['missing'] def foo(arg = _missing): if arg is _missing: arg = ... ... But now _missing is kicking around in the module's namespace. Fixing that is rather messy. (No, you can't just `del' it.) Maybe this can be improved: def _magic(): _missing = ['missing'] def foo(arg = _missing): if arg is _missing: arg = ... ... return foo foo = _magic() del foo Solution (b) is just too grim. > But if the situations were reversed, it's hard to get the DID semantics: > > def f(x=None): > if x is None: > global _f_default_arg > try: > x = _f_default_arg > except NameError: > _f_default_arg = x = default_calculation() Ugh. This is artificially awful and doesn't correspond to existing Python DID semantics. * Python evaluates the default argument expression at function definition time. You've implemented delayed evaluation for no obvious reason. * Python evaluates the default argument expression in the enclosing environment. You've evaluated the expression in the function, again for no obvious reason. I'm interested to know why you did this. You know Python well enough that it's probably not just a misunderstanding, and you have enough integrity that it's probably not a dishonest debating tactic. A more faithful implementation of the actual semantics is considerably simpler. _default_arg = ... def func(arg = _default_arg): ... This is always correct, and actually simpler than even the standard but incorrect simulation of DIC. > #3 Re-initialising default values is wasteful for many functions, perhaps > the majority of them. (Of course, if you *need* DIC semantics, it isn't > wasteful, but I'm talking about the situations where you don't care > either way.) In current Python, nobody would write code like this: > > def f(x=None, y=None, z=None): > if x is None: x = 1 > if y is None: y = 2 > if z is None: z = 3 > > but that's what the DIC semantics effectively does. When you need it, > it's useful, but most of the time it's just a performance hit for no good > reason. A smart compiler would factor out the assignment to a constant > and do it once, when the function were defined -- which is just what DID > semantics are. Python's compiler is already clever enough to notice a constant expression when it sees one, and memoizing the default argument values is straightforward enough. There's therefore nothing to choose between the two on constant expressions. > If you're unconvinced about this being a potential performance hit, > consider: No, I can see that clearly, thanks. That comes up much less frequently than the case where a default argument value should be a fresh list or dictionary, in my experience. > What would you prefer, the default value to be calculated once, or every > time you called f()? This situation is rare enough that I'd put up with manual memoization. > #4 Just as DID leads to surprising behaviour with mutable defaults, so > DIC can lead to surprising behaviour: > > def f(x=expression): > do_something_with(x) > > If expression is anything except a literal, it could be changed after f > is defined but before it is called. If so, then f() will change it's > behaviour. Yes. Most usefully, the expression may refer to other argument values (to its left, only, presumably). This is frequently handy, not least in object constructors. This is an enormous sidetrack on what I'd hoped would be a parenthetical remark left unremarked. I'm not sure that further discussion will be especia
Re: Why "flat is better than nested"?
Am 28.10.2010 03:40, schrieb Steven D'Aprano: > [ snip a lot of wise words ] Can I put this (translated) in the german python wiki? I guess it might help more people to understand some decisions taken during python's development - and I'm to lazy to do something similar myself ;) Greetings from Berlin Jörg Gerlach -- http://mail.python.org/mailman/listinfo/python-list
Re: How convert list to nested dictionary?
Arnaud Delobelle wrote:
macm writes:
Hi Folks
How convert list to nested dictionary?
l
['k1', 'k2', 'k3', 'k4', 'k5']
result
{'k1': {'k2': {'k3': {'k4': {'k5': {}}
Regards
macm
reduce(lambda x,y: {y:x}, reversed(l), {})
d={}
while L : d={L.pop():d}
--
http://mail.python.org/mailman/listinfo/python-list
Silly newbie question - Carrot character (^)
Hey Everyone, Just curious - I'm working on a program which includes a calculation of a circle, and I found myself trying to use pi*radius^2, and getting errors that data types float and int are unsupported for "^". Now, I realized I was making the mistake of using '^' instead of "**". I've corrected this and its now working. However, what exactly does ^ do? I know its used in regular expressions but I can't seem to find anything about using it as an operator. Sadly my google foo is failing since the character gets filtered out. -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
On Fri, Nov 5, 2010 at 2:43 PM, Matty Sarro wrote: > Hey Everyone, > Just curious - I'm working on a program which includes a calculation of a > circle, and I found myself trying to use pi*radius^2, and getting errors > that data types float and int are unsupported for "^". Now, I realized I was > making the mistake of using '^' instead of "**". I've corrected this and its > now working. However, what exactly does ^ do? I know its used in regular > expressions but I can't seem to find anything about using it as an operator. > Sadly my google foo is failing since the character gets filtered out. It's a binary operator i think... something like xor. -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
2010/11/5 Matty Sarro : > Hey Everyone, > Just curious - I'm working on a program which includes a calculation of a > circle, and I found myself trying to use pi*radius^2, and getting errors > that data types float and int are unsupported for "^". Now, I realized I was > making the mistake of using '^' instead of "**". I've corrected this and its > now working. However, what exactly does ^ do? I know its used in regular > expressions but I can't seem to find anything about using it as an operator. > Sadly my google foo is failing since the character gets filtered out. > > -- > http://mail.python.org/mailman/listinfo/python-list > > Hi, see http://docs.python.org/reference/expressions.html#binary-bitwise-operations for bitwise XOR. The usage in regular expressions is different, of course; hth, vbr -- http://mail.python.org/mailman/listinfo/python-list
Re: How convert list to nested dictionary?
Boris Borcic wrote:
> Arnaud Delobelle wrote:
>> macm writes:
>>
>>> Hi Folks
>>>
>>> How convert list to nested dictionary?
>>>
>> l
>>> ['k1', 'k2', 'k3', 'k4', 'k5']
>> result
>>> {'k1': {'k2': {'k3': {'k4': {'k5': {}}
>>>
>>> Regards
>>>
>>> macm
>>
>> reduce(lambda x,y: {y:x}, reversed(l), {})
>>
>
> d={}
> while L : d={L.pop():d}
Iterating over the keys in normal order:
>>> keys = "abcde"
>>> d = outer = {}
>>> for key in keys:
... outer[key] = inner = {}
... outer = inner
...
>>> d
{'a': {'b': {'c': {'d': {'e': {}}
The "functional" variant:
>>> d = {}
>>> reduce(lambda outer, key: outer.setdefault(key, {}), "abcde", d)
{}
>>> d
{'a': {'b': {'c': {'d': {'e': {}}
In a single expression if you are willing to pay the price:
>>> reduce(lambda (accu, outer), key: (accu, outer.setdefault(key, {})),
"abcde", ({},)*2)[0]
{'a': {'b': {'c': {'d': {'e': {}}
Peter
--
http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
> However, what exactly does ^ do? Bitwise XOR: http://docs.python.org/py3k/reference/expressions.html#binary-bitwise-operations -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
On Fri, 5 Nov 2010 09:43:25 -0400
Matty Sarro wrote:
> now working. However, what exactly does ^ do? I know its used in regular
> expressions but I can't seem to find anything about using it as an operator.
It's the XOR operator. Try "help('^')" for more detail.
By the way, it's "caret", not "carrot".
--
D'Arcy J.M. Cain | Democracy is three wolves
http://www.druid.net/darcy/| and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
On Fri, Nov 5, 2010 at 7:26 PM, Krister Svanlund wrote: > On Fri, Nov 5, 2010 at 2:43 PM, Matty Sarro wrote: > > Hey Everyone, > > Just curious - I'm working on a program which includes a calculation of a > > circle, and I found myself trying to use pi*radius^2, and getting errors > > that data types float and int are unsupported for "^". Now, I realized I > was > > making the mistake of using '^' instead of "**". I've corrected this and > its > > now working. However, what exactly does ^ do? I know its used in regular > > expressions but I can't seem to find anything about using it as an > operator. > > Sadly my google foo is failing since the character gets filtered out. > > It's a binary operator i think... something like xor. > Yes. Infact '^' is binary XOR. >>> a = 4 >>> bin(a) '0b100' >>> b = 5 >>> bin(b) '0b101' >>> a ^ b 1 100 ^ 101 = 001 > -- > http://mail.python.org/mailman/listinfo/python-list > -- ~l0nwlf -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
Thanks everyone, that explains it :) -Matty On Fri, Nov 5, 2010 at 9:43 AM, Matty Sarro wrote: > Hey Everyone, > Just curious - I'm working on a program which includes a calculation of a > circle, and I found myself trying to use pi*radius^2, and getting errors > that data types float and int are unsupported for "^". Now, I realized I was > making the mistake of using '^' instead of "**". I've corrected this and its > now working. However, what exactly does ^ do? I know its used in regular > expressions but I can't seem to find anything about using it as an operator. > Sadly my google foo is failing since the character gets filtered out. > -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
On Nov 5, 2010, at 9:43 AM, Matty Sarro wrote: > Hey Everyone, > Just curious - I'm working on a program which includes a calculation of a > circle, and I found myself trying to use pi*radius^2, and getting errors > that data types float and int are unsupported for "^". Now, I realized I was > making the mistake of using '^' instead of "**". I've corrected this and its > now working. However, what exactly does ^ do? I know its used in regular > expressions but I can't seem to find anything about using it as an operator. > Sadly my google foo is failing since the character gets filtered out. As others have said, ^ is for XOR. That's buried here in the documentation: http://docs.python.org/release/2.7/reference/expressions.html#binary-bitwise-operations Not that I would have expected you to find it there since that's pretty dense. In fact, older versions of the Python doc used to describe this section as "for language lawyers" but I see they've changed that now. BTW the more common name for this character is caret (ka-RAY). Cheers Philip -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie qns : how do i use xmldiff?
I had to do some fishing around to figure this much out. Hope it helps. from input import * # From the xmldiff directory from fmes import * # From the xmldiff directory from format import *# From the xmldiff directory from StringIO import * # Build your original tree text1 = '123' stream1 = StringIO(text) tree1 = tree_from_stream(stream) # Build your modified tree text2 = '223' stream2 = StringIO(text2) tree2 = tree_from_stream(stream2) # Compare the trees formatter = InternalPrinter() corrector = FmesCorrector(formatter) corrector.process_trees(tree, tree2) ## OUTPUT: ## Instructions for modifying original to modified # [rename, /point[1]/y[1], x] # [insert-after, /point[1]/x[2], # # 2 # # ] # [remove, /point[1]/x[1]] > On Wednesday, February 03, 2010 1:38 AM sWrath swrath wrote: > Hi , > > I am pretty new to python , and reading up on it. > > Basically I am trying to compare xml files . I know difflib have it > but it does not work out as expected. I was looking at xmldiff , > unfortunately I am not able to find documentation how to call it from > python. Anyone knows a link or doc to it as I have been looking high > and low for few days? > > lastly , is there a py (or algorithm) where it behaves exactly like > diff ? Greatly appreciated. > > Thanks > john >> On Wednesday, February 03, 2010 3:34 PM Terry Reedy wrote: >> On 2/3/2010 1:38 AM, sWrath swrath wrote: >> >> When asking such a question, it is good to explain what sort of thing, >> in this case, 'xmldiff' is and where it is is from. Let us assume you >> meant xmldiff from >> >> http://www.logilab.org/859 >> >> It says it is a python tool that can "be used be used as a library or as >> a command line tool." It includes a README file. Have you read that? >> That says "USAGE ... Read the HELP.txt file.". Have you read *that*? >> HELP.txt seems to focus on command line usage. I would start with that. >> To use it as a library (via import ...), you might have to look at the >> source code as I did not see importing covered in my quick look at that >> file. >> >> Terry Jan Reedy >> Submitted via EggHeadCafe - Software Developer Portal of Choice >> FireAndForget Asynchronous Utility Class for SQL Server Inserts and Updates >> http://www.eggheadcafe.com/tutorials/aspnet/7a22d9a4-59fc-40b0-8337-75c76f14fb3b/fireandforget-asynchronous-utility-class-for-sql-server-inserts-and-updates.aspx -- http://mail.python.org/mailman/listinfo/python-list
What is the best way to handle a missing newline in the following case
I have an text file with the following numbers 1 3 5 7 3 9 Now the program reads in this file. When it encounters a '\n', it will do some stuff and then move to the next line. For example, it will read 1 and then '\n'. When it sees '\n', it will do some stuff and go on to read 3. The problem is when I get to the last line. When the program sees '\n' after the 9, everything works fine. However, when there isn't a '\n', the program doesn't process the last line. What would be the best approach to handle the case of the possible missing '\n' at the end of the file? -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the best way to handle a missing newline in the following case
chad wrote:
> I have an text file with the following numbers
>
> 1
> 3
> 5
> 7
> 3
> 9
>
>
>
> Now the program reads in this file. When it encounters a '\n', it will
> do some stuff and then move to the next line. For example, it will
> read 1 and then '\n'. When it sees '\n', it will do some stuff and go
> on to read 3.
>
> The problem is when I get to the last line. When the program sees '\n'
> after the 9, everything works fine. However, when there isn't a '\n',
> the program doesn't process the last line.
>
> What would be the best approach to handle the case of the possible
> missing '\n' at the end of the file?
Don't split the data into lines yourself, delegate to python
>>> with open("tmp.txt", "wb") as f:
... f.write("1\n2\n3\r\n4\r5")
...
>>> for line in open("tmp.txt", "U"):
... print repr(line)
...
'1\n'
'2\n'
'3\n'
'4\n'
'5'
As you can see "\n", "\r\n" and "\r" are all converted to "\n". This is
called universal newline mode and enabled by open(..., "U"). If your client
code insists that a line has to end with "\n" and there's no way to change
that you can wrap the file
>>> def ensure_newline(instream):
... prev = next(instream)
... for cur in instream:
... yield prev
... prev = cur
... if not prev.endswith("\n"):
... prev += "\n"
... yield prev
...
>>> for line in ensure_newline(open("tmp.txt", "U")):
... print repr(line)
...
'1\n'
'2\n'
'3\n'
'4\n'
'5\n'
But often the opposite direction, removing any newlines, works just as well
and is easier to achieve:
>>> for line in open("tmp.txt", "U"):
... print repr(line.strip("\n"))
...
'1'
'2'
'3'
'4'
'5'
Peter
--
http://mail.python.org/mailman/listinfo/python-list
Re: What is the best way to handle a missing newline in the following case
> The problem is when I get to the last line. When the program sees '\n' > after the 9, everything works fine. However, when there isn't a '\n', > the program doesn't process the last line. > > What would be the best approach to handle the case of the possible > missing '\n' at the end of the file? use readines to read all lines into a list and then iterate thru the list: f = open(r'c:\test.txt', 'rb') print f.readlines() >> ['1\r\n', '3\r\n', '5\r\n', '7\r\n', '3\r\n', '9'] -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the best way to handle a missing newline in the following case
"[email protected]" writes: >> The problem is when I get to the last line. When the program sees '\n' >> after the 9, everything works fine. However, when there isn't a '\n', >> the program doesn't process the last line. >> >> What would be the best approach to handle the case of the possible >> missing '\n' at the end of the file? > > use readines to read all lines into a list and then iterate thru the > list: > > f = open(r'c:\test.txt', 'rb') > print f.readlines() > >>> > ['1\r\n', '3\r\n', '5\r\n', '7\r\n', '3\r\n', '9'] There's no real point in contructing a list. Just do with open(r'c:\test.txt') as f: for l in f: print int(l) As long as you just have digits and whitespace then that's fine - int() will do as you want. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the best way to handle a missing newline in the following case
On 2010-11-05, Paul Rudin wrote: > "[email protected]" writes: >>> The problem is when I get to the last line. When the program >>> sees '\n' after the 9, everything works fine. However, when >>> there isn't a '\n', the program doesn't process the last >>> line. >>> >>> What would be the best approach to handle the case of the possible >>> missing '\n' at the end of the file? >> >> use readines to read all lines into a list and then iterate thru the >> list: >> >> f = open(r'c:\test.txt', 'rb') >> print f.readlines() >> >> ['1\r\n', '3\r\n', '5\r\n', '7\r\n', '3\r\n', '9'] > > There's no real point in contructing a list. Just do > > with open(r'c:\test.txt') as f: >for l in f: >print int(l) > > As long as you just have digits and whitespace then that's fine > - int() will do as you want. Keep in mind that a file that a text file that doesn't end with a newline isn't strictly legal. You can expect problems, or at least warnings, with other tools with such files. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: How convert list to nested dictionary?
Hi Folks
thanks a lot all. All solutions work fine.
while I am doing my home work.
Reading "Learning Python" and much more.
Let me ask again to close my doubts:
>>> l = ['k1', 'k2', 'k3', 'k4', 'k5']
>>> d = reduce(lambda x,y: {y:x}, reversed(l), {'/':[1,2,3]})
>>> d
{'k1': {'k2': {'k3': {'k4': {'k5': {'/': [1, 2, 3]}}
>>> d['k1']['k2']['k3']['k4']['k5']
{'/': [1, 2, 3]}
>>> d['k1']['k2']['k3']['k4']['k5']['/']
[1, 2, 3]
>>>
now I want generate the "index" to access the element.
==> d['k1']['k2']['k3']['k4']['k5']['/'] from l
So again I have only.
>>> l = ['k1', 'k2', 'k3', 'k4', 'k5']
z = ?magicCode?
z = d['k1']['k2']['k3']['k4']['k5']['/']
>>> z
[1, 2, 3]
>>>z.append('4')
>>>z
[1, 2, 3, 4]
Best Regards
macm
On 5 nov, 11:57, Peter Otten <[email protected]> wrote:
> Boris Borcic wrote:
> > Arnaud Delobelle wrote:
> >> macm writes:
>
> >>> Hi Folks
>
> >>> How convert list to nested dictionary?
>
> >> l
> >>> ['k1', 'k2', 'k3', 'k4', 'k5']
> >> result
> >>> {'k1': {'k2': {'k3': {'k4': {'k5': {}}
>
> >>> Regards
>
> >>> macm
>
> >> reduce(lambda x,y: {y:x}, reversed(l), {})
>
> > d={}
> > while L : d={L.pop():d}
>
> Iterating over the keys in normal order:
>
> >>> keys = "abcde"
> >>> d = outer = {}
> >>> for key in keys:
>
> ... outer[key] = inner = {}
> ... outer = inner
> ...>>> d
>
> {'a': {'b': {'c': {'d': {'e': {}}
>
> The "functional" variant:
>
> >>> d = {}
> >>> reduce(lambda outer, key: outer.setdefault(key, {}), "abcde", d)
> {}
> >>> d
>
> {'a': {'b': {'c': {'d': {'e': {}}
>
> In a single expression if you are willing to pay the price:
>
> >>> reduce(lambda (accu, outer), key: (accu, outer.setdefault(key, {})),
>
> "abcde", ({},)*2)[0]
> {'a': {'b': {'c': {'d': {'e': {}}
>
> Peter
--
http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
On Fri, 5 Nov 2010 10:12:05 -0400, Philip Semanchuk wrote: > > BTW the more common name for this character is caret (ka-RAY). Yes, it's caret, but no, it's KA-rit, almost the same as carrot. It's straight from Latin, with no detour through French. -- To email me, substitute nowhere->spamcop, invalid->net. -- http://mail.python.org/mailman/listinfo/python-list
How to get dynamically-created fxn's source?
For a project I'm working on I need a way to retrieve the source code of dynamically generated Python functions. (These functions are implemented dynamically in order to simulate "partial application" in Python.[1]) The ultimate goal is to preserve a textual record of transformations performed on data, along with all the data (both pre- and post- transformation) itself. These transformation functions could be dynamically generated as closures, but I suspect that this would make it more difficult to extract source code that could serve as a reasonably self-contained description of the transformation (because this source code would refer to variables defined outside of the function). An alternative would be to generate the *source code* for the functions dynamically, from a template having slots (within the function's definition) that gets filled in with actual parameter values, and pass this source code to exec. In any case, the problem remains of how to extract the dynamically-generated function's source code. One possibility would be to define a Transformation wrapper class whose __init__ takes the dynamically-generated source code (a string) as argument, keeps it around as an instance attribute for future reference, and exec's it to define its __call__ method. Is this overkill/reinventing the wheel? IOW, does Python already have a built-in way to achieve this same effect? (Also, the wrapper scheme above is somewhat loose: it's relatively easy for the source code instance attribute (as described) to fall out of sync with the function that actually executes when __call__ runs. Maybe a tighter connection between the obtained source code and the code that actually executes when __call__ runs is possible.) I'm aware of the inspect module, but from reading its source code I gather that it is designed for inspecting source code that is explicitly written in files, and would not be too good at inspecting functions that are generated dynamically (i.e. not from source code explicitly given in a source file--I hope that made sense). Your comments and suggestions would be much appreciated. Many thanks in advance! G [1] For example, given a base function spam that has the signature (typeT, typeT, typeT, int, int, int) and three specific integer values X, Y, and Z, dynamically generate a new function spamXYZ with signature (typeT, typeT, typeT) such that spamXYZ(A, B, C) is identical to spam(A, B, C, X, Y, Z), for all possible values of A, B, C. -- http://mail.python.org/mailman/listinfo/python-list
Exception handling with NameError
Hello, I want to append new input to list SESSION_U without erasing its content. I try this: ... try: SESSION_U.append(UNIQUES) except NameError: SESSION_U = [] SESSION_U.append(UNIQUES) ... I would think that at first try I would get the NameError and SESSION_U list would be created and appended; the second time try would work. But it does not. Do you know why? -- http://mail.python.org/mailman/listinfo/python-list
Re: Exception handling with NameError
Zeynel wrote: > I want to append new input to list SESSION_U without erasing its > content. I try this: > > ... > try: > SESSION_U.append(UNIQUES) > except NameError: > SESSION_U = [] > SESSION_U.append(UNIQUES) > ... > I would think that at first try I would get the NameError and > SESSION_U list would be created and appended; the second time try > would work. But it does not. Do you know why? If you want SESSION_U to be global you must say so. E. g.: def your_func(): global SESSION_U # ... > try: > SESSION_U.append(UNIQUES) > except NameError: > SESSION_U = [] > SESSION_U.append(UNIQUES) # ... Of course I'm only guessing because you don't provide enough context. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get dynamically-created fxn's source?
On 11/5/2010 9:55 AM gb345 said... In any case, the problem remains of how to extract the dynamically-generated function's source code. Are you looking for the source code of the dynamically created wrapper function (effectively the piece that calls the original function) or of the wrapped function? (the piece that ultimately gets called?) I'm pretty sure you can't get source from the executable function (python 2.x anyway), but with your naming scheme, it may be possible to trace into the wrapped function's source. Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get dynamically-created fxn's source?
gb345 wrote:
> For a project I'm working on I need a way to retrieve the source
> code of dynamically generated Python functions. (These functions
> are implemented dynamically in order to simulate "partial application"
> in Python.[1]) The ultimate goal is to preserve a textual record
> of transformations performed on data, along with all the data (both
> pre- and post- transformation) itself.
Are you aware of functools.partial?
>>> from functools import partial
>>> def f(a, b, c, x, y, z):
... return a*x + b*y*y + c*z*z*z
...
>>> fstar = partial(f, x=1, y=2, z=3)
>>> fstar(1, 0, 0)
1
>>> fstar(0, 1, 0)
4
>>> fstar(0, 0, 1)
27
>>> fstar.args, fstar.keywords
((), {'y': 2, 'x': 1, 'z': 3})
>>> fstar.func
--
http://mail.python.org/mailman/listinfo/python-list
Re: How convert list to nested dictionary?
macm wrote:
> thanks a lot all. All solutions work fine.
>
> while I am doing my home work.
> Reading "Learning Python" and much more.
>
> Let me ask again to close my doubts:
>
l = ['k1', 'k2', 'k3', 'k4', 'k5']
d = reduce(lambda x,y: {y:x}, reversed(l), {'/':[1,2,3]})
d
> {'k1': {'k2': {'k3': {'k4': {'k5': {'/': [1, 2, 3]}}
d['k1']['k2']['k3']['k4']['k5']
> {'/': [1, 2, 3]}
d['k1']['k2']['k3']['k4']['k5']['/']
> [1, 2, 3]
>
> now I want generate the "index" to access the element.
>
> ==> d['k1']['k2']['k3']['k4']['k5']['/'] from l
>
> So again I have only.
l = ['k1', 'k2', 'k3', 'k4', 'k5']
>
> z = ?magicCode?
>
> z = d['k1']['k2']['k3']['k4']['k5']['/']
You'll eventually have to start and write your first line of code. Why not
doing it right now? It is sure more rewarding than copying other people's
canned solutions and it can even be fun.
Peter
--
http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 2010-11-05, Steven D'Aprano wrote: > On Thu, 04 Nov 2010 21:47:59 +, Tim Harig wrote: > >> I have seen huge patches caused by nothing more then some edit that >> accidently added a trailing space to a large number of lines. White >> space mangling happens all the time without people even knowing about >> it. > > How does an edit accidentally add a trailing space to a large number of > lines? Putting it back in context, it doesn't matter. Seeb's point stands. diff -b was designed because there are so many tools and channels that mangle whitespace. Changes in something such as brace style would make non-whitespace changes that would not be eliminated by diff -b. Probably the biggest reason for -b is for handling the differences in line endings used on different platforms. > (1) The programmer shifted the cursor to the end of the line, pressed > space, moved down a line, shift to eol, press space, repeat a large > number of times. I don't call that an "accident". A search and replace operation could easily add extra whitespace and since whitespace is not normally visible, the changes most likely go unnoticed. The bottom line is that it happens and assigning blame really doesn't change that fact. > (2) Some programmer used a tool that thought it was okay to add > whitespace to the end of lines without being told to. I don't call that > an accident either, I call that using a broken tool. Yep, there are probably thousands of tools that mangle whitespace. In many cases, such as differences in line endings, what they are doing is not even wrong. You can blame the tools all you like; but, they are not going away. You keep trying to tell us that using whitespace is superior; but, other languages manage to work with these thousands of imperfect tools without issue. The use of whitespace was a stylistic change and stylistic holy wars exist because it is almost impossible to prove that any reasonable style has benefit over another. That whitespace causes issues is verifiable. I find it hard to concluded that that whitespace based syntax is superior when it tells us that we cannot use thousands of otherwise useful tools that other langauges manage to work with. I find it hard to select a matter of taste with no verifiable benefit over a verifiable disadvantage that happens to strike many people. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 2010-11-05, Tim Harig wrote: > On 2010-11-05, Steven D'Aprano wrote: >> On Thu, 04 Nov 2010 21:47:59 +, Tim Harig wrote: >> >>> I have seen huge patches caused by nothing more then some edit that >>> accidently added a trailing space to a large number of lines. White >>> space mangling happens all the time without people even knowing about >>> it. And how does that affect a Python program? The same as it does a C program. >> How does an edit accidentally add a trailing space to a large number of >> lines? > > Putting it back in context, it doesn't matter. Seeb's point stands. > diff -b was designed because there are so many tools and channels that > mangle whitespace. Changes in something such as brace style would make > non-whitespace changes that would not be eliminated by diff -b. > > Probably the biggest reason for -b is for handling the differences in line > endings used on different platforms. Different line-endings are tolerated by Python just as well as they are by C. -- Grant Edwards grant.b.edwardsYow! They collapsed at ... like nuns in the gmail.comstreet ... they had no teen appeal! -- http://mail.python.org/mailman/listinfo/python-list
Re: Exception handling with NameError
On Nov 5, 1:26 pm, Peter Otten <[email protected]> wrote: > Of course I'm only guessing because you don't provide enough context. > > Peter Thanks. This is the problem I am having, in general: K = [] # a container list K = ["A", "B"] ARCHIVE = [] # a list where items from K is archived ARCHIVE.append(K) # K is updated K = ["C", "D"] # append new K to ARCHIVE ARCHIVE.append(K) The problem I am having is this: If I do: K = [] ARCHIVE = [] ARCHIVE.append(K) any time K is updated (user submits new input) the content of ARCHIVE is erased: If I do this: K = [] ARCHIVE.append(K) I get NameError: "Name ARCHIVE not defined" What is the solution? -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 2010-11-04, D'Arcy J.M. Cain wrote: > On Thu, 4 Nov 2010 19:37:25 + (UTC) > Tim Harig wrote: >> On 2010-11-04, D'Arcy J.M. Cain wrote: >> You are the one who seems to be on a crusade against against braces. It > > You totally misunderstand me. I am not on a crusade of any sort. I am I appologize that I confused your name with Steven D'Aprano; but, your positions are pretty much the same. > care about. If no one was on a crusade to convince people that > indentation as syntax (can we call is IAS from now on?) was evil then I > wouldn't be posting anything at all on the subject. I am being totally > reactionary here. Neither of you are really adding anything to the conversation other then to assert that you like whitespace syntax and that the problems do not effect you. Good for you; but, that doesn't help the people who are finding that it presents problems. >> would seem to me, that if you want people to accept that white space >> formatting is superior, that you would be looking for a simple way to solve >> the white space mangling problem. > > I might if it was a problem for me. Good for you but telling us that doesn't really help those that do. Your stance is based an a stylistic preference. Holy wars around style continue to exist because, in most cases, it is almost impossible to prove the advantages of one reasonable style over another. It is, however, verifiable that white space syntax causes issues with a large number of common tools. I am a man of science. When choosing between the intangible and verifiable, I choose the verifable truth. >> The world is full of broken tools that many of us have to use; but, why >> should we accept that your choice is superior when other choices manage to >> work with these tools without issues. > > You don't have to accept anything. Choose your own tools. I happen to > choose Python and the tools that I choose to use work fine for me. It is simply hard for me to accept that your solution is better when it is telling us that we have to abandon thousands of tools that other solutions manage to work with without difficulty. -- http://mail.python.org/mailman/listinfo/python-list
decimal.py ver 2.6,2.7 not working with python 2.7
I have a 'Python 2.7' installed. It seems like the decimal.py module that comes with the Python2.7 package is not working. I hope I'm wrong, but here's why I think so: If I simply try to import the module, I get this error: >>> import decimal Traceback (most recent call last): File "", line 1, in File "/opt/ictools/python_2_7/lib/python2.7/decimal.py", line 3700, in _numbers.Number.register(Decimal) AttributeError: 'module' object has no attribute 'Number' >>> But, if I download, and import the 2.5 version of decimal.py, it imports with no complaint. In the 2.5 version of decimal.py, there is no reference to '_numbers' like there is in the 2.6 and 2.7 versions. Is this a bug, or is there something I can do to fix it (as a user, with limited permissions)? I don't feel good about continuing to run with the 2.5 decimal.py, since I'll be using alot of numpy and other modules that use decimal, and I don't know how they'll react. Thanks, Bob -- http://mail.python.org/mailman/listinfo/python-list
ANN: Leo 4.8 beta 1 released
Leo 4.8 beta 1 is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.8: -- - Leo now uses the simplest possible sentinel lines in external files. External files with sentinels now look like Emacs org-mode files. - Leo Qt gui now supports Drag and Drop. This was one of the most frequently requested features. - Improved abbreviation commands. You now define abbreviations in Leo settings nodes, not external files. - @url nodes may contain url's in body text. This allows headlines to contain summaries: very useful. - Leo now uses PyEnchant to check spelling. - Leo can now open multiple files from the command line. - Leo's ancient Tangle and Untangle commands are now deprecated. This will help newbies how to learn Leo. - Leo now shows "Resurrected" and "Recovered" nodes. These protect data and show how data have changed. These fix several long-standing data-related problems. - A new "screenshots" plugin for creating slide shows with Leo. I used this plugin to create Leo's introductory slide shows. - A better installer. - Many bug fixes. Links: -- Leo: http://webpages.charter.net/edreamleo/front.html Forum:http://groups.google.com/group/leo-editor Download: http://sourceforge.net/project/showfiles.php?group_id=3458 Bzr: http://code.launchpad.net/leo-editor/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 2010-11-05, Alain Ketterlin wrote: > Terry Reedy writes: > >> If you add the normally redundant information in the form of explicit >> dedents (anything starting with '#' and distinguishable from normal >> comments), then it is not too hard to re-indent even after all indents >> have been removed. > > I actually use such a trick in emacs, not with comments but with "pass" > (emacs' python mode knows that pass end return end the current block). > It's extrememly useful in heavily nested code, or if I need to paste > some piece of code from one level to another. This lets my editor's > auto-indenter do the right thing. And I see immediately if/when I did > the nesting wrong. Thank-you for your tip. It is nice to know that some people are thinking of ways to work around the trade-offs rather then just asserting that we shouldn't use tools that happen to collide with Python. -- http://mail.python.org/mailman/listinfo/python-list
Using %x to format number to hex and number of digits
I'm currently trying to convert a digit from decimal to hex, however I need the full 4 digit hex form. Python appears to be shortening the form. Example: num = 10 num = "%x"%(num) print(num) >a num = 10 num = "%#x"%(num) print(num) >0xa I need it to output as 0x0a, and the exercise is requiring me to use %x to format the string. Any help would be appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 2010-11-05, Grant Edwards wrote: > On 2010-11-05, Tim Harig wrote: >> On 2010-11-05, Steven D'Aprano wrote: >>> On Thu, 04 Nov 2010 21:47:59 +, Tim Harig wrote: >>> I have seen huge patches caused by nothing more then some edit that accidently added a trailing space to a large number of lines. White space mangling happens all the time without people even knowing about it. > > And how does that affect a Python program? The same as it does a C > program. I wasn't making any statement of C versus Python in this thread. Those have been covered elsewhere. I was responding to your assertion: It exists because so many people change whitespace intentionally in C source code because no two C programmers seem able to agree on how to format code. Diff -b allows you to attempt to ignore semantically null stylistic changes made by programmers. That is clearly wrong. If a C programmer changes the format of the code, it is almost universally true that they will make changes that affect more then just the whitespace on a single line. Diff will register these changes even with the -b option. I provided a couple of common scenerios that are more likely to have justified the -b option. -- http://mail.python.org/mailman/listinfo/python-list
Re: decimal.py ver 2.6,2.7 not working with python 2.7
On Fri, Nov 5, 2010 at 10:50 AM, robert roze wrote: > I have a 'Python 2.7' installed. > > It seems like the decimal.py module that comes with the Python2.7 package is > not working. I hope I'm wrong, but here's why I think so: > > If I simply try to import the module, I get this error: > import decimal > Traceback (most recent call last): > File "", line 1, in > File "/opt/ictools/python_2_7/lib/python2.7/decimal.py", line 3700, in > > _numbers.Number.register(Decimal) > AttributeError: 'module' object has no attribute 'Number' What does the following output for you?: import numbers print(numbers.__file__) print(dir(numbers)) Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 11/5/2010 11:13 AM Tim Harig said... It is simply hard for me to accept that your solution is better when it is telling us that we have to abandon thousands of tools that other solutions manage to work with without difficulty. I only work with a few tools none of which alter or strip leading whitespace, and I don't try to transport python code in ways that allow harmful transformations to take place, eg, reinterpreted by html or email rendering engines, which aren't effective programming tools anyway. So, which of your tools are you married to that are causing your issues? If-you-got-a-bigger-hammer-you-could-drive-that-phillips-screw-into-anything-ly y'rs, Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 11/5/2010 3:41 AM, Steven D'Aprano wrote: On Thu, 04 Nov 2010 20:17:35 +, Seebs wrote: * I /do/ have a significant problem with cutting and pasting code in Python. In most languages, I can haul a chunk of code about, hit C-M-q, and Emacs magically indents the result properly. This is, unfortunately, impossible with Python. It has caused me real bugs, and I have to be extra careful to fix the indentation up. That was the thing which bit me the worst. I had a fairly large block of code in a first-pass ugly program. I wanted to start refactoring it, so I moved a big hunk of code into a method (with plans to further refactor). It took about fifteen minutes to redo the logic. Well there's your problem -- you are relying on tools that operate by magic. Not magic, just code understanding. INTERLISP's editor allowed the user to select a block of LISP code and make it into a function. The selected block would be analyzed to determine which local variables it referenced, and a new function would be created with those parameters. The block of code at the original point would then be replaced by a call to the function. Today's editors are too dumb to do that right. They're text editors with the illusion of knowing something about the language, not language editors which also format text. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 2010-11-05, Steven D'Aprano wrote: > How does an edit accidentally add a trailing space to a large number of > lines? I would love to know the answer to this question. However, empirically, it happens. My guess would be cutting and pasting in some way. > So we keep coming back to work-arounds for tools that mangle your data > for no good reason... To some extent, this is true. How about this. How about we make the Python TCP Stack. The Python TCP Stack works on the same principles that you advocate for the Python language. For instance, if any packet it receives is malformed or contrary to the applicable specs, it has a 95% chance of dropping the packet, and a 5% chance of interpreting the packet as being of a different type entirely. This will NEVER be a problem, and is a good design, because handling packets which contain any kind of spec violation is just work-arounds for broken tools, right? And the first thing we should do is *always* to ensure that, if anything anywhere does not live up to our proposed specification, it causes us to fail in spectacular ways. Of course, to fully capture the feel of Python's choice here, we have to include some common packet variant, which violates no RFCs, as one of the "broken" ones on the grounds that it doesn't make sense to us and isn't easy for a newcomer to read. -s -- Copyright 2010, all wrongs reversed. Peter Seebach / [email protected] http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated! I am not speaking for my employer, although they do rent some of my opinions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 2010-11-05, Steven D'Aprano wrote: > On Thu, 04 Nov 2010 20:17:35 +, Seebs wrote: >> That was the thing which bit me the worst. I had a fairly large block >> of code in a first-pass ugly program. I wanted to start refactoring it, >> so I moved a big hunk of code into a method (with plans to further >> refactor). It took about fifteen minutes to redo the logic. > Well there's your problem -- you are relying on tools that operate by > magic. Wrong. > Rather than re-create the logic, why not just hit Undo and then re-paste > the code *without* the magic auto-reformat? Half a second, to undo and re- > paste, followed by 10 or 20 seconds to select the appropriate lines and > *explicitly* re-indent the lines to the correct level. There was no magic auto-reformat. Where did you invent that from? Why are you making stuff up which I never said or referred to? > For somebody who keeps tossing around the mantra that "explicit is better > than implicit", you're amazingly reliant on a tool that performs massive, > apparently irreversible formatting operations implicitly. No, I am not. No such tool was involved. I never mentioned one, referred to one, or hinted at one -- and have never used one, because I hate them. In fact, it is ludicrous to imagine that I was using one, given that I've stated in this very thread that so far as I know such a tool cannot be created for Python. Your decision to invent something I never referred to is not a problem with my approach to the language. -s -- Copyright 2010, all wrongs reversed. Peter Seebach / [email protected] http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated! I am not speaking for my employer, although they do rent some of my opinions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
On Nov 5, 2010, at 12:43 PM, Peter Pearson wrote: > On Fri, 5 Nov 2010 10:12:05 -0400, Philip Semanchuk wrote: >> >> BTW the more common name for this character is caret (ka-RAY). > > Yes, it's caret, but no, it's KA-rit, almost the same as > carrot. It's straight from Latin, with no detour through > French. This I did not know (obviously). Thanks. I knew all those years of studying French would ruin me somehow. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 2010-11-05, Emile van Sebille wrote: > So, which of your tools are you married to that are causing your issues? Python. -s -- Copyright 2010, all wrongs reversed. Peter Seebach / [email protected] http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated! I am not speaking for my employer, although they do rent some of my opinions. -- http://mail.python.org/mailman/listinfo/python-list
Re: How convert list to nested dictionary?
Hi Peter Thanks a lot for your tips and codes, Cake Recipes are good to learn! So I post just basic issues. Hopping a good soul like you can help me! But I am still learning... : ) Best Regards macm On 5 nov, 15:40, Peter Otten <[email protected]> wrote: > macm wrote: > > thanks a lot all. All solutions work fine. > > > while I am doing my home work. > > Reading "Learning Python" and much more. > > > Let me ask again to close my doubts: > > l = ['k1', 'k2', 'k3', 'k4', 'k5'] > d = reduce(lambda x,y: {y:x}, reversed(l), {'/':[1,2,3]}) > d > > {'k1': {'k2': {'k3': {'k4': {'k5': {'/': [1, 2, 3]}} > d['k1']['k2']['k3']['k4']['k5'] > > {'/': [1, 2, 3]} > d['k1']['k2']['k3']['k4']['k5']['/'] > > [1, 2, 3] > > > now I want generate the "index" to access the element. > > > ==> d['k1']['k2']['k3']['k4']['k5']['/'] from l > > > So again I have only. > l = ['k1', 'k2', 'k3', 'k4', 'k5'] > > > z = ?magicCode? > > > z = d['k1']['k2']['k3']['k4']['k5']['/'] > > You'll eventually have to start and write your first line of code. Why not > doing it right now? It is sure more rewarding than copying other people's > canned solutions and it can even be fun. > > Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Using %x to format number to hex and number of digits
On Fri, Nov 5, 2010 at 11:23 AM, Matty Sarro wrote: > I'm currently trying to convert a digit from decimal to hex, however I need > the full 4 digit hex form. Python appears to be shortening the form. > Example: > > num = 10 > num = "%x"%(num) > print(num) > >>a > > num = 10 > num = "%#x"%(num) > print(num) > >>0xa > > I need it to output as 0x0a, and the exercise is requiring me to use %x to > format the string. Any help would be appreciated. Use str.zfill() and add the 0x manually: num = 10 hexdig = "%x" % num padded = hexdig.zfill(2) # pad with 0 if necessary oxd = "0x" + padded print(oxd) Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 2010-11-05, Seebs wrote: > On 2010-11-05, Emile van Sebille wrote: >> So, which of your tools are you married to that are causing your issues? > > Python. I think you should quit using Python and choose a language that works with whatever tools are causing all your white-space corruption problems. -- Grant Edwards grant.b.edwardsYow! My pants just went to at high school in the Carlsbad gmail.comCaverns!!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Using %x to format number to hex and number of digits
On Fri, Nov 5, 2010 at 11:23 AM, Matty Sarro wrote: > I'm currently trying to convert a digit from decimal to hex, however I need > the full 4 digit hex form. Python appears to be shortening the form. > Example: > > num = 10 > num = "%x"%(num) > print(num) > >>a > > num = 10 > num = "%#x"%(num) > print(num) > >>0xa > > I need it to output as 0x0a, and the exercise is requiring me to use %x to > format the string. Any help would be appreciated. http://docs.python.org/release/2.5.2/lib/typesseq-strings.html What you're asking for is called "zero padding", so if I were you, I'd search the above page for the phrase "zero pad". -- Grant Edwards grant.b.edwardsYow! BARBARA STANWYCK makes at me nervous!! gmail.com -- http://mail.python.org/mailman/listinfo/python-list
RE: decimal.py ver 2.6,2.7 not working with python 2.7
Hi Chris, Aha! yes, you figured it out. My PYTHONPATH env variable had an old experiment in it, which happened to be called numbers.py. Take it out, and decimal.py works fine. Thank you, Bob >What does the following output for you?: > >import numbers >print(numbers.__file__) >print(dir(numbers)) > >Cheers, >Chris >-- >http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Using %x to format number to hex and number of digits
I actually was able to get it working a few minutes after posting the question. My apologies for not posting a followup :) I ended up using the following format: num = 10 num = "%#0.2x"%(num) print(num) It works, however I'm not sure if it'd be considered very "pythonic" or not. Thanks for your thoughts! On Fri, Nov 5, 2010 at 2:57 PM, Chris Rebert wrote: > On Fri, Nov 5, 2010 at 11:23 AM, Matty Sarro wrote: > > I'm currently trying to convert a digit from decimal to hex, however I > need > > the full 4 digit hex form. Python appears to be shortening the form. > > Example: > > > > num = 10 > > num = "%x"%(num) > > print(num) > > > >>a > > > > num = 10 > > num = "%#x"%(num) > > print(num) > > > >>0xa > > > > I need it to output as 0x0a, and the exercise is requiring me to use %x > to > > format the string. Any help would be appreciated. > > Use str.zfill() and add the 0x manually: > > num = 10 > hexdig = "%x" % num > padded = hexdig.zfill(2) # pad with 0 if necessary > oxd = "0x" + padded > print(oxd) > > Cheers, > Chris > -- > http://blog.rebertia.com > -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
Tim Harig wrote: The use of whitespace was a stylistic change and stylistic holy wars exist because it is almost impossible to prove that any reasonable style has benefit over another. That whitespace causes issues is verifiable. I find it hard to concluded that that whitespace based syntax is superior when it tells us that we cannot use thousands of otherwise useful tools that other langauges manage to work with. I find it hard to select a matter of taste with no verifiable benefit over a verifiable disadvantage that happens to strike many people. The verifiable benefit for me is ease of use, ease of thought, ease of typing... I realize these are not benefits for everyone, but they are for some -- and I would venture a guess that the ease of thought benefit is one of the primary reasons Python is popular. I am definitely one of those that think indentation based structure is one of Python's best features. I do acknowledge that if you don't think that way, it can be major hassle, and I sympathize. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On Fri, 5 Nov 2010 18:13:44 + (UTC) Tim Harig wrote: > > care about. If no one was on a crusade to convince people that > > indentation as syntax (can we call is IAS from now on?) was evil then I > > wouldn't be posting anything at all on the subject. I am being totally > > reactionary here. > > Neither of you are really adding anything to the conversation other then to Well, whether I am adding anything is a judgement call. That I don't accept your premise doesn't mean that my postings are content free. > It is, however, verifiable that white space syntax causes issues with a > large number of common tools. I am a man of science. When choosing The simple fact is that the combination of your tools and Python is broken. The combination of my tools and Python is not. That's lucky for me since I really, really like IAS. That's unlucky for people who have to work with tools that mangle code. But don't crusade to change my language. Use Perl or C or even pybraces. > It is simply hard for me to accept that your solution is better when > it is telling us that we have to abandon thousands of tools that other > solutions manage to work with without difficulty. I am offering no solutions. Why would I since I don't see a problem? -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
*** glibc detected *** gdb: malloc(): smallbin double linked list
Hi, I've compiled Python 2.7 (r27:82500, Nov 2 2010, 09:00:37) [GCC 4.4.3] on linux2 with the following configure options ./configure --prefix=/home/john/local/python-dbg --with-pydebug I've installed numpy and some other packages but when I try to run my extension code under gdb I get the errors below. Does anyone have any ideas of how to track down what's happening here? I imagine I've misconfigured something somewhere. Is valgrind the answer? Thanks, John. *** glibc detected *** gdb: malloc(): smallbin double linked list corrupted: 0x04de7ad0 *** === Backtrace: = /lib/libc.so.6(+0x775b6)[0x7f0a252215b6] /lib/libc.so.6(+0x7b8e9)[0x7f0a252258e9] /lib/libc.so.6(__libc_malloc+0x6e)[0x7f0a2522658e] gdb(xmalloc+0x18)[0x45bc38] gdb[0x476df1] gdb[0x474c9b] gdb[0x474ee8] gdb(execute_command+0x2dd)[0x458d1d] gdb(catch_exception+0x50)[0x535510] gdb[0x4b5191] gdb(interp_exec+0x17)[0x535637] gdb(mi_cmd_interpreter_exec+0x6c)[0x4b9adc] gdb[0x4ba71a] gdb(catch_exception+0x50)[0x535510] gdb(mi_execute_command+0x97)[0x4ba137] gdb[0x53a0f8] gdb(gdb_do_one_event+0x29a)[0x53b38a] gdb(catch_errors+0x5b)[0x53531b] gdb(start_event_loop+0x1e)[0x53a90e] gdb[0x44f619] gdb(catch_errors+0x5b)[0x53531b] gdb[0x450166] gdb(catch_errors+0x5b)[0x53531b] gdb(gdb_main+0x24)[0x44f554] gdb(main+0x2e)[0x44f51e] /lib/libc.so.6(__libc_start_main+0xfd)[0x7f0a251c8c4d] gdb[0x44f429] === Memory map: 0040-00818000 r-xp 08:05 4832730 /usr/bin/gdb 00a17000-00a18000 r--p 00417000 08:05 4832730 /usr/bin/gdb 00a18000-00a25000 rw-p 00418000 08:05 4832730 /usr/bin/gdb 00a25000-00a43000 rw-p 00:00 0 0287f000-0b92 rw-p 00:00 0 [heap] 7f0a1c00-7f0a1c021000 rw-p 00:00 0 7f0a1c021000-7f0a2000 ---p 00:00 0 7f0a20fc-7f0a20fd6000 r-xp 08:05 3498245 /lib/libgcc_s.so.1 7f0a20fd6000-7f0a211d5000 ---p 00016000 08:05 3498245 /lib/libgcc_s.so.1 7f0a211d5000-7f0a211d6000 r--p 00015000 08:05 3498245 /lib/libgcc_s.so.1 7f0a211d6000-7f0a211d7000 rw-p 00016000 08:05 3498245 /lib/libgcc_s.so.1 7f0a211fd000-7f0a21211000 r--p 000dc000 08:05 4825848 /usr/lib/libstdc++.so.6.0.13 7f0a21211000-7f0a21218000 r--p 00018000 08:05 4841756 /usr/lib/debug/lib/librt-2.11.1.so 7f0a21218000-7f0a21226000 r--p 1000 08:05 4841756 /usr/lib/debug/lib/librt-2.11.1.so 7f0a21226000-7f0a2123e000 r--p 000bc000 08:05 4653290 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0 7f0a2123e000-7f0a21287000 r--p 003dd000 08:05 4653290 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0 7f0a21287000-7f0a21299000 r--p 00425000 08:05 4653290 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0 7f0a21299000-7f0a213e7000 r--p 0018c000 08:05 4653290 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0 7f0a213e7000-7f0a2152f000 r--p 0207c000 08:05 4653324 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/_stempy.so 7f0a2152f000-7f0a22027000 r--p 01585000 08:05 4653324 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/_stempy.so 7f0a22027000-7f0a2240 rw-p 00:00 0 7f0a22408000-7f0a224d1000 r--p 00315000 08:05 4653290 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0 7f0a224d1000-7f0a224ff000 r--p 002e8000 08:05 4653290 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0 7f0a224ff000-7f0a22526000 r--p 00038000 08:05 4653310 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/myrrh_pylib-d 7f0a22526000-7f0a2259c000 r--p 0151 08:05 4653324 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/_stempy.so 7f0a2259c000-7f0a2280c000 r--p 012a 08:05 4653324 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/_stempy.so 7f0a2280c000-7f0a2343f000 rw-p 00:00 0 7f0a23443000-7f0a2344c000 r--p 0001a000 08:05 6169643 /home/john/local/python-dbg/lib/python2.7/lib-dynload/datetime.so 7f0a2344c000-7f0a2345c000 r--p 002d9000 08:05 4653290 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0 7f0a2345c000-7f0a23461000 r--p 0005e000 08:05 4653310 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/myrrh_pylib-d 7f0a23461000-7f0a23477000 r--p 0001f000 08:05 4653310 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/myrrh_pylib-d 7f0a23477000-7f0a2347d000 r--p 4000 08:05 4653095 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_system.so.1.44.0 7f0a2347d000-7f0a2350c000 r--p 00757000 08:05 4653324 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/_stempy.so 7f0a2350c000-7f0a23555000 r--p 021c3000 08:05 4653324 /home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/_stempy.so 7f0a23555000-7f0a2355b000 r--p 00048000 08:05 6169627 /home/john/local/python-dbg/lib/python2.7/lib-dynload/_ct
Re: Silly newbie question - Carrot character (^)
It's ok, people who refer to a labret piercing as a "la-BRAY" piercing are also incorrect. It's pronounced lab-RET, as its base word is the latin "labretta." French as a language shall doom us all :) On Fri, Nov 5, 2010 at 2:54 PM, Philip Semanchuk wrote: > > On Nov 5, 2010, at 12:43 PM, Peter Pearson wrote: > > > On Fri, 5 Nov 2010 10:12:05 -0400, Philip Semanchuk wrote: > >> > >> BTW the more common name for this character is caret (ka-RAY). > > > > Yes, it's caret, but no, it's KA-rit, almost the same as > > carrot. It's straight from Latin, with no detour through > > French. > > This I did not know (obviously). Thanks. I knew all those years of studying > French would ruin me somehow. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: How convert list to nested dictionary?
Ok. Done
>>> def appendNested(nest, path, val):
... nest2 = nest
... for key in path[:-1]:
... nest2 = nest2[key]
... nest2[path[-1]].append(val)
... return nest
...
>>>
>>> l = ['k1','k2','k3','k4','k5']
>>> ndict = reduce(lambda x,y: {y:x}, reversed(l), {'/':[1,2,3]})
>>> x = l + list('/')
>>> print appendNested(ndict, x, 5)
{'k1': {'k2': {'k3': {'k4': {'k5': {'/': [1, 2, 3, 5]}}
>>>
I need make lambda but now is friday night here and I guess I will go
drink a beer or three!
Cheers!
macm
On 5 nov, 16:51, macm wrote:
> Hi Peter
>
> Thanks a lot for your tips and codes,
>
> Cake Recipes are good to learn! So I post just basic issues.
>
> Hopping a good soul like you can help me!
>
> But I am still learning... : )
>
> Best Regards
>
> macm
>
> On 5 nov, 15:40, Peter Otten <[email protected]> wrote:
>
> > macm wrote:
> > > thanks a lot all. All solutions work fine.
>
> > > while I am doing my home work.
> > > Reading "Learning Python" and much more.
>
> > > Let me ask again to close my doubts:
>
> > l = ['k1', 'k2', 'k3', 'k4', 'k5']
> > d = reduce(lambda x,y: {y:x}, reversed(l), {'/':[1,2,3]})
> > d
> > > {'k1': {'k2': {'k3': {'k4': {'k5': {'/': [1, 2, 3]}}
> > d['k1']['k2']['k3']['k4']['k5']
> > > {'/': [1, 2, 3]}
> > d['k1']['k2']['k3']['k4']['k5']['/']
> > > [1, 2, 3]
>
> > > now I want generate the "index" to access the element.
>
> > > ==> d['k1']['k2']['k3']['k4']['k5']['/'] from l
>
> > > So again I have only.
> > l = ['k1', 'k2', 'k3', 'k4', 'k5']
>
> > > z = ?magicCode?
>
> > > z = d['k1']['k2']['k3']['k4']['k5']['/']
>
> > You'll eventually have to start and write your first line of code. Why not
> > doing it right now? It is sure more rewarding than copying other people's
> > canned solutions and it can even be fun.
>
> > Peter
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Using %x to format number to hex and number of digits
On 11/05/10 13:23, Matty Sarro wrote: I'm currently trying to convert a digit from decimal to hex, however I need the full 4 digit hex form. Python appears to be shortening the form. Example: num = 10 num = "%x"%(num) print(num) a num = 10 num = "%#x"%(num) print(num) 0xa I need it to output as 0x0a, and the exercise is requiring me to use %x to format the string. Any help would be appreciated. Though it feels hokey to me, using "%#04x" % 10 works for me. The "#" adds the "0x" prefix (the "alternate form"), the "0" pads with zeros, and the "4" is really "2 places + 2 characters for the prefix". So if you want 4 hex characters + the 2 prefix characters, you'd use "%#06x". IMHO, this would make more sense if it didn't take the 2-character prefix into consideration (being written as "%#02x" for a byte or "%#04x" for a short), but it's not really a burr in my saddle. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On Nov 5, 12:35 pm, John Nagle wrote: > INTERLISP's editor allowed the user to select a block of > LISP code and make it into a function. The selected block > would be analyzed to determine which local variables it referenced, > and a new function would be created with those parameters. The > block of code at the original point would then be replaced by > a call to the function. > > Today's editors are too dumb to do that right. They're text > editors with the illusion of knowing something about the language, > not language editors which also format text. Eclipse does that. Visual Studio does that. As for Python, I hear that Eric IDE has a plugin to do that, although I haven't tested it myself. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: How convert list to nested dictionary?
Peter Otten <[email protected]> writes: > Boris Borcic wrote: > >> Arnaud Delobelle wrote: >>> macm writes: >>> Hi Folks How convert list to nested dictionary? >>> l ['k1', 'k2', 'k3', 'k4', 'k5'] >>> result {'k1': {'k2': {'k3': {'k4': {'k5': {}} Regards macm >>> >>> reduce(lambda x,y: {y:x}, reversed(l), {}) >>> >> >> d={} >> while L : d={L.pop():d} > > Iterating over the keys in normal order: > keys = "abcde" d = outer = {} for key in keys: > ... outer[key] = inner = {} > ... outer = inner > ... d > {'a': {'b': {'c': {'d': {'e': {}} > > The "functional" variant: > d = {} reduce(lambda outer, key: outer.setdefault(key, {}), "abcde", d) > {} d > {'a': {'b': {'c': {'d': {'e': {}} > > In a single expression if you are willing to pay the price: > reduce(lambda (accu, outer), key: (accu, outer.setdefault(key, {})), > "abcde", ({},)*2)[0] > {'a': {'b': {'c': {'d': {'e': {}} > > Peter The most basic functional version: >>> f = lambda l: {l[0]: f(l[1:])} if l else {} >>> f('abcde') {'a': {'b': {'c': {'d': {'e': {}} -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Final state of underlying sequence in islice
On 11/5/2010 4:58 AM, Raymond Hettinger wrote: Shashank Singh wrote: Are there any promises made with regard to final state of the underlying sequence that islice slices? Currently, there are no promises or guarantees about the final state of the iterator. I interpret the current doc statement as a promise that becomes ambiguous when step > 1. To the extent the pure Python version in the docs differs from the CPython implementation in this regard, it is an accidental implementation detail. That being said, we could introduce some guarantees (earliest possible stop point, latest possible stop point, or decide to leave it undefined). In between earliest and latest, depending on the stop value, is another possibility. If it is relatively easy to patch the C version to match the Python version (earliest stop point) I would go for that. It is easy to skip over and ignore more items, impossible to go back. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Using %x to format number to hex and number of digits
On 2010-11-05, Tim Chase wrote: > On 11/05/10 13:23, Matty Sarro wrote: >>> I'm currently trying to convert a digit from decimal to hex, >>> however I need the full 4 digit hex form. Python appears to >>> be shortening the form. >>> Example: >>> >>> num = 10 >>> num = "%x"%(num) >>> print(num) >>> > a >>> >>> num = 10 >>> num = "%#x"%(num) >>> print(num) >>> > 0xa >>> >>> I need it to output as 0x0a, and the exercise is requiring >>> me to use %x to format the string. Any help would be >>> appreciated. > > Though it feels hokey to me, using > >"%#04x" % 10 > > works for me. I think "0x%02x" % 10 is a bit more readable, but it accomplishes the same thing -- you just don't have to do the mental math to add the prefix width to the number of desired hex digits in the output. -- Grant Edwards grant.b.edwardsYow! Quick, sing me the at BUDAPEST NATIONAL ANTHEM!! gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 2010-11-05, Ethan Furman wrote: > The verifiable benefit for me is ease of use, ease of thought, ease of > typing... I realize these are not benefits for everyone, but they are > for some -- and I would venture a guess that the ease of thought benefit > is one of the primary reasons Python is popular. I am definitely one of > those that think indentation based structure is one of Python's best > features. Could you explain more the "ease of thought" thing? I haven't yet noticed it, but it might be something to look out for as I get more experienced. It certainly sounds like something that would be a benefit. -s -- Copyright 2010, all wrongs reversed. Peter Seebach / [email protected] http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated! I am not speaking for my employer, although they do rent some of my opinions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
On 11/5/2010 9:43 AM, Matty Sarro wrote: Hey Everyone, Just curious - I'm working on a program which includes a calculation of a circle, and I found myself trying to use pi*radius^2, and getting errors that data types float and int are unsupported for "^". Now, I realized I was making the mistake of using '^' instead of "**". I've corrected this and its now working. However, what exactly does ^ do? I know its used in regular expressions but I can't seem to find anything about using it as an operator. Sadly my google foo is failing since the character gets filtered out. All such symbol questions are aswered (or should be) in PySymbols.html: https://code.google.com/p/xploro/downloads/detail?name=PySymbols.html -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 2010-11-05, D'Arcy J.M. Cain wrote: > The simple fact is that the combination of your tools and Python is > broken. The combination of my tools and Python is not. That's lucky > for me since I really, really like IAS. That's unlucky for people who > have to work with tools that mangle code. But don't crusade to change > my language. Use Perl or C or even pybraces. No one is crusading to change Python, or even suggesting that it should be changed. > I am offering no solutions. Why would I since I don't see a problem? One of the things many people try to do is develop the ability to "see" problems that affect other people but possibly not themselves. This allows people to offer solutions to those problems, which is often viewed as a kind of contribution to a community. Certainly, it's more useful than posting nothing more than "that's not a problem for me." I can just see how well this attitude must work in other circumstances: Some Guy: Oh, *...@#. I think I just sprained my ankle. Darcy: I didn't. Some Guy: I don't think I can walk up these stairs. Darcy: I don't have a problem with stairs. Stop trying to change this path. It works fine. -s -- Copyright 2010, all wrongs reversed. Peter Seebach / [email protected] http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated! I am not speaking for my employer, although they do rent some of my opinions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 2010-11-05, Grant Edwards wrote: > On 2010-11-05, Seebs wrote: >> On 2010-11-05, Emile van Sebille wrote: >>> So, which of your tools are you married to that are causing your issues? >> Python. > I think you should quit using Python and choose a language that works > with whatever tools are causing all your white-space corruption > problems. Ahh, but that's the thing. I'm married to it -- there's existing projects I want to work on which are in Python. Anyway, it was a sort of frivolous answer, but it's ha-ha-only-serious; after all, there were no serious issues with any of these tools before. There's a saying a friend of mine has; "a lack of communication is never exclusively one party's fault." This applies, in many cases, to things like "issues" that occur when two programs clash in some aspect of their designs. In some cases, there might be a real and unambiguous standard to be violated. In others, though, you can have a problem which arises from a clash in expectations between two programs, either of which is fine on its own. There is a clash between Python and the whole category of things which sometimes lose whitespace. Because that category is reasonably large, and known to be large, and unlikely to vanish, many language designers choose to build their languages to be robust in the face of minor changes in whitespace. Python chose not to, and that is a source of conflicts. Were someone to invent a *new* text editor, which mangled whitespace, I would accuse it of being gratuitously incompatible with Python; I tend to regard compatibility, once you get past the standards, as a matter of temporal precedence. -s -- Copyright 2010, all wrongs reversed. Peter Seebach / [email protected] http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated! I am not speaking for my employer, although they do rent some of my opinions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 11/5/2010 3:33 PM, D'Arcy J.M. Cain wrote: my language. Use Perl or C or even pybraces. http://timhatch.com/projects/pybraces/ "I work with a guy who hates Python's significant whitespace and wishes that he could just use curly braces." I am offering no solutions. Except you just did ;-). And using a braces encoding makes it looks easier than I expected. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Final state of underlying sequence in islice
On Nov 5, 1:05 pm, Terry Reedy wrote: > > Currently, there are no promises or guarantees about the final state > > of the iterator. > > I interpret the current doc statement as a promise that becomes > ambiguous when step > 1. You may have missed my point. I wrote the tools, the docs, and the tests. If you interpret a "promise" in text, I can assure you it was not intended. The behavior *is* undefined because I never defined it. I'm happy to clarify the docs to make that explicit. Or I can alter the implementation a bit to make a guarantee if it looks like there is a good reason to do so. The OP doesn't have any use cases to light the way and I don't yet see any useful invariants that would arise out of either definition. And since the ambiguity only shows-up in a somewhat rare case, I'm inclined to just mark it as undefined. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: decimal.py ver 2.6,2.7 not working with python 2.7
On 11/5/2010 3:14 PM, robert roze wrote: Aha! yes, you figured it out. My PYTHONPATH env variable had an old experiment in it, which happened to be called numbers.py. Take it out, and decimal.py works fine. Python has a large test suite in Lib/test, which includes test_decimal.py. It is run daily on several machines, and must pass before any release. So a gross failure like an import failure is very likely due to a local cause. What does the following output for you?: import numbers print(numbers.__file__) print(dir(numbers)) These are good test steps for any gross module failure. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
On Fri, 05 Nov 2010 10:12:05 -0400, Philip Semanchuk wrote: > As others have said, ^ is for XOR. That's buried here in the > documentation: > http://docs.python.org/release/2.7/reference/... > > Not that I would have expected you to find it there since that's pretty > dense. In fact, older versions of the Python doc used to describe this > section as "for language lawyers" but I see they've changed that now. However, it's still written for language lawyers. IMHO, the lack of a reference manual for the language itself is a major hole in Python's documentation. -- http://mail.python.org/mailman/listinfo/python-list
Re: *** glibc detected *** gdb: malloc(): smallbin double linked list
On Fri, 05 Nov 2010 19:39:12 +, John Reid wrote: > I've compiled > Python 2.7 (r27:82500, Nov 2 2010, 09:00:37) [GCC 4.4.3] on linux2 > > with the following configure options > ./configure --prefix=/home/john/local/python-dbg --with-pydebug > > I've installed numpy and some other packages but when I try to run my > extension code under gdb I get the errors below. Does anyone have any > ideas of how to track down what's happening here? I imagine I've > misconfigured something somewhere. Is valgrind the answer? I imagine that your extension code is trashing the heap, in which case, valgrind is probably the answer. My first guess would be that something is writing to a heap block after it has been deallocated (possibly due to omitting a Py_INCREF). Of course, other causes are possible, but writing to deallocated memory is a common problem when writing extensions for languages with garbage collection. -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
On Nov 5, 2010, at 5:21 PM, Nobody wrote: > On Fri, 05 Nov 2010 10:12:05 -0400, Philip Semanchuk wrote: > >> As others have said, ^ is for XOR. That's buried here in the >> documentation: >> http://docs.python.org/release/2.7/reference/... >> >> Not that I would have expected you to find it there since that's pretty >> dense. In fact, older versions of the Python doc used to describe this >> section as "for language lawyers" but I see they've changed that now. > > However, it's still written for language lawyers. > > IMHO, the lack of a reference manual for the language itself is a major > hole in Python's documentation. I agree. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PyQt v4.8.1 Released
In message , Дамјан Георгиевски wrote: >>> PyQt is available under the GPL and a commercial license. >> >> Surely you mean “proprietary” rather than “commercial”. There is >> nothing about the GPL that prevents “commercial” use. > > I think he means a license that *he* sells comercially :) Presumably that’s a proprietary licence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Final state of underlying sequence in islice
On Nov 5, 2:51 pm, Raymond Hettinger wrote: > You may have missed my point. I wrote the tools, the docs, and the > tests. > If you interpret a "promise" in text, I can assure you it was not > intended. The behavior *is* undefined because I never defined it. > I'm happy to clarify the docs to make that explicit. Does the existence of a test case imply a guarantee? # Test number of items consumed SF #1171417 it = iter(range(10)) self.assertEqual(list(islice(it, 3)), range(3)) self.assertEqual(list(it), range(3, 10)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
On 2010-11-05, Nobody wrote: > However, it's still written for language lawyers. > IMHO, the lack of a reference manual for the language itself is a major > hole in Python's documentation. I'm a bit lost here. Could you highlight some of the differences between "a reference manual for the language itself" and "something written for language lawyers"? -s -- Copyright 2010, all wrongs reversed. Peter Seebach / [email protected] http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated! I am not speaking for my employer, although they do rent some of my opinions. -- http://mail.python.org/mailman/listinfo/python-list
[ANN] Lupa 0.17 released - Lua in Python
Hi all,
I am happy to announce the release of Lupa 0.17, Lua in Python.
http://pypi.python.org/pypi/lupa/0.17
Have fun,
Stefan
What is Lupa?
--
Lupa integrates the LuaJIT2 runtime [1] into CPython. It is a rewrite of
LunaticPython in Cython with several advanced features.
This release features iteration support for Python objects in Lua.
Changes in this release:
0.17 (2010-11-05)
* new helper function "python.enumerate()" in Lua that returns a Lua
iterator for a Python object and adds the 0-based index to each item.
* new helper function "python.iterex()" in Lua that returns a Lua
iterator for a Python object and unpacks any tuples that the
iterator yields into separate Lua arguments.
* new helper function "python.iter()" in Lua that returns a Lua
iterator for a Python object.
* resurrected the "python.as_function()" helper function for Lua code
as it can be needed in cases where Lua cannot determine how to run a
Python function.
[1] LuaJIT2: http://luajit.org/
Features
-
* separate Lua runtime states through a LuaRuntime class
* frees the GIL and supports threading in separate runtimes when
calling into Lua
* Python compatible coroutine wrapper for Lua coroutines
* iteration support for Python objects in Lua and Lua objects in Python
* proper encoding and decoding of strings (configurable per runtime,
UTF-8 by default)
* supports Python 2.x and 3.x, potentially starting with Python 2.3
(currently untested)
* written for LuaJIT2, as opposed to the Lua interpreter (tested with
LuaJIT 2.0.0-beta5)
* easy to hack on and extend as it is written in Cython, not C
Why use it?
It complements Python very well. Lua is a language as dynamic as Python,
but LuaJIT compiles it to very fast machine code, sometimes faster than
many other compiled languages for computational code. The language runtime
is extremely small and carefully designed for embedding. The complete
binary module of Lupa, including a statically linked LuaJIT2 runtime, is
only some 500KB on a 64 bit machine.
However, the Lua ecosystem lacks many of the batteries that Python readily
includes, either directly in its standard library or as third party
packages. This makes real-world Lua applications harder to write than
equivalent Python applications. Lua is therefore not commonly used as
primary language for large applications, but it makes for a fast,
high-level and resource-friendly backup language inside of Python when raw
speed is required and the edit-compile-run cycle of binary extension
modules is too heavy and too static for agile development or hot-deployment.
Lupa is a very fast and thin wrapper around LuaJIT. It makes it easy to
write dynamic Lua code that accompanies dynamic Python code by switching
between the two languages at runtime, based on the tradeoff between
simplicity and speed.
Examples
-
from lupa import LuaRuntime
lua = LuaRuntime()
lua.eval('1+1')
2
lua_func = lua.eval('function(f, n) return f(n) end')
def py_add1(n): return n+1
lua_func(py_add1, 2)
3
lua_code = '''\
... function(N)
... for i=0,N do
... coroutine.yield( i%2 )
... end
... end
... '''
f = lua.eval(lua_code)
gen = f.coroutine(4)
list(enumerate(gen))
[(0, 0), (1, 1), (2, 0), (3, 1), (4, 0)]
lua_code = '''\
... function(L)
... for item in python.iter(L) do
... if item == 3 then return 1 end
... end
... return 0
... end
... '''
f = lua.eval(lua_code)
f([1,2,3])
1
f([1,2])
0
--
http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 05 Nov 2010 20:14:47 GMT Seebs wrote: > I can just see how well this attitude must work in other circumstances: I guess this message ends the topic for me. Bye. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Final state of underlying sequence in islice
On Nov 5, 3:52 pm, Ian wrote: > On Nov 5, 2:51 pm, Raymond Hettinger wrote: > > > You may have missed my point. I wrote the tools, the docs, and the > > tests. > > If you interpret a "promise" in text, I can assure you it was not > > intended. The behavior *is* undefined because I never defined it. > > I'm happy to clarify the docs to make that explicit. > > Does the existence of a test case imply a guarantee? > > # Test number of items consumed SF #1171417 > it = iter(range(10)) > self.assertEqual(list(islice(it, 3)), range(3)) > self.assertEqual(list(it), range(3, 10)) That tests a "natural boundary". In contrast, the OP's issue concerns an odd case where step > 1 and stop != start + n * step and len(list(it)) > start + n * step There's no test for that case and it is not clear what the desired behavior should be. And AFAICT there are no use cases or meaningful invariants to guide the way, so I'm reluctant to lock-in the choice (much like Tim and Guido waited a long time before they guaranteed the stability of list.sort()). If the RightAnswer(tm) is obvious to you, I would like to hear it. If I had to make a choice right now, I would choose stopping at the earlier possible point rather than scanning to the next natural boundary. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: Using %x to format number to hex and number of digits
On 11/05/10 15:10, Grant Edwards wrote: On 2010-11-05, Tim Chase wrote: On 11/05/10 13:23, Matty Sarro wrote: I need it to output as 0x0a, and the exercise is requiring me to use %x to format the string. Any help would be appreciated. Though it feels hokey to me, using "%#04x" % 10 works for me. I think "0x%02x" % 10 is a bit more readable, but it accomplishes the same thing -- you just don't have to do the mental math to add the prefix width to the number of desired hex digits in the output. Which, I confess, is what I usually use because I didn't know about the "#" until this thread, and just made the assumption that one can get the zero-padding along with the "alternate form" in my experimentation this afternoon. So while it _can_ be done with just variants of the "%x" place-holder (as suggested by the OP's exercise), at least two of us on the list prefer to explicitly add the "0x" to the beginning. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Regular expression
I need to extract the quoted text from :
_("get this")
The following works:
re.compile( "_\(['\"]([^'\"]+)['\"]\)" )
However, I don't want to match if there is A-Z or a-z or 0-9 or _
immediately preceding the "_" so I have tried:
"[^0-9a-zA-Z]*_\(['\"]([^'\"]+)['\"]\)"
"[^\w]{0,1}_\(['\"]([^'\"]+)['\"]\)"
"\W*_\(['\"]([^'\"]+)['\"]\)"
to match against:
skip this text _("get this")
Thanks
--
http://mail.python.org/mailman/listinfo/python-list
Re: Why "flat is better than nested"?
On Fri, 05 Nov 2010 14:19:47 +0100, J. Gerlach wrote: > Am 28.10.2010 03:40, schrieb Steven D'Aprano: >> [ snip a lot of wise words ] > > Can I put this (translated) in the german python wiki? I guess it might > help more people to understand some decisions taken during python's > development - and I'm to lazy to do something similar myself ;) Sure, go ahead. I would appreciate a link back to my post, and/or credit, but that's not essential. (I understand it's a wiki and there's no guarantee that the link will remain there forever.) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Lupa 0.17 released - Lua in Python
On Nov 5, 4:21 pm, Stefan Behnel wrote: > Hi all, > > I am happy to announce the release of Lupa 0.17, Lua in Python. > > http://pypi.python.org/pypi/lupa/0.17 > > Have fun, > > Stefan Thanks, interesting projection. Good idea. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On Thu, 04 Nov 2010 19:37:25 +, Tim Harig wrote: > Examples of communication channels that mangle white space abound. Yes. So what? If your communication channel mangles your data, change your communication channel, don't expect users of clean communication channels to hand-enter error-correcting codes (braces) into the data. > I > don't know of any that mangle either braces or pascal style start/end > blocks. > > You are the one who seems to be on a crusade against against braces. It > would seem to me, that if you want people to accept that white space > formatting is superior, that you would be looking for a simple way to > solve the white space mangling problem. Why is it the responsibility of the programming language syntax to correct the problem with Seebs' faulty mail server? I've experienced the spilled-coke-on-the-keyboard problem more often than mangled whitespace, but you don't see me arguing that what every language needs is error-correcting codes that let me work with keyboards that have had Coke spilled on them. [...] > Transfering binary programs has always been an issue and using text > based communications (preferably human readable) has always been > considered a good design decision. I put up with Python's white space > idiosyncrasies; I wouldn't even bother looking at a language that > requires me to enter the source in binary. I also consider the move > toward XML based document formats a move in the right direction. Okay, now you have zero credibility. XML is not a data format for human use, it is for use by machines. It is slow, inefficient, and uneditable by humans except for the most trivial cases. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On Thu, 04 Nov 2010 17:45:58 +, Tim Harig wrote: >>> Python is the only language that I know that *needs* to specify tabs >>> versus spaces since it is the only language I know of which uses >>> whitespace formating as part of its syntax and structure. [...] > I am also aware of other langauges such as Boo; but, I don't really > consider them individually relevant to the conversation as they are > explicitly using a Python based syntax. For this discussion I merely > group them with Python. You might as well say that C is the only language that uses tags around blocks, since for this discussion "I merely group" Pascal, Algol, Java, etc with C. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On Fri, 05 Nov 2010 18:45:39 +, Seebs wrote: > On 2010-11-05, Steven D'Aprano > wrote: >> On Thu, 04 Nov 2010 20:17:35 +, Seebs wrote: >>> That was the thing which bit me the worst. I had a fairly large block >>> of code in a first-pass ugly program. I wanted to start refactoring >>> it, so I moved a big hunk of code into a method (with plans to further >>> refactor). It took about fifteen minutes to redo the logic. > >> Well there's your problem -- you are relying on tools that operate by >> magic. > > Wrong. Really? Then how did the logic get screwed up from a mere copy-and-paste operation? In context (which you deleted), you were agreeing with Mark Wooding who wrote: "I /do/ have a significant problem with cutting and pasting code in Python. In most languages, I can haul a chunk of code about, hit C-M-q, and Emacs magically indents the result properly. This is, unfortunately, impossible with Python. It has caused me real bugs, and I have to be extra careful to fix the indentation up." [Aside: he isn't having problems with cutting and pasting code in Python, but in Emacs.] You *agreed with him*, and related your story. In context, I think it was perfectly reasonable to conclude that you too used C-M-q in Emacs, which then "magically indents the result". Mark's words, not mine. But perhaps you were using Notepad, and you just hit Ctrl-V, and something else mangled the code so badly you needed to spend 15 minutes re-creating the program logic. I am open to correction either way. >> Rather than re-create the logic, why not just hit Undo and then >> re-paste the code *without* the magic auto-reformat? Half a second, to >> undo and re- paste, followed by 10 or 20 seconds to select the >> appropriate lines and *explicitly* re-indent the lines to the correct >> level. > > There was no magic auto-reformat. Where did you invent that from? Why > are you making stuff up which I never said or referred to? Then how did the logic get mangled from a simple copy and paste operation? What god-awful editor are you using that can't copy and paste text without mangling it? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression
On 06/11/2010 01:25, Paul Hemans wrote:
I need to extract the quoted text from :
_("get this")
The following works:
re.compile( "_\(['\"]([^'\"]+)['\"]\)" )
However, I don't want to match if there is A-Z or a-z or 0-9 or _
immediately preceding the "_" so I have tried:
"[^0-9a-zA-Z]*_\(['\"]([^'\"]+)['\"]\)"
"[^\w]{0,1}_\(['\"]([^'\"]+)['\"]\)"
"\W*_\(['\"]([^'\"]+)['\"]\)"
to match against:
skip this text _("get this")
Use a negative lookbehind:
re.compile(r'''(?http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
On Fri, 05 Nov 2010 22:51:10 +, Seebs wrote: > On 2010-11-05, Nobody wrote: >> However, it's still written for language lawyers. > >> IMHO, the lack of a reference manual for the language itself is a major >> hole in Python's documentation. > > I'm a bit lost here. Could you highlight some of the differences > between "a reference manual for the language itself" and "something > written for language lawyers"? +1 QOTW -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Using Python for a demonstration in historical linguistics
Hello, In the framework of a project on evolutionary linguistics I wish to have a program to process words and simulate the effect of sound shift, for instance following the Rask's-Grimm's rule. I look to have python take a dictionary file or a string input and replace the consonants in it with the Grimm rule equivalent. For example: bʰ → b → p → f dʰ → d → t → θ gʰ → g → k → x gʷʰ → gʷ → kʷ → xʷ If the dictionary file has the word "Abe" I want the program to replace the letter b with f forming the word "Afe" and write the result in a tabular file. How easy is it to find the python functions to do that? Best regards, Dax Bloom -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for a demonstration in historical linguistics
On Fri, Nov 5, 2010 at 7:17 PM, Dax Bloom wrote: > Hello, > > In the framework of a project on evolutionary linguistics I wish to > have a program to process words and simulate the effect of sound > shift, for instance following the Rask's-Grimm's rule. I look to have > python take a dictionary file or a string input and replace the > consonants in it with the Grimm rule equivalent. For example: > bʰ → b → p → f > dʰ → d → t → θ > gʰ → g → k → x > gʷʰ → gʷ → kʷ → xʷ > If the dictionary file has the word "Abe" I want the program to > replace the letter b with f forming the word "Afe" and write the > result in a tabular file. How easy is it to find the python functions > to do that? Tabular files: http://docs.python.org/library/csv.html Character substitution: (a) http://docs.python.org/library/string.html#string.maketrans and http://docs.python.org/library/stdtypes.html#str.translate (b) http://docs.python.org/library/stdtypes.html#str.replace In either case, learn about dicts: http://docs.python.org/library/stdtypes.html#dict Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for a demonstration in historical linguistics
On 06/11/2010 02:17, Dax Bloom wrote: Hello, In the framework of a project on evolutionary linguistics I wish to have a program to process words and simulate the effect of sound shift, for instance following the Rask's-Grimm's rule. I look to have python take a dictionary file or a string input and replace the consonants in it with the Grimm rule equivalent. For example: bʰ → b → p → f dʰ → d → t → θ gʰ → g → k → x gʷʰ → gʷ → kʷ → xʷ If the dictionary file has the word "Abe" I want the program to replace the letter b with f forming the word "Afe" and write the result in a tabular file. How easy is it to find the python functions to do that? Very. :-) I'd build a dict of each rule: bʰ → b b → p etc, and then use the re module to perform the replacements in one pass, looking up the new sound for each match. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On Fri, 05 Nov 2010 08:17:02 +0530, Rustom Mody wrote:
> However the original question -- mixing tabs and spaces is bad -- has
> got lost in the flames. Do the most die-hard python fanboys deny this?
> And if not is it asking too much (say in python3) that mixing tabs and
> spaces be flagged as an error or at least warning?
Mixing spaces and tabs for indentation can be ambiguous. Python 2.x will
attempt to ignore the ambiguity, and therefore run the code if it can,
but Python 3.x treats mixed indentation in a single block as an error.
[st...@sylar ~]$ cat ambiguous.py
def f():
print("indented with 8 spaces")
print("indented with tab")
f()
[st...@sylar ~]$ cat unambiguous.py
def f():
print("indented with 8 spaces")
def g():
print("indented with tab")
f()
g()
Python 2.x will execute both files. Python 3.x will happily execute
unambiguous.py, but raises an error on the other:
[st...@sylar ~]$ python3 ambiguous.py
File "ambiguous.py", line 3
print("indented with tab")
^
TabError: inconsistent use of tabs and spaces in indentation
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: Silly newbie question - Carrot character (^)
On Nov 5, 2010, at 6:51 PM, Seebs wrote: > On 2010-11-05, Nobody wrote: >> However, it's still written for language lawyers. > >> IMHO, the lack of a reference manual for the language itself is a major >> hole in Python's documentation. > > I'm a bit lost here. Could you highlight some of the differences > between "a reference manual for the language itself" and "something > written for language lawyers"? The former refers to something that programmers would use to learn the language once they've gone through the tutorial a few times. The latter is great for writing a Python parser but isn't the friendliest guide to language constructs. Take the OP's question. How is one supposed to find out about bitwise operators in Python? AFAICT they're not mentioned in the tutorial, and neither are decorators, assert(), global, exec, the ternary if statement, etc. It seems that plowing through a document written for language lawyers is the only formal way to learn about those language features, and that could be improved upon IMO. Cheers Philip -- http://mail.python.org/mailman/listinfo/python-list
Re: Compare source code
On 2010-11-06, Steven D'Aprano wrote: > On Fri, 05 Nov 2010 18:45:39 +, Seebs wrote: >> On 2010-11-05, Steven D'Aprano >> wrote: >>> Well there's your problem -- you are relying on tools that operate by >>> magic. >> Wrong. > Really? Then how did the logic get screwed up from a mere copy-and-paste > operation? I inserted four spaces in front of a bunch of lines. :) > [Aside: he isn't having problems with cutting and pasting code in Python, > but in Emacs.] True. > You *agreed with him*, and related your story. In context, I think it was > perfectly reasonable to conclude that you too used C-M-q in Emacs, which > then "magically indents the result". Mark's words, not mine. Ahh, okay. I can see how you would have inferred that, but no, that's not what I did. > What god-awful editor are you using that can't copy and paste text > without mangling it? It's a side-effect of vi being, by default, configured to prefer to convert things to tabs. The particular vi I'm using doesn't, so far as I know "recognize" file formats, and that default behavior is not merely tolerable but *preferable* for all of the dozens of other kinds of files I edit. I've since learned to work around it, but the fact remains that, given a fairly common behavior, which is *preferable* for every other context, I ended up with a file where an operation which would have worked for re-indenting any other language I use didn't for re-indenting Python. I've long since figured out ways to prevent that, but that wasn't the point; the point was how much harder it was to fix indentation once it had gotten mangled than it would be in, oh, any other programming language or file format I've used. (Even Makefiles are easier to fix, if only because they're so much simpler.) -s -- Copyright 2010, all wrongs reversed. Peter Seebach / [email protected] http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated! I am not speaking for my employer, although they do rent some of my opinions. -- http://mail.python.org/mailman/listinfo/python-list
