Re: string formatting

2011-05-07 Thread Terry Reedy

On 5/6/2011 8:09 PM, Chris Angelico wrote:

On Sat, May 7, 2011 at 6:54 AM, Terry Reedy  wrote:

def emsg(x):
  if isinstance(x,tuple):
x = (x,)
  print(The following object caused a proplem: %s" % x)



Couldn't you just do that unconditionally?
print(The following object caused a proplem: %s" % (x,))


I guess so, as long as one remembers the ','. That does not obviate the 
fact that % x is an attractive nuisance which works until it does not.


--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: PyGTK, Glade/libglade. What am I doing wrong?

2011-05-07 Thread Alister Ware
On Sat, 07 May 2011 15:14:07 +1100, Даниил Рыжков wrote:

> Thanks, Cristian! It works.
>> List of Pygtk: http://www.daa.com.au/mailman/listinfo/pygtk
> Thanks again. Subscribed :)
> 2011/5/7 craf :
>> Hi.
>>
>> Try this:
>>
>> #!/usr/bin/env python
>>
>> import gtk.glade
>>
>> class TestPyGtk:
>>    """This is an Hello World GTK application"""
>>
>>    def __init__(self):
>>
>>        #Set the Glade file
>>        self.gladefile = "test.glade"
>>        self.glade = gtk.glade.XML(self.gladefile)
>>
>>        self.MainWindow = self.glade.get_widget('MainWindow')
>>        self.MainWindow.show()
>>        self.MainWindow.connect('destroy', lambda e:gtk.main_quit())
>>
>>
>>
>> TestPyGtk()
>> gtk.main()
>>
>> Regards.
>>
>> Cristian.
>>
>> List of Pygtk: http://www.daa.com.au/mailman/listinfo/pygtk
you may also want to look at using gtk.builder instread as it is now the 
prefered option.




-- 
The human mind ordinarily operates at only ten percent of its capacity
-- the rest is overhead for the operating system.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-07 Thread Steven D'Aprano
On Fri, 06 May 2011 14:49:24 -0500, harrismh777 wrote:

> Terry Reedy wrote:
 (2) if not li:
>>>
>>> This is fine.
>>
>> This is the intended way. Anything in addition is extra noise and
>> wasted calculation. In other words, let Python do the boilerplate work
>> for you.
> 
> I agree, but I don't like it.
> 
> ... if not li  says nothing about what li is supposed to 'be' 

Yes, and? Neither does:

isempty(li)  # li could be anything that polymorphic isempty can deal with
li.isempty()  # li could be anything with a "isempty" method
len(li) == 0  # li could be anything with a length (list, dict, set, ...)


That's duck-typing for you, and it is generally a strength rather than a 
weakness. For those times when it is a weakness, that's where we have 
naming conventions, type-testing, and (in some languages) static types.


> and implies in any case that li does not exist

It does nothing of the sort. If li doesn't exist, you get a NameError.


> or worse is some kind of boolean.

Only if you're still thinking in some language that isn't Python.

Boolean tests in Python are polymorphic. bool() exists mainly to provide 
a canonical representation of true and false values, not because you are 
limited to using booleans in truth-testing. Far from it: it is often very 
useful to do something like this:

settings = local_settings or global_settings or builtin_settings

where the first non-empty *_settings wins.


> li is in fact an empty list [] and will identify as such, and of
> course (as a list object) has all of the attributes and methods of a
> list...
> 
> Why not have a list method that makes this more explicit:

For the same reason that we don't have an int method that makes zero 
testing more explicit:

n = 0
n.iszero()  # returns True


Because sometimes you can have too much explicitness.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coolest Python recipe of all time

2011-05-07 Thread Steven D'Aprano
On Fri, 06 May 2011 12:36:09 -0600, Ian Kelly wrote:

> On Fri, May 6, 2011 at 10:59 AM, Steven D'Aprano
>  wrote:
>> As written, amb is just a brute-force solver using more magic than is
>> good for any code, but it's fun to play with.
> 
> This isn't really amb; as you said it's just a brute-force solver with
> some weird syntax.  The whole point of amb is to enable
> non-deterministic programming, such as this:
[...]
> The amb engine would conceptually execute this function for every
> possible combination of a, b, and c, 

Which pretty much is the definition of "brute-force solver", no?



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: seems like a bug in isinstance()

2011-05-07 Thread Gregory Ewing

Chris Rebert wrote:

This is because you did `from Point import
...` in file2.py, whereas in file1.py you did `from
openopt.kernel.Point import ...`. These 2 different ways of referring
to the same module are sufficient to "trick"/"outsmart" (C)Python and
cause it to import the same module twice


That can't be the whole story, because those two ways of
referring to the module *should* have returned the same
module object, even though one is absolute and the other
relative.

I suspect what's happened is that somehow sys.path contains
both the directory containing .../openopt *and* the directory
.../openopt/kernel, and the second import is picking up
Point.py a second time as though it were a top-level module.

This could have happened by starting an interactive session
while cd'ed to .../openopt/kernel, or by launching a .py
file from there as a main script.

The solution is to make sure that sys.path only contains the
top level directories of the package hierarchy, and doesn't
also contain any of their subdirectories.

Always using absolute imports may be a good idea stylistically,
but in this case it will only mask the symptoms of whatever
is really wrong, and further problems could result from the
same cause.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary Views -- good examples? [was Re: Python 3 dict question]

2011-05-07 Thread Gregory Ewing

Ethan Furman wrote:

Ian Kelly wrote:


next(iter(myDict.items()))


Which is becoming less elegant.


If you're doing this sort of thing a lot you can make
a little helper function:

  def first(x):
return next(iter(x))

then you get to say

  first(myDict.items())

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Gregory Ewing

Hans Georg Schaathun wrote:

You cannot reference nor manipulate a 
reference in python, and that IMHO makes them more abstract.


You can manipulate them just fine by moving them
from one place to another:

   a = b

You can use them to get at stuff they refer to:

   a = b.c
   a[:] = b[:]

You can compare them:

   if a is b:
  ...

That's about all you can do with pointers in Pascal,
and I've never heard anyone argue that Pascal pointers
are any more or less abstract than any other piece of
data in that language.

As for "referencing" a reference, you can't really do
that in Pascal either, at least not the way you can
in C, because (plain) Pascal doesn't have an address-of
operator. The only way to get a pointer to a pointer
in Pascal is to heap-allocate a single pointer, which
isn't normally a very useful thing to do.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Chris Angelico
On Sat, May 7, 2011 at 7:21 PM, Gregory Ewing
 wrote:
> Hans Georg Schaathun wrote:
>
>> You cannot reference nor manipulate a reference in python, and that IMHO
>> makes them more abstract.
>
> You can manipulate them just fine by moving them
> from one place to another:

I think "manipulate" here means things like pointer arithmetic, which
are perfectly normal and common in C and assembly, but not in
languages where they're references.

Chris Angelico
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Gregory Ewing

John Nagle wrote:


Such tuples are still identical, even if they
contain identical references to immutable objects.


The point is you'd have to do the comparison only one
level deep, so it wouldn't be exactly the same as ==
on tuples.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Python3: imports don't see files from same directory?

2011-05-07 Thread dmitrey
hi all,
I try to port my code to Python 3 and somehow files don't see files
from same directory, so I have to add those directories explicitly,
e.g.
import sys
sys.path += [...]

Also, it leads to bugs like this one:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/961a90219a61e19d#

any ideas what's the reason and how to fix it?
I have tried to search google but got nothing yet.

Thank you in advance, D.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: seems like a bug in isinstance()

2011-05-07 Thread dmitrey
On May 7, 11:53 am, Gregory Ewing  wrote:
> Chris Rebert wrote:
> > This is because you did `from Point import
> > ...` in file2.py, whereas in file1.py you did `from
> > openopt.kernel.Point import ...`. These 2 different ways of referring
> > to the same module are sufficient to "trick"/"outsmart" (C)Python and
> > cause it to import the same module twice
>
> That can't be the whole story, because those two ways of
> referring to the module *should* have returned the same
> module object, even though one is absolute and the other
> relative.
>
> I suspect what's happened is that somehow sys.path contains
> both the directory containing .../openopt *and* the directory
> .../openopt/kernel, and the second import is picking up
> Point.py a second time as though it were a top-level module.
>
> This could have happened by starting an interactive session
> while cd'ed to .../openopt/kernel, or by launching a .py
> file from there as a main script.
>
> The solution is to make sure that sys.path only contains the
> top level directories of the package hierarchy, and doesn't
> also contain any of their subdirectories.
>
> Always using absolute imports may be a good idea stylistically,
> but in this case it will only mask the symptoms of whatever
> is really wrong, and further problems could result from the
> same cause.
>
> --
> Greg

> I suspect what's happened is that somehow sys.path contains
both the directory containing .../openopt *and* the directory
.../openopt/kernel
Yes, you are right. But I have to do it due to another issue I haven't
solved yet: Python3 imports don't see files from same directory
http://groups.google.com/group/comp.lang.python/browse_thread/thread/9470dbdacc138709#

Regards, D.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Gregory Ewing

On Thu, 05 May 2011 07:43:59 +1000, Ben Finney wrote:


‘x’ is a name. Names are bound to values. Talk of “variable” only
confuses the issue because of the baggage carried with that term.


But to use 'name' as a complete replacement for 'variable',
you have to stretch it to include things like a[i], b.c,
e.f(x).g[i:j].k, etc. which goes rather a long way beyond
the everyday meaning of the word.

In Python I use 'variable' to mean more or less 'something
that can be assigned to', which accords with the way it's
used in relation to many other languages, and doesn't
suggest any restriction to things named by a single
identifier.


But the data model of Python doesn't fit well with the ideas that the
term “variable” connotes for most programmers:


Seems to me that anyone taking that connotation from it
has not yet been sufficiently educated about the Python
data model itself. Part of explaining that data model
consists of instilling the very idea that the things in
Python that are analogous to variables in other languages
only refer to data rather than containing the actual data.


Saying “variable” and “has the value”


But I don't say "has a value", I say "refers to".

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Gregory Ewing

Andreas Tawn wrote:


If True and False:
waveFunction.collapse(cat)


Call-by-entanglement would be interesting. Anything that the
callee does to the parameter would affect the caller, but
you would only be able to tell by examining a trace of the
output afterwards.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Gregory Ewing

Grant Edwards wrote:

if you feel it just right and you have just the

right synchro-mesh setup, you can slide from 3rd into 4th without
every touching the clutch peddle...



and if that isn't automatic, I don't know what is


No, that's _not_ automatic if you have to do it yourself.  It's
automatic when it happens without user-intervention.


Does it count if the transmission is activated
by saying "Home, Jeeves"?

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


A suggestion for an easy logger

2011-05-07 Thread TheSaint
Hello,
I've resumed my hold project and I like to convert it for py3k2.
My knowledge has stagnated at version 2.4, then I found some improvements, 
but it will take me some time before I get used to.

I was using this logger >>
=
class log:
   """ It outputs lists and strings on file or any possible device that
   allows write mode. Options are: output file writing mode and special end
   of line (EOL)"""

   def __init__(self, output= None, mode= 'w', lsp= EOL):
   """ Can instantiate even no output is given. Choose to build an open file
   object to append to, or new and give a different line separator"""

  self.lsp = lsp
  self.output= output
  self.mode= mode
  try:  self.output= open(output, self.mode)
  except (IOError, TypeError): self.output = None

   def logger(self, strng, allowed=None):
  # without any output will simply send log to nowhere :-)
  if not allowed and not self.output: return
  # no allowed to write the output
  # keep silent even temporary skip writing
  # if allowed, it will go to stderr
  if isinstance(strng,list):
 a= EOL.join(strng)+ EOL
 strng = a
  strng= strng.replace(EOL,self.lsp)
  # when not allowed just return
  if allowed is None:   return
  if strng == '?close?':
 try: # try to close the file
self.output.close()
return
 except IOError: return # silently ignore the failure
  if self.output and Exists(self.output):
 self.output.write(strng)
  else:
 sys.stderr.write(strng)
 sys.stderr.flush()
  return

=

It is somehow convulitive, isn't it?
I do believe the builtin *print* would do more better than my logger.
Basically I would like a class which shoudl do:
1) print to stdout either with or without carriage return 
2) writing to a file
3) Skip some output

Everything should do according to the caller.
I didn't picked up the logging module, a way of confusion on my point of 
view. Some small example might easy my aberration :P

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Grant Edwards
On 2011-05-07, Gregory Ewing  wrote:
> Grant Edwards wrote:
>> if you feel it just right and you have just the
>>>right synchro-mesh setup, you can slide from 3rd into 4th without
>>>every touching the clutch peddle...
>> 
>>>and if that isn't automatic, I don't know what is
>> 
>> No, that's _not_ automatic if you have to do it yourself.  It's
>> automatic when it happens without user-intervention.
>
> Does it count if the transmission is activated
> by saying "Home, Jeeves"?

Only if your name is Bertie Wooster.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread TheSaint
Gregory Ewing wrote:

>  because modern architectures are so freaking complicated
> that it takes a computer to figure out the best instruction
> sequence

certainly is, I would not imagine one who writes on scraps of paper
:D :D :D

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Stuck with urllib.quote and Unicode/UTF-8

2011-05-07 Thread Marian Steinbach
Hi!

I am stuck with calling URLs with parameters containing non-ASCII
characters. I'm creating a url like this.

  url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' +
urllib.quote(address) + '&sensor=false&language=DE'

address can be a string like u"Köln, Nordrhein-Westfalen". This results in

  
http://maps.googleapis.com/maps/api/geocode/json?address=K%F6ln%2C%20Nordrhein-Westfalen&sensor=false&language=DE

and this doesn't seem to meet Google's Encoding expectations. I get an
"INVALID REQUEST" response. (The same things works if there are only
ASCII characters in the address.)

When I manually enter the "Köln"... string in the Firefox address bar,
Firefox makes the URL

  
http://maps.googleapis.com/maps/api/geocode/xml?address=K%C3%B6ln,%20Nordrhein-Westfalen&sensor=false&language=DE

out of this and it works fine. %C3%B6 seems to be the url-encoded
representation of an UTF-8 representation of a "ö" character.


So the next thing I tried is to get address utf-8-encoded, like this:

  url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' +
urllib.quote(address.encode('utf-8')) + '&sensor=false&language=DE'

This gives me an error like

  UnicodeDecodeError: 'ascii' codec can't decode byte 0xf6 in position
1: ordinal not in range(128)

Again, the input string for address is u"Köln, Nordrhein-Westfalen".


Can you see what I'm doing wrong or what I would have to to to get
from u"ö" to "%C3%B6"?


Thanks!

Marian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stuck with urllib.quote and Unicode/UTF-8

2011-05-07 Thread Marian Steinbach
An addition/correction:

It seems as if my input variable address is not Unicode. This is what
I get for print [address]:

['K\xf6ln, Nordrhein-Westfalen']

Isn't this utf-8 encoding?

And I'm using Python 2.5.2.
-- 
http://mail.python.org/mailman/listinfo/python-list


Custom string joining

2011-05-07 Thread Claudiu Popa
Hello Python-list,

I  have  an object which defines some methods. I want to join a list or
an iterable of those objects like this:

new_string = "|".join(iterable_of_custom_objects)

What   is   the   __magic__  function that needs to be implemented for
this case to work?  I  though  that  __str__  is sufficient but it doesn't 
seems to
work. Thanks in advance.

PC

  



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stuck with urllib.quote and Unicode/UTF-8

2011-05-07 Thread Chris Rebert
On Sat, May 7, 2011 at 5:35 AM, Marian Steinbach  wrote:
> An addition/correction:
>
> It seems as if my input variable address is not Unicode. This is what
> I get for print [address]:
>
> ['K\xf6ln, Nordrhein-Westfalen']
>
> Isn't this utf-8 encoding?

Nope, it's Latin-1 (or similar, e.g. Windows-1252):
Python 2.7.1 (r271:86832, Dec  5 2010, 00:12:20)
>>> x = u"Köln"
>>> x.encode('utf_8')
'K\xc3\xb6ln'
>>> x.encode('latin_1')
'K\xf6ln'
>>>

Cheers,
Chris
--
http://rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Custom string joining

2011-05-07 Thread Chris Rebert
On Sat, May 7, 2011 at 5:31 AM, Claudiu Popa  wrote:
> Hello Python-list,
>
> I  have  an object which defines some methods. I want to join a list or
> an iterable of those objects like this:
>
> new_string = "|".join(iterable_of_custom_objects)
>
> What   is   the   __magic__  function that needs to be implemented for
> this case to work?  I  though  that  __str__  is sufficient but it doesn't 
> seems to
> work. Thanks in advance.

You need to do the string conversion yourself; .join() doesn't do it
for you, due to strong typing. It only accepts iterables of strings:
new_string = "|".join(str(x) for x in iterable_of_custom_objects)

Cheers,
Chris
--
http://rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coolest Python recipe of all time

2011-05-07 Thread Ian Kelly
On Sat, May 7, 2011 at 2:29 AM, Steven D'Aprano
 wrote:
>> This isn't really amb; as you said it's just a brute-force solver with
>> some weird syntax.  The whole point of amb is to enable
>> non-deterministic programming, such as this:
> [...]
>> The amb engine would conceptually execute this function for every
>> possible combination of a, b, and c,
>
> Which pretty much is the definition of "brute-force solver", no?

The "execute the function for every possible combination" part, yes.
The "non-deterministic programming" part, no.
-- 
http://mail.python.org/mailman/listinfo/python-list


PyGTK notebook: get current page

2011-05-07 Thread Tracubik
Hi all!
I've made a simple PyGTK program.
It's a window with a notebook, the notebook have 2 pages
When changing page, i'ld like to get the id of current page.

I've coded it, but i can get only the previously open page, not the 
current one. This is not a big deal if i have only 2 pages, but it could 
be with 3 or more pages.

Here's the code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# template di finestra in pyGTK

import pygtk
pygtk.require('2.0')
import gtk

class FinestraGTK:

def pippo(self, widget, event, data=None):
print "current page: " + str(self.nb.get_current_page() )

def delete_event(self, widget, event, data=None):
print "delete event occurred"
return False

def destroy(self, widget, data=None):
print "destroy signal occurred"
gtk.main_quit()

def __init__(self):
self.w = gtk.Window(gtk.WINDOW_TOPLEVEL)

self.w.connect("delete_event", self.delete_event)
self.w.connect("destroy", self.destroy)

self.w.set_border_width(10)
self.w.set_default_size(455,460)

# NOTEBOOK + LABELS
self.nb = gtk.Notebook()
self.nb_label1 = gtk.Label("page 0")
self.nb_label2 = gtk.Label("page 1")

# PAGE 1
self.b1 = gtk.Button("button tab 0")
self.nb.insert_page(self.b1, self.nb_label1, 0)
# PAGE 2
self.b2 = gtk.Button("button tab 1")
self.nb.insert_page(self.b2, self.nb_label2, 1)

self.w.add(self.nb)
self.nb.connect("switch-page", self.pippo)
self.b1.connect("clicked", self.pippo, "")
self.b2.connect("clicked", self.pippo, "")

self.w.show_all()

def main(self):
gtk.main()

if __name__ == "__main__":
hello = FinestraGTK()
hello.main()


any hint? i know it's all about correctly temporize signals, but i don't 
know how to accompliesh this

many thanks
regards
sorry for my english
Nico
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python3: imports don't see files from same directory?

2011-05-07 Thread Ian Kelly
On Sat, May 7, 2011 at 4:02 AM, dmitrey  wrote:
> hi all,
> I try to port my code to Python 3 and somehow files don't see files
> from same directory, so I have to add those directories explicitly,
> e.g.
> import sys
> sys.path += [...]
>
> Also, it leads to bugs like this one:
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/961a90219a61e19d#
>
> any ideas what's the reason and how to fix it?
> I have tried to search google but got nothing yet.

Implicit relative imports were removed in Python 3 to prevent
ambiguity as the number of packages grows.  See PEP 328.

If you have two modules in the same package, pack1.mod1 and
pack1.mod2, then in pack1.mod1 you can no longer just do "import mod2"
or "from mod2 import foo".  Either use an absolute import ("from
pack1.mod2 import foo") or make the relative import explicit ("from
.mod2 import foo" -- note the ".")

If you're upgrading scripts from Python 2 to Python 3, you should
really run them through the 2to3 tool.  I believe this is one of the
many things it will fix for you automatically.
-- 
http://mail.python.org/mailman/listinfo/python-list


Django/AppEngine DevSoup

2011-05-07 Thread John
Sooo I have a windows box... which I like to think is the reason I'm a
django/appengine mess right now.

There's eclipse, pydev, django non-rel, mediagenerator, etc

Would it be stupid of me to just use the simple, clean notepad++ &
django with aims to port into appengine after I finish in a week? I
don't want to deal with all of the other stuff. Will this come back to
haunt me in 7 days?

Yours frazzled,
John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE/text-editor

2011-05-07 Thread emato

> On Apr 16, 1:20 pm, Alec Taylor  wrote:
>
>> I'm looking for an IDE which offers syntax-highlighting,
>> code-completion, tabs,

gedit

http://projects.gnome.org/gedit/index.html 


-- 
http://mail.python.org/mailman/listinfo/python-list


ABC-registered Exceptions are not caught as subclasses

2011-05-07 Thread andrew cooke

This isn't hugely surprising, but doesn't seem to be documented.  Is it a bug, 
or worth raising as one, or have I misunderstood?


Python 3.2 (r32:88445, Feb 27 2011, 13:00:05) 
[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from abc import ABCMeta
>>> class RootException(Exception,metaclass=ABCMeta): pass
... 
>>> class MyException(Exception): pass
... 
>>> RootException.register(MyException)
>>> try:
... raise MyException
... except RootException:
... print('caught')
... 
Traceback (most recent call last):
  File "", line 2, in 
__main__.MyException

If you assume that the ABC "register" class should work likeinheritance (as it 
does with issubclass and isinstance then you would, I think, have expected the 
exception above to have been caught.

Andrew
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Ben Finney
Gregory Ewing  writes:

> > On Thu, 05 May 2011 07:43:59 +1000, Ben Finney wrote:
> >
> >>‘x’ is a name. Names are bound to values. Talk of “variable” only
> >>confuses the issue because of the baggage carried with that term.
>
> But to use 'name' as a complete replacement for 'variable',

I don't propose doing that.

> In Python I use 'variable' to mean more or less 'something that can be
> assigned to', which accords with the way it's used in relation to many
> other languages, and doesn't suggest any restriction to things named
> by a single identifier.

No, I think not. The term “variable” usually comes with a strong
expectation that every variable has exactly one name. Your more broad
usage would need to be carefully explained to newbies anyway, so I don't
see a good reason to use the term “variable” for that either.

> Seems to me that anyone taking that connotation from it has not yet
> been sufficiently educated about the Python data model itself.

Yes, of course. But why not meet such newcomers partway, by not
confusing the issue with a term which needs such delicate treatment?

> >>Saying “variable” and “has the value”
>
> But I don't say "has a value", I say "refers to".

Good for you. Most don't.

-- 
 \ Q: “I've heard that Linux causes cancer...” Torvalds: “That's a |
  `\ filthy lie. Besides, it was only in rats and has not been |
_o__)   reproduced in humans.” —Linus Torvalds |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dictionary size changed during iteration

2011-05-07 Thread Laszlo Nagy



...

That works, but if d is large, it won't be very efficient because it has
to generate a large list.

It is not large. But I'm using Python 2.6 , not Python 3.

I did not get this error again in the last two days. I'll post a new 
reply if I encounter it again. (It happened just a few times out of many 
thousand program invocations)

--
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Roy Smith
In article <87aaeymfww@benfinney.id.au>,
 Ben Finney  wrote:

> No, I think not. The term “variable” usually comes with a strong
> expectation that every variable has exactly one name.

Heh.  You've never used common blocks in Fortran?  Or, for that matter, 
references in C++?  I would call either of those "two names for the same 
variable".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coolest Python recipe of all time

2011-05-07 Thread Raymond Hettinger
On May 7, 1:29 am, Steven D'Aprano  wrote:
> On Fri, 06 May 2011 12:36:09 -0600, Ian Kelly wrote:
> > The amb engine would conceptually execute this function for every
> > possible combination of a, b, and c,
>
> Which pretty much is the definition of "brute-force solver", no?

FWIW, here's one of my favorite brute-force solvers:

   http://code.activestate.com/recipes/576615-alphametics-solver/


Raymond

---
follow my recipes and tips on twitter:  @raymondh

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dictionary size changed during iteration

2011-05-07 Thread Paul Rubin
Roy Smith  writes:
> changes = [ ]
> for key in d.iterkeys():
>   if is_bad(key):
> changes.append(key)

changes = list(k for k in d if is_bad(k))

is a little bit more direct.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyGTK notebook: get current page

2011-05-07 Thread Alexander Kapps

On 07.05.2011 17:04, Tracubik wrote:

Hi all!
I've made a simple PyGTK program.
It's a window with a notebook, the notebook have 2 pages
When changing page, i'ld like to get the id of current page.

I've coded it, but i can get only the previously open page, not the
current one. This is not a big deal if i have only 2 pages, but it could
be with 3 or more pages.

Here's the code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# template di finestra in pyGTK

import pygtk
pygtk.require('2.0')
import gtk

class FinestraGTK:

 def pippo(self, widget, event, data=None):
 print "current page: " + str(self.nb.get_current_page() )


According to PyGTK docs, the event handler for the switch_page 
signal should look like this:


def pippo(self, notebook, page, page_num, user_data=None):
...

With this method you get the new page number in page_num (or in your 
original method with the misleadingly named "data" argument)



HTH
--
http://mail.python.org/mailman/listinfo/python-list


Re: dictionary size changed during iteration

2011-05-07 Thread Roy Smith
In article <7xd3jukyn9@ruckus.brouhaha.com>,
 Paul Rubin  wrote:

> Roy Smith  writes:
> > changes = [ ]
> > for key in d.iterkeys():
> >   if is_bad(key):
> > changes.append(key)
> 
> changes = list(k for k in d if is_bad(k))
> 
> is a little bit more direct.

This is true.  I still file list comprehensions under "new fangled 
toys".  While I use them, and appreciate their value, I admit they're 
not always the first thing that comes to my mind.

OBTW,

> changes = [k for k in d if is_bad(k)]

is even more direct :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Gregory Ewing

Chris Angelico wrote:


I think "manipulate" here means things like pointer arithmetic,


I don't believe that allowing arithmetic on pointers
is a prerequisite to considering them first-class values.
You can't do arithmetic on pointers in Pascal, for
example, but nobody argues that Pascal pointers are
not values.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


is there an autocompletion like Dasher ?

2011-05-07 Thread Stef Mientki
hello,

I would like to have a autocompletion / help /snippet system like Dasher :

http://www.inference.phy.cam.ac.uk/dasher/

anyone seen such a component ?

thanks,
Stef
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Gregory Ewing

Ben Finney wrote:


No, I think not. The term “variable” usually comes with a strong
expectation that every variable has exactly one name.


I would say that many variables don't have names *at all*,
unless you consider an expression such as a[i] to be
a "name". And if you *do* consider that to be a name,
then clearly one variable can have a great many names.

What would *you* call a[i]?

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: seems like a bug in isinstance()

2011-05-07 Thread Gregory Ewing

dmitrey wrote:


Yes, you are right. But I have to do it due to another issue I haven't
solved yet: Python3 imports don't see files from same directory
http://groups.google.com/group/comp.lang.python/browse_thread/thread/9470dbdacc138709#


That's because the syntax for relative imports has changed
in Python 3. See the recent comment on your posting there
for details.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: Django/AppEngine DevSoup

2011-05-07 Thread Gregory Ewing

John wrote:

There's eclipse, pydev, django non-rel, mediagenerator, etc

Would it be stupid of me to just use the simple, clean notepad++ &
django with aims to port into appengine after I finish in a week? I
don't want to deal with all of the other stuff. Will this come back to
haunt me in 7 days?


I'd say you definitely don't need Eclipse, and probably
don't need the other stuff.

I've being doing all my Python coding using relatively
dumb text editors for many years, including maintaining
a django-based site, and haven't suffered any hauntings
so far. :-)

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there an autocompletion like Dasher ?

2011-05-07 Thread Dan Stromberg
On Sat, May 7, 2011 at 3:40 PM, Stef Mientki  wrote:

> hello,
>
> I would like to have a autocompletion / help /snippet system like Dasher :
>
> http://www.inference.phy.cam.ac.uk/dasher/
>
> anyone seen such a component ?
>

Ummm...  For what OS and what hardware?  Do you need something that was
written in Python?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Chris Angelico
On Sun, May 8, 2011 at 8:54 AM, Gregory Ewing
 wrote:
> Ben Finney wrote:
>
>> No, I think not. The term “variable” usually comes with a strong
>> expectation that every variable has exactly one name.
>
> I would say that many variables don't have names *at all*,
> unless you consider an expression such as a[i] to be
> a "name". And if you *do* consider that to be a name,
> then clearly one variable can have a great many names.
>
> What would *you* call a[i]?

a is a variable; i is a variable; a[i] is an expression. It's not a
single name, and if you had two variables i and j with the same value,
nobody would disagree that a[i] and a[j] ought to be the same thing.
That's the whole point of arrays/lists/etc/etc. But if you want to fry
your noggin, wrap your head around REXX's compound variables:

a=5
b=3
array.a.b="Hello" /* see, this is a two-dimensional array */

c=63/10
array.c="world!" /* see, we can have non-integers as array indices */

d=a+1
result = array.a.b", "array.d.b /* "Hello, world!" */

So what is a "name" in REXX? You have to evaluate the compound
variable as a set of tokens, then evaluate the whole thing again, and
is that the name? Because the resulting "name" might not be a valid
identifier...

Yep, it's good stuff.

Chris Angelico
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there an autocompletion like Dasher ?

2011-05-07 Thread Stef Mientki
On 08-05-2011 01:28, Dan Stromberg wrote:
>
> On Sat, May 7, 2011 at 3:40 PM, Stef Mientki  > wrote:
>
> hello,
>
> I would like to have a autocompletion / help /snippet system like Dasher :
>
> http://www.inference.phy.cam.ac.uk/dasher/
>
> anyone seen such a component ?
>
>
> Ummm...  For what OS and what hardware?
Windows desktop (and webbrowser would be nice)
>   Do you need something that was written in Python?
>
>  
preferable

thanks,
Stef
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A suggestion for an easy logger

2011-05-07 Thread mcilrain
Aside from the fact that it's very Javay, what's wrong with the logging module?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Ben Finney
Gregory Ewing  writes:

> Ben Finney wrote:
>
> > No, I think not. The term “variable” usually comes with a strong
> > expectation that every variable has exactly one name.
>
> I would say that many variables don't have names *at all*, unless you
> consider an expression such as a[i] to be a "name".

Again, our disagreement is not over the behaviour of Python, but over
what an average newcomer to Python can be expected to understand by the
term “variable” from its usage elsewhere in programming.

> What would *you* call a[i]?

What *I* would call that isn't relevant to the point. I do think it's
even more misleading to call that “a variable”, though, since it's not
what the Python docs call a variable and it's not what an average
newcomer would call a variable.

It's a reference. So is ‘a’, so is ‘i’; names are a special kind of
reference. In Python, references are how we get at objects within our
code, and names are one kind of reference.

-- 
 \  “Not using Microsoft products is like being a non-smoker 40 or |
  `\ 50 years ago: You can choose not to smoke, yourself, but it's |
_o__)   hard to avoid second-hand smoke.” —Michael Tiemann |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ABC-registered Exceptions are not caught as subclasses

2011-05-07 Thread Chris Rebert
On Sat, May 7, 2011 at 12:03 PM, andrew cooke  wrote:
>
> This isn't hugely surprising, but doesn't seem to be documented.  Is it a 
> bug, or worth raising as one, or have I misunderstood?
>
>
> Python 3.2 (r32:88445, Feb 27 2011, 13:00:05)
> [GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 from abc import ABCMeta
 class RootException(Exception,metaclass=ABCMeta): pass
> ...
 class MyException(Exception): pass
> ...
 RootException.register(MyException)
 try:
> ...     raise MyException
> ... except RootException:
> ...     print('caught')
> ...
> Traceback (most recent call last):
>  File "", line 2, in 
> __main__.MyException
>
> If you assume that the ABC "register" class should work likeinheritance (as 
> it does with issubclass and isinstance then you would, I think, have expected 
> the exception above to have been caught.

Seems worth filing a bug IMO; it probably deserves clarification in
the docs if nothing else, though this behavior isn't inconsistent with
them as they're currently written (due to the vagaries of natural
language).

Cheers,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Steven D'Aprano
On Sat, 07 May 2011 21:21:45 +1200, Gregory Ewing wrote:

> Hans Georg Schaathun wrote:
> 
>> You cannot reference nor manipulate a reference in python, and that
>> IMHO makes them more abstract.
> 
> You can manipulate them just fine by moving them from one place to
> another:
> 
> a = b

I see no reference there, nor do I see any moving taking place. What I 
see is a name binding operation. What is happening is that the name "a" 
is being bound to the object "b" (or to be precise, to whatever object is 
currently bound to name "b").

Since you haven't explained what you think is happening, I can only 
guess. My guess is that you are thinking about some implementation of the 
Python VM which uses some sort of reference internally. Perhaps it's 
CPython, which uses pointers, or some C++ implementation which actually 
uses an indirect pointer-like data structure called "reference", or maybe 
even some old-time FORTRAN I implementation that simulates pointers with 
integer indexes into a fixed size array. It could be anything.

But whatever you're thinking of, it's not the behaviour of *Python* code, 
it's behaviour of the Python virtual machine's implementation.

It astonishes me how hard it is to distinguish between abstraction levels 
when discussing computer languages. We don't have this problem in other 
fields. Nobody talking about (say) Solitaire on a computer would say:

"Blat the pixels in the rect A,B,C,D to the rect E,F,G,H. That will free 
up the Ace of Spades and allow you to memcopy the records in the far 
right column of the tableau into the foundation."

but when it comes to high-level computer languages like Python, we do the 
equivalent *all the time*. (I include myself in this.) And people get 
into (often angry) arguments over definitions, when what they're really 
arguing about is what is happening at different abstraction levels.

A simplified view:


At the Python level: binding of objects to names. No data is copied 
except by use of a direct "copy" instruction, e.g. slicing.

At the Python VM level: objects pushed and popped from a stack.

At the VM implementation level: Name binding may be implemented by 
copying pointers, or some other reference, in some data structure 
representing name spaces. Or by any other mechanism you like, so long as 
the behaviour at the Python level is the same.

At the assembly language level: memory is copied from one address to 
another.

At the hardware level: we usually describe bit manipulation in terms of 
binary AND, XOR and OR, but even that may be an abstraction: it's 
possible that the only binary op physically used by the machine is NAND.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A suggestion for an easy logger

2011-05-07 Thread Vinay Sajip
On May 8, 1:00 am, mcilrain  wrote:
> Aside from the fact that it's very Javay, what's wrong with theloggingmodule?

It's not especially Java-like. Since you can log using just

import logging

logging.basicConfig(level=logging.DEBUG)
logging.debug('This is %sic, not %s-like - that's FUD', 'Python',
'Java')

it doesn't seem especially Java-like: no factories, Interfaces,
builders, using plain functions etc.

The second line is optional and needed only if you want to log DEBUG
or INFO messages (as the default threshold is WARNING).

Despite other logging libraries claiming to be more Pythonic, they
have pretty much the same concepts as stdlib logging - because those
concepts are tied to logging, not to Java. Call it correlation vs.
causation, or convergent evolution, or what you will.

Regards,

Vinay Sajip
-- 
http://mail.python.org/mailman/listinfo/python-list


Py 3.2: sqlite can't operate on a closed cursor

2011-05-07 Thread Gnarlodious
I installed Python 3.2, suddenly getting an error on my sqlite pages
(CGI):

ProgrammingError: Cannot operate on a closed cursor

Works normally in interactive mode. Seems to error when the sqlite
statement is in a function. Are sqlite objects now required to be
declared global?

-- Gnarlie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Py 3.2: sqlite can't operate on a closed cursor

2011-05-07 Thread Gnarlodious
It turns out Python 3.2 now honors closing sqlite connections opened
in another module. Previous versions allowed you to have identically
named sqlite connections open in other modules. Python 3.2 apparently
treats them all as the same connection.

Hopefully some other victim will find this, because it wasn't written
in the documentation
http://docs.python.org/dev/whatsnew/3.2.html#sqlite3

-- Gnarlie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-07 Thread harrismh777

Steven D'Aprano wrote:

... if not li  says nothing about what li is supposed to 'be'

Yes, and? Neither does:

isempty(li)  # li could be anything that polymorphic isempty can deal with
li.isempty()  # li could be anything with a "isempty" method
len(li) == 0  # li could be anything with a length (list, dict, set, ...)


 Sure.


That's duck-typing for you, and it is generally a strength rather than a
weakness. For those times when it is a weakness, that's where we have
naming conventions, type-testing, and (in some languages) static types.


 I can fix almost anything with duck-type...:)


>  and implies in any case that li does not exist

It does nothing of the sort. If li doesn't exist, you get a NameError.


 That was the point.   'not' implies something that is not logical; 
which is irony extreme since 'not' is typically considered a logical 
operator.   What does it mean to say  not ?  Well, apparently 
it means the list is 'empty'... but why should it mean that? Why not 
have it mean the list has been reversed in place?  Why not have it mean 
that the list isn't homogeneous?  Why not have it mean that its not 
mutable?  I could think of more... Why should 'not' mean 'empty'?



>  or worse is some kind of boolean.

Only if you're still thinking in some language that isn't Python.


   Which most of us are... hate to remind you...   Python is the new 
kid on the block, and most of us are coming at this from multiple 
filters in comp sci experience.  Its just the truth.



>   Why not have a list method that makes this more explicit:

For the same reason that we don't have an int method that makes zero
testing more explicit:



Because sometimes you can have too much explicitness.


True.


kind regards,

m harris


--
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread harrismh777

Steven D'Aprano wrote:

  Nobody talking about (say) Solitaire on a computer would say:

"Blat the pixels in the rect A,B,C,D to the rect E,F,G,H. That will free
up the Ace of Spades and allow you to memcopy the records in the far
right column of the tableau into the foundation."

but when it comes to high-level computer languages like Python, we do the
equivalent *all the time*.


I find exception to that argument. That is an example of the bogus 
analogy fallacy. (I am offering this in friendship, actually). The two 
cases have nothing to do with one another, do not affect one another 
directly or indirectly, and are not helpful for comparison sake. 
Analogies are generally not helpful in discussion and ought to be 
avoided generally... except for entertainment sake... and frankly I have 
found many of your analogies most entertaining (and creative) !


Second point, we seldom do anything *all the time* /  this is a 
fallacy that presupposes extreme references, as we think about the 
argument; extreme exageration is not helpful... may or may not be 
rightly extreme, and may or may not be relevant.


What can be said (about the argument) is that we sometimes waste 
time arguing over abstraction layers with limited cross-dependent 
understanding.


(I include myself in this.)

(myself, as well)   ... the humility is appreciated.


And people get
into (often angry) arguments over definitions, when what they're really
arguing about is what is happening at different abstraction levels.


Sometimes. More often than not, folks are not really angry (I am 
seldom angry at my computer terminal... its one of the places where I 
relax, learn, communicate, and relate with other computer scientists who 
enjoy what they do because its enjoyable. I do agree with you that we 
all sometimes talk past each other because we're arguing from within a 
'different' level of abstraction.




kind regards,
m harris


--
http://mail.python.org/mailman/listinfo/python-list


Re: A suggestion for an easy logger

2011-05-07 Thread TheSaint
Vinay Sajip wrote:

WoW :O , the creator !!

> import logging
> 
> logging.basicConfig(level=logging.DEBUG)

I'm getting there, but the result it's not what I would.
As far as I got to know, it should take to write a configuration file, which 
I still not aware of.
I'd like to just have the 4 conditions mentioned in the first post.
Once I'll get into the dirt I'll try to bring up also the other features 
that logging module gives.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-07 Thread Ethan Furman

harrismh777 wrote:

Steven D'Aprano wrote:

>>>  attribution lost wrote:

>  and implies in any case that li does not exist

It does nothing of the sort. If li doesn't exist, you get a NameError.


 That was the point.   'not' implies something that is not logical; 
which is irony extreme since 'not' is typically considered a logical 
operator.   What does it mean to say  not ?  Well, apparently 
it means the list is 'empty'... but why should it mean that? Why not 
have it mean the list has been reversed in place?  Why not have it mean 
that the list isn't homogeneous?  Why not have it mean that its not 
mutable?  I could think of more... Why should 'not' mean 'empty'?


Because this is Python, and in Python that's what it means.




>  or worse is some kind of boolean.

Only if you're still thinking in some language that isn't Python.


   Which most of us are... hate to remind you...   Python is the new kid 
on the block, and most of us are coming at this from multiple filters in 
comp sci experience.  Its just the truth.


And your point would be?

If you're going to use a language, and use it well, you have to learn 
how that language works.


~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: Fibonacci series recursion error

2011-05-07 Thread Robert Brown

Steven D'Aprano  writes:
> If you value runtime efficiency over development time, sure. There are
> plenty of languages which have made that decision: Pascal, C, Java,
> Lisp, Forth, and many more.

I don't understand why you place Lisp and Forth in the same category as
Pascal, C, and Java.  Lisp and Forth generally have highly interactive
development environments, while the other languages generally require an
edit, compile, run it again debugging cycle.  Lisp in particular does a
better job than Python in optimizing developer time.  I can change class
definitions interactively without restarting my program.  I can add type
declarations to a single function and recompile it without restarting my
program.  Python requires me to rewrite the slow bits of my program in C
to get good performance.  Why is that an efficient use of developer
time?

bob
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread rusi
On May 8, 7:17 am, Steven D'Aprano  wrote:
> On Sat, 07 May 2011 21:21:45 +1200, Gregory Ewing wrote:
> > Hans Georg Schaathun wrote:
>
> >> You cannot reference nor manipulate a reference in python, and that
> >> IMHO makes them more abstract.
>
> > You can manipulate them just fine by moving them from one place to
> > another:
>
> >     a = b
>
> I see no reference there, nor do I see any moving taking place. What I
> see is a name binding operation. What is happening is that the name "a"
> is being bound to the object "b" (or to be precise, to whatever object is
> currently bound to name "b").
>
> Since you haven't explained what you think is happening, I can only
> guess. My guess is that you are thinking about some implementation of the
> Python VM which uses some sort of reference internally. Perhaps it's
> CPython, which uses pointers, or some C++ implementation which actually
> uses an indirect pointer-like data structure called "reference", or maybe
> even some old-time FORTRAN I implementation that simulates pointers with
> integer indexes into a fixed size array. It could be anything.
>
> But whatever you're thinking of, it's not the behaviour of *Python* code,
> it's behaviour of the Python virtual machine's implementation.
>
> It astonishes me how hard it is to distinguish between abstraction levels
> when discussing computer languages. We don't have this problem in other
> fields. Nobody talking about (say) Solitaire on a computer would say:
>
> "Blat the pixels in the rect A,B,C,D to the rect E,F,G,H. That will free
> up the Ace of Spades and allow you to memcopy the records in the far
> right column of the tableau into the foundation."
>
> but when it comes to high-level computer languages like Python, we do the
> equivalent *all the time*.

It has to be so -- because the Turing machine like the modern computer
is an unbelievable abstraction squasher.  Yes unbelievable in the
sense that people simply cant come to terms with this.  [Witness your
"It astonishes me..." Harris: "I take exception.." etc]

The modern computer (von Neumann) <- self-modifying code <- Data=Code
<- Undecidability (Halting problem) <- Consistency XOR Completeness
(Godels theorem(s)) <- Leaky Abstractions as inevitable

If anyone thinks Godels theorems are easy trivial, he probably does
not know what he is talking about,  Yet we think that computers are
easy to understand?

[Ive personally witnessed PhDs in computer science not appreciate
compilers' inability to do certain things, and yet they could go and
take a bunch of lectures on the halting problem.  What they understand
is anybody's guess :-) ]

Coming back to topic:  The argument (about bindings, variables etc)
arises because python (like lisp) is an imperative language
masquerading as a functional one.
Such arguments dont arise in Haskell or in assembly language.
They arise and are tolerable in C.
They are terrible in C++ because all the abstractions are built to
leak.

Where python sits in this (circular) spectrum is an interesting
question
(and I watch the arguments with much interest)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python3: imports don't see files from same directory?

2011-05-07 Thread John O'Hagan
On Sat, 7 May 2011, Ian Kelly wrote:
[...]
> 
> Implicit relative imports were removed in Python 3 to prevent
> ambiguity as the number of packages grows.  See PEP 328.
> 
> If you have two modules in the same package, pack1.mod1 and
> pack1.mod2, then in pack1.mod1 you can no longer just do "import 
mod2"
> or "from mod2 import foo".  Either use an absolute import ("from
> pack1.mod2 import foo") or make the relative import explicit ("from
> .mod2 import foo" -- note the ".")
> 
> If you're upgrading scripts from Python 2 to Python 3, you should
> really run them through the 2to3 tool.  I believe this is one of the
> many things it will fix for you automatically.

For some reason I haven't fathomed yet, I've found that while 2to3 
does change the import syntax to the dot form as you say, this results 
in "ValueError: Attempted relative import in non-package", and I have 
to change it back to the old way, which works fine although the docs 
say it shouldn't. This is python 3.2 on Debian testing. 

For example, if I have a directory containing an __init__.py file, and two 
modules, one of which is called mod1 and contains

#!/usr/bin/python3
a=1

in the other module I can have

import mod1

or

from  mod1 import a

but not 

from .mod1 import a

or

import .mod1


What gives?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A suggestion for an easy logger

2011-05-07 Thread TheSaint
TheSaint wrote:

> I'd like to just have the 4 conditions mentioned in the first post.
> 
OK, my analysis led me to the print() function, which would suffice for 
initial my purposes.
Meanwhile I reading the tutorials, but I couldn't get how to make a 
formatter to suppress or keep the LF(CR) at the end of the statement.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python3: imports don't see files from same directory?

2011-05-07 Thread Benjamin Kaplan
On Sat, May 7, 2011 at 11:04 PM, John O'Hagan  wrote:
> On Sat, 7 May 2011, Ian Kelly wrote:
> [...]
>>
>> Implicit relative imports were removed in Python 3 to prevent
>> ambiguity as the number of packages grows.  See PEP 328.
>>
>> If you have two modules in the same package, pack1.mod1 and
>> pack1.mod2, then in pack1.mod1 you can no longer just do "import
> mod2"
>> or "from mod2 import foo".  Either use an absolute import ("from
>> pack1.mod2 import foo") or make the relative import explicit ("from
>> .mod2 import foo" -- note the ".")
>>
>> If you're upgrading scripts from Python 2 to Python 3, you should
>> really run them through the 2to3 tool.  I believe this is one of the
>> many things it will fix for you automatically.
>
> For some reason I haven't fathomed yet, I've found that while 2to3
> does change the import syntax to the dot form as you say, this results
> in "ValueError: Attempted relative import in non-package", and I have
> to change it back to the old way, which works fine although the docs
> say it shouldn't. This is python 3.2 on Debian testing.
>
> For example, if I have a directory containing an __init__.py file, and two
> modules, one of which is called mod1 and contains
>
> #!/usr/bin/python3
> a=1
>
> in the other module I can have
>
> import mod1
>
> or
>
> from  mod1 import a
>
> but not
>
> from .mod1 import a
>
> or
>
> import .mod1
>
>
> What gives?

* Absolute imports are given as modules coming straight from something
on sys.path. If you actually check sys.path, you'll probably notice
that '' is on there, which in this case refers to the current
directory.

* In order to do relative imports, you need to be in a package. Having
an __init__.py somewhere does not automatically make it a package. To
be a package, it has to be in one of the folders on sys.path. Since
python doesn't have a name for that folder that __init__.py is in,
it's not actually a part of a package.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread Chris Angelico
On Sun, May 8, 2011 at 4:16 PM, Dennis Lee Bieber  wrote:
> On Sun, 08 May 2011 10:54:57 +1200, Gregory Ewing
>  declaimed the following in
> gmane.comp.python.general:
>
>>
>> What would *you* call a[i]?
>>
>        Depending upon the nature of the beast, I'd be tempted to call it a
> "fully qualified name" or a "partially qualified name"
>
>        a = [1, 2, 4, ("c", "d", "e")]

Why is an integer more or less important than a tuple? a[3] is no less
qualified than a[2]; each of them points to an object. One of those
objects happens to contain other objects.

What if you had:
stdio = [stdin, stdout, stderr]

They might be 'file' objects, or they might be integers (unlikely in
Python), or they could be pipes or other file-like objects, or they
might be some kind of special tee object that contains two file
objects. Let's say your standard I/O uses the notation
stdout.write('message') and that you have a subclass of tuple that
will apply the . operator to all its members (is that possible in
Python? If not, pretend it is). You could then execute
stdio[1]=(stdout,teeobject) to easily copy your screen output to
another file. At this point, you can actually pretend that stdio[0]
and stdio[1] are identical objects, but you can use stdio[1][1] and
you can't use stdio[0][1] - which means that, per your definition, one
of them is only partially qualified.

As Inigo Montoya said, there is too much - let me sum up. Lists/tuples
and integers are equally objects, so whether or not you have a 'name'
is not affected by what type of object it points to.

Chris Angelico
-- 
http://mail.python.org/mailman/listinfo/python-list