Re: Naming Conventions, Where's the Convention Waldo?

2010-07-11 Thread Terry Reedy

On 7/11/2010 3:26 AM, rantingrick wrote:


Another source of asininity seems to be the naming conventions of the
Python language proper! True/False start with an upper case and i
applaud this. However str, list, tuple, int, float --need i go
on...?-- start with lowercase.


This is an anomaly, known to all long-time Pythoneers, due the the 
history of Python. Before 2.2 and unification of types and classes as 
new-style classes, those were all type constructor *functions*, not 
class names. The idea of breaking most every serious Python program on 
the planet by upper-casing them has been considered and so far rejected.


--
Terry Jan Reedy

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


Re: Learn Python the Hard Way (online tutorial)

2010-07-11 Thread Stephen Hansen
On 7/11/10 10:59 PM, Chris Rebert wrote:
> On Sun, Jul 11, 2010 at 10:03 PM, Paul Rubin  wrote:
>> I just came across this, a python tutorial purportedly intended for
>> beginning programmers.  I only read the first few pages and I'm not
>> crazy about the approach, but I haven't seen it mentioned here, and some
>> folks might like it:
>>
>>  http://learnpythonthehardway.org/home
> 
> "By Zed A. Shaw"
> 
> Hm...

Is there some significance to this name that I am unaware? Google points
me to a wikipedia article on a guy who appears involved in both Python
and Ruby. Is there something about him that colors or holds meaning for
his approach?

Just curious.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy questions from a python beginner

2010-07-11 Thread Terry Reedy

On 7/11/2010 1:48 PM, wheres pythonmonks wrote:


2.  How can I write a function, "def swap(x,y):..." so that "x = 3; y
= 7; swap(x,y);" given x=7,y=3??
(I want to use Perl's Ref "\" operator, or C's&).
(And if I cannot do this [other than creating an Int class], is this
behavior limited to strings,
  tuples, and numbers)


Since you are just exploring, addendum to other answers:

>>> x,y = 1,2
>>> def swapxy():
global x,y
x,y=y,x

>>> swapxy()
>>> x,y
(2, 1)

Not too useful

>>> s = [1,2]
>>> def swap01(lis):
lis[:2] = reversed(lis[:2]) # other versions possible

>>> swap01(s)
>>> s
[2, 1]

A function can *modify* an input object. When is does, the usual 
convention is that it should *not* return the object.


--
Terry Jan Reedy

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


Re: Easy questions from a python beginner

2010-07-11 Thread Steven D'Aprano
On Sun, 11 Jul 2010 21:52:17 -0700, sturlamolden wrote:

> On 11 Jul, 21:37, "Alf P. Steinbach /Usenet"  +use...@gmail.com> wrote:
> 
>> Oh, I wouldn't give that advice. It's meaningless mumbo-jumbo. Python
>> works like Java in this respect, that's all; neither Java nor Python
>> support 'swap'.
> 
> x,y = y,x


Of course that's a good alternative, but that's not what Alf, or the 
original poster, are talking about.

They're specifically talking about writing a function which swaps two 
variables in the enclosing scope. This is a good test of languages that 
support call-by-reference, e.g. Pascal:


procedure swap(var x:integer, var y: integer):
  VAR
tmp: integer;
  BEGIN
tmp := x;
x := y;
y := x;
  END;


If you pass two integer variables to swap(), Pascal will exchange their 
values. You can't do this in Python. You can get close if you assume the 
enclosing scope is global, or if you pass the name of the variables 
rather than the variables themselves, but even then you can't make it 
work reliably. Or at all.

Naturally the swap() function itself is not terribly useful in a language 
like Python that makes exchanging variables so easy, but there are other 
uses for call-by-reference that aren't quite so trivial. However, I can't 
think of anything off the top of my head, so here's another trivial 
example that can't work in Python:

s = "hello"
call_something_magic(s)
assert s == "goodbye"




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


Re: Learn Python the Hard Way (online tutorial)

2010-07-11 Thread Chris Rebert
On Sun, Jul 11, 2010 at 10:03 PM, Paul Rubin  wrote:
> I just came across this, a python tutorial purportedly intended for
> beginning programmers.  I only read the first few pages and I'm not
> crazy about the approach, but I haven't seen it mentioned here, and some
> folks might like it:
>
>  http://learnpythonthehardway.org/home

"By Zed A. Shaw"

Hm...

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


Re: Easy questions from a python beginner

2010-07-11 Thread Alf P. Steinbach /Usenet

* sturlamolden, on 12.07.2010 06:52:

On 11 Jul, 21:37, "Alf P. Steinbach /Usenet"  wrote:


Oh, I wouldn't give that advice. It's meaningless mumbo-jumbo. Python works like
Java in this respect, that's all; neither Java nor Python support 'swap'.


x,y = y,x



We're talking about defining a 'swap' routine that works on variables.

Since Java/Python doesn't support pass by reference of variables it's not 
possible in these languages, i.e., you missed the point, or made a joke. :-)


However, C# is very similar to Java, nearly all the way, except that in C# you 
can pass by reference. Remove that from C# and you have Java. Add that to Java 
and you have C#, roughly. No change in other aspects is needed. E.g. (ignore 
this if you've never heard about it, but it's a subtle point that you might be 
wondering about now) both Java and C# implement the definite assignment rule.


I.e., there's nothing in the core semantics that prevents accessing/passing the 
variables by reference, although for Python and Java it could be a 
terminological nightmare, and for Python compounded to the n'th degree by the 
general confusion of a subset of the Python community about basic concepts.


I don't know how C#'ers resolve the terminology...


Cheers & hth.,

- Alf

--
blog at http://alfps.wordpress.com>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Easy questions from a python beginner

2010-07-11 Thread Stephen Hansen
On 7/11/10 7:25 PM, Alf P. Steinbach /Usenet wrote:
> The alleged facts etc. you're referring are just that, alleged, by you.

Two people come together and have a debate. Both present arguments. Both
present cases. In the end, they are still in disagreement.

You declare us, "religious", and therefore our opinions, arguments,
facts, and conclusion are based solely on faith and unworthy of
consideration on their merits.

That, my friend, is an ad hominem attack. Hypocrite.

And you are plonked.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't python's list append() method return the list itself?

2010-07-11 Thread Chris Rebert
On Sun, Jul 11, 2010 at 10:03 PM, Nathan Rice
 wrote:
> Yeah, I long ago filed the in place place in the same folder as

> all() returning True for an empty iterable

If you weren't taught about vacuous truth (or even identity elements)
in Discrete Mathematics, someone fscked up. Said behavior is the
absolute correct behavior from a formal logic standpoint.

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


Re: Why doesn't python's list append() method return the list itself?

2010-07-11 Thread Stephen Hansen
On 7/11/10 10:03 PM, Nathan Rice wrote:
> Yeah, I long ago filed the in place place in the same folder as
> strings-as-sequences, all() returning True for an empty iterable and any
> returning True rather than the thing which triggered it.

You know, the latter two I can see an argument for, and could see the
usefulness therein -- though I've never used either like that, but I
consider that chance. I could see the use (and could readily write my
own all/any in such a case, then keep it in my toolbox).

But the first: what?!

for ch in data:

is exceptionally useful. Strings-as-sequences I've used hundreds,
thousands of times. I use it constantly.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Learn Python the Hard Way (online tutorial)

2010-07-11 Thread Paul Rubin
I just came across this, a python tutorial purportedly intended for
beginning programmers.  I only read the first few pages and I'm not
crazy about the approach, but I haven't seen it mentioned here, and some
folks might like it:

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


Re: Why doesn't python's list append() method return the list itself?

2010-07-11 Thread Nathan Rice
Yeah, I long ago filed the in place place in the same folder as
strings-as-sequences, all() returning True for an empty iterable and any
returning True rather than the thing which triggered it.  Almost always
annoying and worked around, but that's the price you pay for the other nice
stuff :)  It just takes writing a few hundred lines of Java code for me to
shrug and forget about it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy questions from a python beginner

2010-07-11 Thread sturlamolden
On 11 Jul, 21:37, "Alf P. Steinbach /Usenet"  wrote:

> Oh, I wouldn't give that advice. It's meaningless mumbo-jumbo. Python works 
> like
> Java in this respect, that's all; neither Java nor Python support 'swap'.

x,y = y,x

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


Re: IOError and Try Again to loop the loop.

2010-07-11 Thread Chris Rebert
> On Jul 12, 2:14 pm, Chris Rebert  wrote:
>> On Sun, Jul 11, 2010 at 8:13 PM, The Danny Bos  wrote:
>> > Thanks gang,
>> > I'm gonna paste what I've put together, doesn't seem right. Am I way
>> > off?
>>
>> > Here's my code.
>> >  - It goes through a table Item
>> >  - Matches that Item ID to an API call
>> >  - Grabs the data, saves it and creates the thumbnail
>> >  - It dies due to Timeouts and Other baloney, all silly, nothing code
>> > based.
>>
>> > items = Item.objects.all().filter(cover='').order_by('-reference_id')
>> > for item in items:
>> >        url = "http://someaddress.org/books/?issue=%s"; % item.reference_id
>>
>> >        url_array = []
>> >        url_open = urllib.urlopen(url)
>> >        url_read = url_open.read().decode('utf-8')
>>
>> >        try:
>> >                url_data = simplejson.loads(url_read)
>> >                url_array.append(url_data)
>>
>> >                for detail in url_array:
>>
>> Unless I'm missing something, there's no need for url_array to exist
>> at all. It starts out empty, you append url_data to it, then you
>> iterate over it as `detail`; and you don't touch it anywhere else in
>> the loop. Just s/detail/url_data/ and excise url_array altogether. As
>> a bonus, there'll be one less level of indentation.
>>
>> Also, the reason your code doesn't work (currently, it just skips to
>> the next item upon error) is because you're missing a surrounding
>> `while True` loop (and associated embedded `break`) to do the retrying
>> (see my or MRAB's examples).
>>
>> Additionally, stylistically I'd prefer the try-excepts to cover
>> smaller and more targeted areas of the code, rather than having one
>> giant blanket one for the entire loop body; perhaps that's just me
>> though.

On Sun, Jul 11, 2010 at 9:20 PM, The Danny Bos  wrote:
> Thanks Chris,
>
> Agreed some of the code is a lot useless, I need to go through that
> stuff.
> So something like this (apologies for asking for some details, I'm not
> good at catching):
>
> items = Item.objects.all().filter(cover='').order_by('-reference_id')
> for item in items:
>    url = "http://someaddress.org/books/?issue=%s"; %
> item.reference_id
>    url_array = []
>    url_open = urllib.urlopen(url)
>    url_read = url_open.read().decode('utf-8')
>
>    while True:
>        try:

>                break
>        except ValueError:
>                print "Error Processing record: %s: %s" %
> (item.reference_id, url)
>                pass
>        except IOError:
>                print "IOError; Retrying..."
>                pass
>
> print "Done"

Yes, correct, that's essentially it, although the `pass` statements
are superfluous, and I would personally put the `break` in a
separate+new else-clause of the try-except for clarity; so the
try-except part of the code would look like:

try:
# lots of code here
except ValueError:
print "Error Processing record: %s: %s" % (item.reference_id, url)
except IOError:
print "IOError; Retrying..."
else:
break

Also, please avoid top-posting in the future;
http://en.wikipedia.org/wiki/Top-posting#Top-posting

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


Re: IOError and Try Again to loop the loop.

2010-07-11 Thread The Danny Bos


Thanks Chris,

Agreed some of the code is a lot useless, I need to go through that
stuff.
So something like this (apologies for asking for some details, I'm not
good at catching):

items = Item.objects.all().filter(cover='').order_by('-reference_id')
for item in items:
url = "http://someaddress.org/books/?issue=%s"; %
item.reference_id
url_array = []
url_open = urllib.urlopen(url)
url_read = url_open.read().decode('utf-8')

while True:
try:
url_data = simplejson.loads(url_read)
url_array.append(url_data)
for detail in url_array:
if detail['artworkUrl']:
cover_url =
detail['artworkUrl'].replace(' ','%20')
cover_open =
urllib.urlretrieve(cover_url)
cover_name = os.path.split(cover_url)
[1]
item.cover.save(cover_name,
File(open(cover_open[0])), save=True)
print "Cover - %s: %s" % (item.number,
url)
else:
print "Missing - %s: %s" %
(item.number, url)
break
except ValueError:
print "Error Processing record: %s: %s" %
(item.reference_id, url)
pass
except IOError:
print "IOError; Retrying..."
pass

print "Done"




On Jul 12, 2:14 pm, Chris Rebert  wrote:
> On Sun, Jul 11, 2010 at 8:13 PM, The Danny Bos  wrote:
>
>
>
>
>
> > Thanks gang,
> > I'm gonna paste what I've put together, doesn't seem right. Am I way
> > off?
>
> > Here's my code.
> >  - It goes through a table Item
> >  - Matches that Item ID to an API call
> >  - Grabs the data, saves it and creates the thumbnail
> >  - It dies due to Timeouts and Other baloney, all silly, nothing code
> > based.
>
> > items = Item.objects.all().filter(cover='').order_by('-reference_id')
> > for item in items:
> >        url = "http://someaddress.org/books/?issue=%s"; % item.reference_id
>
> >        url_array = []
> >        url_open = urllib.urlopen(url)
> >        url_read = url_open.read().decode('utf-8')
>
> >        try:
> >                url_data = simplejson.loads(url_read)
> >                url_array.append(url_data)
>
> >                for detail in url_array:
>
> Unless I'm missing something, there's no need for url_array to exist
> at all. It starts out empty, you append url_data to it, then you
> iterate over it as `detail`; and you don't touch it anywhere else in
> the loop. Just s/detail/url_data/ and excise url_array altogether. As
> a bonus, there'll be one less level of indentation.
>
> Also, the reason your code doesn't work (currently, it just skips to
> the next item upon error) is because you're missing a surrounding
> `while True` loop (and associated embedded `break`) to do the retrying
> (see my or MRAB's examples).
>
> Additionally, stylistically I'd prefer the try-excepts to cover
> smaller and more targeted areas of the code, rather than having one
> giant blanket one for the entire loop body; perhaps that's just me
> though.
>
> Cheers,
> Chris
> --
> How exactly does one acquire a prenominal "The"?http://blog.rebertia.com

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


[Python-ideas] explicitation lines in python ?

2010-07-11 Thread geremy condra
On Sun, Jul 11, 2010 at 11:39 PM, Carl M. Johnson
 wrote:
> On Sun, Jun 27, 2010 at 8:25 PM, Nick Coghlan  wrote:
>
>> The availability of "nonlocal" binding semantics also makes the
>> semantics much easier to define than they were in those previous
>> discussions (the lack of clear semantics for name binding statements
>> with an attached local namespace was the major factor blocking
>> creation of a reference implementation for this proposal back then).
>>
>> For example:
>>
>>  c = sqrt(a*a + b*b) where:
>>    a = retrieve_a()
>>    b = retrieve_b()
>>
>> could translate to something like:
>>
>>  def _anon(): # *(see below)
>>    nonlocal c
>>    a = retrieve_a()
>>    b = retrieve_b()
>>    c = sqrt(a*a + b*b)
>>  _anon()
>>
>> *(unlike Python code, the compiler can make truly anonymous functions
>> by storing them solely on the VM stack. It already does this when
>> executing class definitions):
>
> I like this idea, but I would tweak it slightly. Maybe we should say
>
> EXPRESSION where:
>    BLOCK
>
> is equivalent to
>
> def _():
>    BLOCK
>    return EXPRESSION
> _()
>
> That way, c = a where: a = 7 would be equivalent to
>
> def _():
>   a = 7
>   return a
> c = _()
>
> One advantage of this equivalence is it would make it easier to work
> around a longstanding scoping gotcha. A naïve coder might expect this
> code to print out numbers 0 to 4:
>
>    >>> fs = []
>    >>> for n in range(5):
>    ...     def f():
>    ...         print(item)
>    ...     fs.append(f)
>    ...
>    >>> [f() for f in fs]
>    4
>    4
>    4
>    4
>    4
>    [None, None, None, None, None]
>
> I think we all have enough experience to know this isn’t a totally
> unrealistic scenario. I personally stumbled into when I was trying to
> create a class by looping through a set of method names.
>
> To get around it, one could use a where clause like so:
>
> fs = []
> for n in range(5):
>    fs.append(f) where:
>        shadow = n
>        def f():
>            print(shadow)
>
> This would print out 0 to 4 as expected and be equivalent to
>
>    >>> fs = []
>    >>> for n in range(5):
>    ...     def _():
>    ...         shadow = n
>    ...         def f():
>    ...             print(shadow)
>    ...         fs.append(f)
>    ...     _()
>    ...
>    >>> [f() for f in fs]
>    0
>    1
>    2
>    3
>    4
>    [None, None, None, None, None]
>
> I think a where-clause with def-like namespace semantics would be a
> positive addition to Python, once the moratorium is up.
>
> -- Carl Johnson

+1 from me, FWIW

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


Re: IOError and Try Again to loop the loop.

2010-07-11 Thread Chris Rebert
On Sun, Jul 11, 2010 at 8:13 PM, The Danny Bos  wrote:
> Thanks gang,
> I'm gonna paste what I've put together, doesn't seem right. Am I way
> off?
>
> Here's my code.
>  - It goes through a table Item
>  - Matches that Item ID to an API call
>  - Grabs the data, saves it and creates the thumbnail
>  - It dies due to Timeouts and Other baloney, all silly, nothing code
> based.
>
> items = Item.objects.all().filter(cover='').order_by('-reference_id')
> for item in items:
>        url = "http://someaddress.org/books/?issue=%s"; % item.reference_id
>
>        url_array = []
>        url_open = urllib.urlopen(url)
>        url_read = url_open.read().decode('utf-8')
>
>        try:
>                url_data = simplejson.loads(url_read)
>                url_array.append(url_data)
>
>                for detail in url_array:

Unless I'm missing something, there's no need for url_array to exist
at all. It starts out empty, you append url_data to it, then you
iterate over it as `detail`; and you don't touch it anywhere else in
the loop. Just s/detail/url_data/ and excise url_array altogether. As
a bonus, there'll be one less level of indentation.

Also, the reason your code doesn't work (currently, it just skips to
the next item upon error) is because you're missing a surrounding
`while True` loop (and associated embedded `break`) to do the retrying
(see my or MRAB's examples).

Additionally, stylistically I'd prefer the try-excepts to cover
smaller and more targeted areas of the code, rather than having one
giant blanket one for the entire loop body; perhaps that's just me
though.

Cheers,
Chris
--
How exactly does one acquire a prenominal "The"?
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy questions from a python beginner

2010-07-11 Thread geremy condra
On Sun, Jul 11, 2010 at 10:39 PM, Steven D'Aprano
 wrote:
> On Mon, 12 Jul 2010 03:12:10 +0200, Alf P. Steinbach /Usenet wrote:
>
>> * MRAB, on 12.07.2010 00:37:
> [...]
>>> In Java a variable is declared and exists even before the first
>>> assignment to it. In Python a 'variable' isn't declared and won't exist
>>> until the first 'assignment' to it.
>>
>> That is a misconception.
>>
>> In Python a variable is declared by having an assignment to it, which
>> for a local variable may be anywhere within a routine.
>
> Oh, I'm going to regret being sucked into this...
>
> In *CPython*, but not necessarily other implementations, variables which
> are local to a function are not kept in a dictionary-based namespace, but
> in slots in the code object (not to be confused with __slots__ used for
> classes). Python has STORE_FAST and LOAD_FAST byte-codes for accessing
> locals.
>
> This is intended as a speed, and possibly memory, optimization. I don't
> believe this is a requirement though, so implementations may not do this.
>
> It is true that the slot is created at compile time, and in *that sense*,
> local variables exist before they are bound. I'm not entirely convinced
> that this is the only sense that matters, but never mind. The error
> message given exposes this to the user:
>
 def f():
> ...     print x
> ...     x = 1
> ...
 f()
> Traceback (most recent call last):
>  File "", line 1, in 
>  File "", line 2, in f
> UnboundLocalError: local variable 'x' referenced before assignment
>
>
> If you try this with a global, you get this:
>
 def f():
> ...     global x
> ...     print x
> ...
 f()
> Traceback (most recent call last):
>  File "", line 1, in 
>  File "", line 3, in f
> NameError: global name 'x' is not defined
>
> In this case, there's no doubt that global variable "x" doesn't exist at
> all -- there is no key "x" in the global namespace.
>
>
> It seems to me that "a slot to hold the variable is created for local
> variables" is an implementation detail, not a language feature. CPython
> could easily hide the difference by changing the exception from
> UnboundLocalError to:
>
> NameError: local name 'x' does not exist
>
> and nobody would be any wiser. (Well, perhaps people who catch
> UnboundLocalError, but why would you do that?)
>
> I also note that UnboundLocalError is a subclass of NameError, so
> "variable exists but is not bound" is considered to be a special case of
> "variable doesn't exist" rather than a completely independent case. In
> that sense, I think I'm on solid ground to say that in Python variables
> don't exist until they are bound to a value, and leave it to pedants like
> you and I to mention that for CPython local variables have space reserved
> for them by the compiler before they are bound.

Very interesting, and a pleasant change of tone to boot. Thanks.

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


Re: Getting started with python on macintosh snow leopard with mysql - need help

2010-07-11 Thread Benjamin Kaplan
On Sun, Jul 11, 2010 at 1:18 PM, dk  wrote:
> I have been going round and round trying to configure python 2.6
> running on osx 10.6.x to work with mySQL 5.1.44.
> Python seems to work ... i have an installation of mysql 5.1.44
> running and have used it in conjunction for other php/apache projects.
>
> I want to learn python and think i need a better database then mysql
> lite that installs with the web2py frame work, so my quest to connect
> to mysql or postgres began.
>
> I seem to be stuck stuck getting mySQLdb drivers installed.  I down
> loaded python 2.6.5 from the python site and MySQL-python-1.2.3 from
> the my sql site.
> I have worked past numerous errors by i now get the errors below when
> i try to compile.
>
> -- some background that might help anyone kind enough to have read
> this far and who might be inclined to take pitty --
> I have (tried) to use macports to install setuptools (which MySQL-
> python-1.2.3 says it needs).
> MacPorts has put tons of stuff in /opt/local ... so i am not sure i am
> using this tool the way its intended.
> this could all be as simple as adding some path declarations in the
> right place but where?
>

That could be part of your problem. Macports basically ignores the
rest of the system. Setuptools depends on python, so Macports compiles
and installs its own version of Python in /opt/local. So you now have
3 different versions of Python 2.6 on your computer: /usr/bin/python
(the System python), /usr/local/bin/python (the Python.org python) and
/opt/local/Library/Frameworks/Python.Framework/Versions/2.6/bin/python.
You can use Macport's python-select package to choose which one is the
default (it symlinks one of them to /opt/local/bin/python which should
be first on your path).

Anyway, as long as you're using Macports :

sudo port install py26-mysql

that should solve most of your problems :)

> lots of the post i have seen on the subject talk about 32/64
> installation ... it makes sense that you might need to be consistent
> in getting your components to work together, but i am not sure how i
> tell of the various parts i have install which and how they were
> compiled.
>
> whereis python  display  /usr/bin/python
> python -v spits out lots ... but here is a sample:
>
> # /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
> encodings/utf_8.pyc matches /Library/Frameworks/Python.framework/
> Versions/2.6/lib/python2.6/encodings/utf_8.py
> import encodings.utf_8 # precompiled from /Library/Frameworks/
> Python.framework/Versions/2.6/lib/python2.6/encodings/utf_8.pyc
> Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
> [GCC 4.0.1 (Apple Inc. build 5493)] on darwin
>
>
>
>
>
> when i try to compile mysql-python-1.2.3 i get the following error
> returned from python setup.py build -
>
> building '_mysql' extension
> gcc-4.0 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing
> -fno-common -dynamic -DNDEBUG -g -O3 -Dversion_info=(1,2,3,'final',0) -
> D__version__=1.2.3 -I/usr/local/mysql/include -I/Library/Frameworks/
> Python.framework/Versions/2.6/include/python2.6 -c _mysql.c -o build/
> temp.macosx-10.3-fat-2.6/_mysql.o -g -Os -arch x86_64 -fno-common -
> D_P1003_1B_VISIBLE -DSIGNAL_WITH_VIO_CLOSE -DSIGNALS_DONT_BREAK_READ -
> DIGNORE_SIGHUP_SIGQUIT -DDONT_DECLARE_CXA_PURE_VIRTUAL
> In file included from /Library/Frameworks/Python.framework/Versions/
> 2.6/include/python2.6/unicodeobject.h:4,
>                 from /Library/Frameworks/Python.framework/Versions/
> 2.6/include/python2.6/Python.h:85,
>                 from pymemcompat.h:10,
>                 from _mysql.c:29:
> /Developer/SDKs/MacOSX10.4u.sdk/usr/include/stdarg.h:4:25: error:
> stdarg.h: No such file or directory
> In file included from _mysql.c:36:
> /usr/local/mysql/include/my_config.h:1053:1: warning: "HAVE_WCSCOLL"
> redefined
> In file included from /Library/Frameworks/Python.framework/Versions/
> 2.6/include/python2.6/Python.h:8,
>                 from pymemcompat.h:10,
>                 from _mysql.c:29:
> /Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/
> pyconfig.h:808:1: warning: this is the location of the previous
> definition
> error: command 'gcc-4.0' failed with exit status 1
> --

Strange. Seems that the package is trying to use gcc-4.0 and the
MacOSX10.4 SDK. The default version of gcc on Snow Leopard is 4.2, and
XCode only comes with the SDKs for the previous two versions of OS X.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IOError and Try Again to loop the loop.

2010-07-11 Thread The Danny Bos
Thanks gang,
I'm gonna paste what I've put together, doesn't seem right. Am I way
off?

Here's my code.
 - It goes through a table Item
 - Matches that Item ID to an API call
 - Grabs the data, saves it and creates the thumbnail
 - It dies due to Timeouts and Other baloney, all silly, nothing code
based.

items = Item.objects.all().filter(cover='').order_by('-reference_id')
for item in items:
url = "http://someaddress.org/books/?issue=%s"; % item.reference_id

url_array = []
url_open = urllib.urlopen(url)
url_read = url_open.read().decode('utf-8')

try:
url_data = simplejson.loads(url_read)
url_array.append(url_data)

for detail in url_array:
if detail['artworkUrl']:
cover_url = detail['artworkUrl'].replace(' 
','%20')
cover_open = urllib.urlretrieve(cover_url)
cover_name = os.path.split(cover_url)[1]

item.cover.save(cover_name, 
File(open(cover_open[0])),
save=True)## Create and save Thumbnail

print "Cover - %s: %s" % (item.number, url)
else:
print "Missing - %s: %s" % (item.number, url)

except ValueError:
print "Error Processing record: %s: %s" % (item.reference_id, 
url)
pass
except IOError:
print "IOError; Retrying..."
pass

print "Done"



On Jul 12, 12:33 pm, MRAB  wrote:
> The Danny Bos wrote:
> > Heya,
>
> > I'm running a py script that simply grabs an image, creates a
> > thumbnail and uploads it to s3. I'm simply logging into ssh and
> > running the script through Terminal. It works fine, but gives me an
> > IOError every now and then.
>
> > I was wondering if I can catch this error and just get the script to
> > start again?
> > I mean, in Terminal it dies anyway, so I have to start it again by
> > hand, which is a pain as it dies so sporadically. Can I automate this
> > error, catch it and just get it to restart the loop?
>
> > Thanks for your time and energy,
>
> Exceptions can be caught. You could do something like this:
>
>      while True:
>          try:
>              do_something()
>              break
>          except IOError:
>              pass

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


Re: Errno 9] Bad file descriptor

2010-07-11 Thread Steven D'Aprano
On Sun, 11 Jul 2010 17:48:40 -0700, joblack wrote:

> I get sometimes a
> 
> Errno 9 Bad file descriptor
> 
> the code is too long to show it here 

You can at least show the actual line that fails. Are you trying to open 
a file, a named socket, a pipe or a device?


> but what are the circumstances this
> could happen? A web search showed nothing.

The first two google hits for "bad file descriptor" seem pretty relevant 
to me:

http://linux.sys-con.com/node/1053821
http://lists.freebsd.org/pipermail/freebsd-questions/2003-June/009583.html


> I have especially the feeling Python 2.6 has some problems with Unicode
> ... and might not find the file. Is that possible?

Possible, but you should get 

Errno 2 No such file or directory 

not bad file descriptor.

If you're trying to open a file, you have a broken file system and need 
to run fsck or equivalent. If it's a pipe or socket or something, you 
need to tell us what it is.



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


Re: Easy questions from a python beginner

2010-07-11 Thread Alf P. Steinbach /Usenet

* MRAB, on 12.07.2010 04:09:

Alf P. Steinbach /Usenet wrote:

* MRAB, on 12.07.2010 00:37:

Alf P. Steinbach /Usenet wrote:

* Stephen Hansen, on 11.07.2010 21:00:

On 7/11/10 11:45 AM, wheres pythonmonks wrote:

Follow-up:
Is there a way to define compile-time constants in python and have
the
bytecode compiler optimize away expressions like:

if is_my_extra_debugging_on: print ...

when "is_my_extra_debugging" is set to false? I'd like to pay no
run-time penalty for such code when extra_debugging is disabled.


Any code wrapped in a __debug__ guard is utterly ommitted if you run
Python with the -O option. That, and asserts go away.


On #2: My point regarding the impossibility of writing the swap
function for ints is to explicitly understand that this isn't
possible, so as not to look for solutions along those lines when
trying to write python code.


Its impossible because Python's calling and namespace semantics simply
don't work like that. There's no references in the traditional sense,
because there's no variables-- boxes that you put values in. There's
just concrete objects. Objects are passed into the function and given
new names; that those objects have names in the enclosing scope is
something you don't know, can't access, and can't manipulate.. even
the
objects don't know what names they happen to be called.

Check out http://effbot.org/zone/call-by-object.htm


Oh, I wouldn't give that advice. It's meaningless mumbo-jumbo. Python
works like Java in this respect, that's all; neither Java nor Python
support 'swap'.

Of course there are variables, that's why the docs call them variables.


In Java a variable is declared and exists even before the first
assignment to it. In Python a 'variable' isn't declared and won't exist
until the first 'assignment' to it.


That is a misconception.

In Python a variable is declared by having an assignment to it, which
for a local variable may be anywhere within a routine.

If such a variable is used before it's been assigned to, then you get
an uninitialized variable exception. Clearly the variable must exist
in order for the exception to refer to it (not to mention the
exception occurring at all).

def foo():
print( blah )
blah = "this is both an assignment and a declaration causing it to exist"

foo()

Clearly when the exception is raised, referring to the variable, the
variable exists.

Contrary to your statement that is before the assignment.

However, as stated up-thread, I do not expect facts, logic or general
reasoning to have any effect whatsoever on such hard-core religious
beliefs. And I do not care whether I convince you or not. But I *do
not* want the religious subset of the community to succeed too much in
propagating nonsense idiot beliefs to newbies -- hence the concrete
example that any newbie can try.


How about this:

 >>> def foo():
print("Before:", locals())
x = 0
print("After:", locals())


 >>> foo()
Before: {}
After: {'x': 0}


How about it?

Note that you get the same result if you do

x = "blah"
def foo():
# print( x )  # Causes uninitialized variable exception here
print( "Before:", locals() )
x = 0
print( "After:", locals() )

However, if you remove the local assignment to x, then the out-commented print 
statement will no longer cause an exception, it will then refer to the global.


The reason that it does throw an exception when you do have the local 
assignment, is that the local x exists at that point. If it didn't exist it 
could not have any effect. Things that don't exist generally have no effect, 
except in the minds of the religious, like angels and so on.


On the basis of what locals() reports it should be OK to refer to the global x 
as above. Judging by locals(), there's no local x that could get in the way. But 
since it is not OK to refer to the global x, the result of locals() has nothing 
to do with that: it doesn't tell you about the local x  --  and no, the Python 
interpreter does not look forward in time to see that it will appear.


In passing, I should perhaps have told you up front, your argument has nothing 
substantial to do with the article you originally responded to, about the 
semantics of variables. Your argument is the assertion that different languages 
can't have similar or identical semantics for some feature. That's nonsense in 
itself, plus, as you've seen, the difference that you focused on is not there, 
and, third, what you do maintain is not there, doesn't exist, has a real effect.



Cheers & hth.,

- Alf

--
blog at http://alfps.wordpress.com>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Naming Conventions, Where's the Convention Waldo?

2010-07-11 Thread Steven D'Aprano
On Mon, 12 Jul 2010 02:40:07 +, Steven D'Aprano wrote:

> On Mon, 12 Jul 2010 01:31:14 +0100, Mark Lawrence wrote:
> 
>> Well said Steven, or is it Stephen, or Stephan, or Stefen, or what?
> 
> For some reason, when I answer the phone and say "Hello, Steven
> speaking?" I often get called Peter.

Er, without the question mark.

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


Re: Naming Conventions, Where's the Convention Waldo?

2010-07-11 Thread Steven D'Aprano
On Mon, 12 Jul 2010 01:31:14 +0100, Mark Lawrence wrote:

> Well said Steven, or is it Stephen, or Stephan, or Stefen, or what?

For some reason, when I answer the phone and say "Hello, Steven 
speaking?" I often get called Peter.


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


Re: Easy questions from a python beginner

2010-07-11 Thread Steven D'Aprano
On Mon, 12 Jul 2010 03:12:10 +0200, Alf P. Steinbach /Usenet wrote:

> * MRAB, on 12.07.2010 00:37:
[...]
>> In Java a variable is declared and exists even before the first
>> assignment to it. In Python a 'variable' isn't declared and won't exist
>> until the first 'assignment' to it.
> 
> That is a misconception.
> 
> In Python a variable is declared by having an assignment to it, which
> for a local variable may be anywhere within a routine.

Oh, I'm going to regret being sucked into this... 

In *CPython*, but not necessarily other implementations, variables which 
are local to a function are not kept in a dictionary-based namespace, but 
in slots in the code object (not to be confused with __slots__ used for 
classes). Python has STORE_FAST and LOAD_FAST byte-codes for accessing 
locals.

This is intended as a speed, and possibly memory, optimization. I don't 
believe this is a requirement though, so implementations may not do this.

It is true that the slot is created at compile time, and in *that sense*, 
local variables exist before they are bound. I'm not entirely convinced 
that this is the only sense that matters, but never mind. The error 
message given exposes this to the user:

>>> def f():
... print x
... x = 1
...
>>> f()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in f
UnboundLocalError: local variable 'x' referenced before assignment


If you try this with a global, you get this:

>>> def f():
... global x
... print x
...
>>> f()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in f
NameError: global name 'x' is not defined

In this case, there's no doubt that global variable "x" doesn't exist at 
all -- there is no key "x" in the global namespace.


It seems to me that "a slot to hold the variable is created for local 
variables" is an implementation detail, not a language feature. CPython 
could easily hide the difference by changing the exception from 
UnboundLocalError to:

NameError: local name 'x' does not exist

and nobody would be any wiser. (Well, perhaps people who catch 
UnboundLocalError, but why would you do that?)

I also note that UnboundLocalError is a subclass of NameError, so 
"variable exists but is not bound" is considered to be a special case of 
"variable doesn't exist" rather than a completely independent case. In 
that sense, I think I'm on solid ground to say that in Python variables 
don't exist until they are bound to a value, and leave it to pedants like 
you and I to mention that for CPython local variables have space reserved 
for them by the compiler before they are bound.



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


Re: IOError and Try Again to loop the loop.

2010-07-11 Thread Alex Hall
It seems like seeing the code, or at least the bit in question, would
be easier, but what about:

for img in range(0, len(imagesToUpload:))
 try:
  #do the thumbnail / upload thing on images[i]
 exceptIOError:
  i=0

This will duplicate a lot of the images already processed, but you
said you are just restarting the script anyway. If you are in a while
loop, just move the processing to the for loop and use the while to
add all images to be processed to a list.

On 7/11/10, The Danny Bos  wrote:
> Heya,
>
> I'm running a py script that simply grabs an image, creates a
> thumbnail and uploads it to s3. I'm simply logging into ssh and
> running the script through Terminal. It works fine, but gives me an
> IOError every now and then.
>
> I was wondering if I can catch this error and just get the script to
> start again?
> I mean, in Terminal it dies anyway, so I have to start it again by
> hand, which is a pain as it dies so sporadically. Can I automate this
> error, catch it and just get it to restart the loop?
>
> Thanks for your time and energy,
>
> Danny
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IOError and Try Again to loop the loop.

2010-07-11 Thread MRAB

The Danny Bos wrote:

Heya,

I'm running a py script that simply grabs an image, creates a
thumbnail and uploads it to s3. I'm simply logging into ssh and
running the script through Terminal. It works fine, but gives me an
IOError every now and then.

I was wondering if I can catch this error and just get the script to
start again?
I mean, in Terminal it dies anyway, so I have to start it again by
hand, which is a pain as it dies so sporadically. Can I automate this
error, catch it and just get it to restart the loop?

Thanks for your time and energy,


Exceptions can be caught. You could do something like this:

while True:
try:
do_something()
break
except IOError:
pass

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


Re: IOError and Try Again to loop the loop.

2010-07-11 Thread Chris Rebert
On Sun, Jul 11, 2010 at 7:15 PM, The Danny Bos  wrote:
> Heya,
>
> I'm running a py script that simply grabs an image, creates a
> thumbnail and uploads it to s3. I'm simply logging into ssh and
> running the script through Terminal. It works fine, but gives me an
> IOError every now and then.
>
> I was wondering if I can catch this error and just get the script to
> start again?
> I mean, in Terminal it dies anyway, so I have to start it again by
> hand, which is a pain as it dies so sporadically. Can I automate this
> error, catch it and just get it to restart the loop?

Of course. Use try-except;
http://docs.python.org/tutorial/errors.html#handling-exceptions
Here's one way to do it:

for image in images:#or whatever the actual loop is
# whatever
while True:
try:
part_that_may_raise_IOError()
except IOError:
print("IOError; Retrying...")
else:
break
# whatever other stuff

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


Re: Easy questions from a python beginner

2010-07-11 Thread Alf P. Steinbach /Usenet

* Stephen Hansen, on 12.07.2010 04:02:

On 7/11/10 6:12 PM, Alf P. Steinbach /Usenet wrote:

However, as stated up-thread, I do not expect facts, logic or general
reasoning to have any effect whatsoever on such hard-core religious
beliefs.


Grow up, and/or get a grip, and/or get over yourself.

Everyone who disagreed with you, disagreed with you with arguments,
logic, facts, and reasoning. You disputed those facts, disagreed with
the conclusions, but for you to then just dismiss people who don't agree
with you as merely "religious", is childish.

Exactly why I think you're wrong -- you're free to go re-read, I stand
by my statements in this thread, and the others. The same arguments
apply. Its not a religion, dear; my conclusions are not a matter of faith.

That's all I have to say on this subject; the conversation has been had,
at length (repeatedly).

I swear, I'm just going to filter you and Rick out to /dev/null today
and leave it at that at this rate. I'm getting worn out of these kinds
of responses.


Well, the above is flaming, which I predicted.

The alleged facts etc. you're referring are just that, alleged, by you.

In contrast, in debates among non-religious folks facts are /presented/, like 
I've done in this thread, e.g. concrete code, instead of like you alleging that 
facts have been presented, hinting about things, and so on  --  it's pathetic.



Cheers & hth.,

- Alf

--
blog at http://alfps.wordpress.com>
--
http://mail.python.org/mailman/listinfo/python-list


IOError and Try Again to loop the loop.

2010-07-11 Thread The Danny Bos
Heya,

I'm running a py script that simply grabs an image, creates a
thumbnail and uploads it to s3. I'm simply logging into ssh and
running the script through Terminal. It works fine, but gives me an
IOError every now and then.

I was wondering if I can catch this error and just get the script to
start again?
I mean, in Terminal it dies anyway, so I have to start it again by
hand, which is a pain as it dies so sporadically. Can I automate this
error, catch it and just get it to restart the loop?

Thanks for your time and energy,

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


Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

2010-07-11 Thread Steven D'Aprano
On Sun, 11 Jul 2010 17:35:18 -0700, rantingrick wrote:

> On Jul 11, 7:02 pm, Steven D'Aprano  cybersource.com.au> wrote:
> 
>> Come back when you have profiled your code and can prove that the cost
>> of building empty tuples is an actual bottleneck.
> 
> Did you even read this thread, i mean from head to tail.

Yes I did.

> I NEVER said
> building EMPTY tuples was the cause of my rant.

The cause of your rant appears to be that you have nothing better to do 
with your time. But the *excuse* for your rant was that you had to 
replace:

choiceIdx1 = None

with:

choiceIdx1 = ()

and followed with:

Seems kinda dumb to build a tuple just so a conditional 
wont blow chunks!

and

My bin packer could potentially compute millions of parts. 
I do not want to waste valuable processor cycles building 
numerous TUPLES just for the sake of a conditional 
"condition"!

[emphasis added]


> My complaint (an oddly
> enough the title of this thread!) concerns the fact that Python treats 0
> as False and every integer above and below 0 as True. Which is another
> example of how *some* aspects of Python support bad coding styles.

Yes, Python does support bad coding styles. The treatment of 0 as a false 
value is not one of them though.



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


Re: Easy questions from a python beginner

2010-07-11 Thread MRAB

Alf P. Steinbach /Usenet wrote:

* MRAB, on 12.07.2010 00:37:

Alf P. Steinbach /Usenet wrote:

* Stephen Hansen, on 11.07.2010 21:00:

On 7/11/10 11:45 AM, wheres pythonmonks wrote:

Follow-up:
Is there a way to define compile-time constants in python and have the
bytecode compiler optimize away expressions like:

if is_my_extra_debugging_on: print ...

when "is_my_extra_debugging" is set to false? I'd like to pay no
run-time penalty for such code when extra_debugging is disabled.


Any code wrapped in a __debug__ guard is utterly ommitted if you run
Python with the -O option. That, and asserts go away.


On #2: My point regarding the impossibility of writing the swap
function for ints is to explicitly understand that this isn't
possible, so as not to look for solutions along those lines when
trying to write python code.


Its impossible because Python's calling and namespace semantics simply
don't work like that. There's no references in the traditional sense,
because there's no variables-- boxes that you put values in. There's
just concrete objects. Objects are passed into the function and given
new names; that those objects have names in the enclosing scope is
something you don't know, can't access, and can't manipulate.. even the
objects don't know what names they happen to be called.

Check out http://effbot.org/zone/call-by-object.htm


Oh, I wouldn't give that advice. It's meaningless mumbo-jumbo. Python
works like Java in this respect, that's all; neither Java nor Python
support 'swap'.

Of course there are variables, that's why the docs call them variables.


In Java a variable is declared and exists even before the first
assignment to it. In Python a 'variable' isn't declared and won't exist
until the first 'assignment' to it.


That is a misconception.

In Python a variable is declared by having an assignment to it, which 
for a local variable may be anywhere within a routine.


If such a variable is used before it's been assigned to, then you get an 
uninitialized variable exception. Clearly the variable must exist in 
order for the exception to refer to it (not to mention the exception 
occurring at all).


  def foo():
  print( blah )
  blah = "this is both an assignment and a declaration causing it to 
exist"


  foo()

Clearly when the exception is raised, referring to the variable, the 
variable exists.


Contrary to your statement that is before the assignment.

However, as stated up-thread, I do not expect facts, logic or general 
reasoning to have any effect whatsoever on such hard-core religious 
beliefs. And I do not care whether I convince you or not. But I *do not* 
want the religious subset of the community to succeed too much in 
propagating nonsense idiot beliefs to newbies  --  hence the concrete 
example that any newbie can try.



How about this:

>>> def foo():
print("Before:", locals())
x = 0
print("After:", locals())


>>> foo()
Before: {}
After: {'x': 0}
--
http://mail.python.org/mailman/listinfo/python-list


Re: Easy questions from a python beginner

2010-07-11 Thread Stephen Hansen
On 7/11/10 6:12 PM, Alf P. Steinbach /Usenet wrote:
> However, as stated up-thread, I do not expect facts, logic or general
> reasoning to have any effect whatsoever on such hard-core religious
> beliefs. 

Grow up, and/or get a grip, and/or get over yourself.

Everyone who disagreed with you, disagreed with you with arguments,
logic, facts, and reasoning. You disputed those facts, disagreed with
the conclusions, but for you to then just dismiss people who don't agree
with you as merely "religious", is childish.

Exactly why I think you're wrong -- you're free to go re-read, I stand
by my statements in this thread, and the others. The same arguments
apply. Its not a religion, dear; my conclusions are not a matter of faith.

That's all I have to say on this subject; the conversation has been had,
at length (repeatedly).

I swear, I'm just going to filter you and Rick out to /dev/null today
and leave it at that at this rate. I'm getting worn out of these kinds
of responses.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread Stephen Hansen
On 7/11/10 6:10 PM, rantingrick wrote:
> On Jul 11, 7:31 pm, Stephen Hansen  wrote:
> 
> You said about macs...
>> Copying a file without the resource fork on a mac, *can* result in
>> essential data being lost (This is less common then it used to be). As
>> simple a task as chown/chmod for posix systems to take ownership of a
>> file and make it only readable by you is actually a *deeply* complex
>> task with the win32api.
> 
> And again...
>> That's not even getting into the nitty-gritty details, like how Mac's
>> are *usually* case-insensitive, windows is always, linux is almost
>> always not, and yet some power users go out of their way to enable
>> case-sensitivity on mac filesystems (which has a tendency to break all
>> kinds of things).
> 
> And again...
>> Oh, and a LOT of the filesystem-details and how you could go around
>> handling them on a mac is *very* dependant on just what version of OSX
>> you have. It changes a lot.
> 
> Well i've never used a mac and now i won't even bother for sure! But
> if you want to maintain the macfman code base feel free.

I like how you tried to cut out my commentary on Windows and its
difficulties and peculiarities, but you accidentally included it anyways
-- hint: read more then the first line of a paragraph.

My point stands.

And I take your non actually responding to my actual point as a
concession to it. With that, I'm signing off of this conversation.

Tah.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

2010-07-11 Thread Brendon Wickham
"i had once considered you one of the foremost intelligent minds
within this group. However, after your display within this thread i am
beginning to doubt my original beliefs of you."

"Oh ... grow a spine already, really. I can't help but thinking of the
spineless Robert Ford every time you open your mouth"

@rantingrick : these comments among others fail to meet the standard
of engagement expected of, and traditional to, this list. Take a
breath, get some sleep and come back with a level head and a civil
tongue. If you have any valid point to make at all, your attitude so
far has failed to make it credible, and nor will it enable you to
enlist supporters.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

2010-07-11 Thread Stephen Hansen
On 7/11/10 5:51 PM, rantingrick wrote:
> On Jul 11, 7:23 pm, Steven D'Aprano  cybersource.com.au> wrote:
>> On Sun, 11 Jul 2010 16:22:41 -0700, rantingrick wrote:
>>> On Jul 11, 1:19 pm, Mark Dickinson  wrote:
>>
 Okay.  What fix do you propose?  Would your fix maintain the identity
 "0 == False"?
>>
>>> No because all integers should bool True. An integer is a value that IS
>>> NOT empty
>>
>> Integers aren't containers, the concept of "empty" or "full" doesn't
>> apply to them.
> 
> And again you failed to follow along with the thread so you have no
> idea where my statements is projected from. Of course integers are NOT
> containers in the way a list or dict is a container! My remark was a
> rebuff of comments made by Stephen earlier.

I forgot to reply to that; an integer is certainly not empty.

But 0 is nothing.

Its not empty vs full. Its nothing vs something that determines if
something is considered true-ish or not.

>> Nevertheless, what is done is done, and now you have to deal with it.
>> Just wishing that it was never done is not dealing with backwards
>> compatibility, and breaking existing code is not an acceptable option.
> 
> Yea and if Guido would have taking your defeatist attitude we'd all be
> using braces for scope!

Guido made a new language.

You should go do that.

Feel free to define it however you want.

In Python, the meaning of "truth" goes back a very, very, very long way.
It isn't going to change. Every once in awhile people hate it. For
awhile after True/False were introduced, some people wanted to go modify
things to a boolean strictness. But in the end, its all pointless.

This is just how it works. Its not going to change. It would break
thousands and thousands of lines of code. There's not going to be
another major breakage for, oh, maybe ten years. Or twenty. If ever.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy questions from a python beginner

2010-07-11 Thread Alf P. Steinbach /Usenet

* MRAB, on 12.07.2010 00:37:

Alf P. Steinbach /Usenet wrote:

* Stephen Hansen, on 11.07.2010 21:00:

On 7/11/10 11:45 AM, wheres pythonmonks wrote:

Follow-up:
Is there a way to define compile-time constants in python and have the
bytecode compiler optimize away expressions like:

if is_my_extra_debugging_on: print ...

when "is_my_extra_debugging" is set to false? I'd like to pay no
run-time penalty for such code when extra_debugging is disabled.


Any code wrapped in a __debug__ guard is utterly ommitted if you run
Python with the -O option. That, and asserts go away.


On #2: My point regarding the impossibility of writing the swap
function for ints is to explicitly understand that this isn't
possible, so as not to look for solutions along those lines when
trying to write python code.


Its impossible because Python's calling and namespace semantics simply
don't work like that. There's no references in the traditional sense,
because there's no variables-- boxes that you put values in. There's
just concrete objects. Objects are passed into the function and given
new names; that those objects have names in the enclosing scope is
something you don't know, can't access, and can't manipulate.. even the
objects don't know what names they happen to be called.

Check out http://effbot.org/zone/call-by-object.htm


Oh, I wouldn't give that advice. It's meaningless mumbo-jumbo. Python
works like Java in this respect, that's all; neither Java nor Python
support 'swap'.

Of course there are variables, that's why the docs call them variables.


In Java a variable is declared and exists even before the first
assignment to it. In Python a 'variable' isn't declared and won't exist
until the first 'assignment' to it.


That is a misconception.

In Python a variable is declared by having an assignment to it, which for a 
local variable may be anywhere within a routine.


If such a variable is used before it's been assigned to, then you get an 
uninitialized variable exception. Clearly the variable must exist in order for 
the exception to refer to it (not to mention the exception occurring at all).


  def foo():
  print( blah )
  blah = "this is both an assignment and a declaration causing it to exist"

  foo()

Clearly when the exception is raised, referring to the variable, the variable 
exists.


Contrary to your statement that is before the assignment.

However, as stated up-thread, I do not expect facts, logic or general reasoning 
to have any effect whatsoever on such hard-core religious beliefs. And I do not 
care whether I convince you or not. But I *do not* want the religious subset of 
the community to succeed too much in propagating nonsense idiot beliefs to 
newbies  --  hence the concrete example that any newbie can try.



Cheers & hth.,

- Alf

--
blog at http://alfps.wordpress.com>
--
http://mail.python.org/mailman/listinfo/python-list


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread rantingrick
On Jul 11, 7:31 pm, Stephen Hansen  wrote:

You said about macs...
> Copying a file without the resource fork on a mac, *can* result in
> essential data being lost (This is less common then it used to be). As
> simple a task as chown/chmod for posix systems to take ownership of a
> file and make it only readable by you is actually a *deeply* complex
> task with the win32api.

And again...
> That's not even getting into the nitty-gritty details, like how Mac's
> are *usually* case-insensitive, windows is always, linux is almost
> always not, and yet some power users go out of their way to enable
> case-sensitivity on mac filesystems (which has a tendency to break all
> kinds of things).

And again...
> Oh, and a LOT of the filesystem-details and how you could go around
> handling them on a mac is *very* dependant on just what version of OSX
> you have. It changes a lot.

Well i've never used a mac and now i won't even bother for sure! But
if you want to maintain the macfman code base feel free.

> Selective quoting to make it sound like I'm agreeing in some way with
> you = jerkoff move.

*fakes throwing stick*
*dog runs to get stick but stick not there*

Who's smarter ;-)

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


Re: Why doesn't python's list append() method return the list itself?

2010-07-11 Thread Raymond Hettinger
On Jul 11, 8:59 am, dhruvbird  wrote:
> Why doesn't python's list append() method return the list itself? For
> that matter, even the reverse() and sort() methods?

Because Guido thinks that having those methods return None is the best
way to communicate that the underlying object has been mutated in-
place.

Some other languages do it differently, but this is Guido's language,
so we do it his way.


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


Problems running VirtualEnv under Windows.

2010-07-11 Thread ashconnor
Hello,

After reading 'Practical Django Projects' I decided that I want to
implement the VirtualEnv tip suggested in order to properly segregate
code/modules in different projects. I am however having problems with
my django installations not using site-packages within the virtualenv
but rather attempting to use site-packages in the default python
installation directory.

Recreating the problem:

1) Install Python 2.7 via the Windows installer. Add C:/Python27;C:/
Python27/Scripts to Windows PATH.
2) Install setuptools-0.6c11-py2.7.egg via the Windows installer.
3) Install VirtualEnv through `pip install virtualenv`
4) Create an VirtualEnv via `virtualenv --no-site-packages MyEnvName`
5) Activate VirtualEnv via `../MyEnvName/Scripts/activate.bat`
6) Install django via `pip install django`
7) Run django-admin.py startproject ProjectName
8) Error results stating django.core module does not exist.

NB: This error will not occur if django is installed in your root
directory.
NB2: Running the Python interpreter in active VirtualEnv to print the
sys.path shows the correct paths. Which has just futher added to my
confusion.

I'd appreciate any insight or troubleshooting assistance.

Thanks

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


Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

2010-07-11 Thread rantingrick
On Jul 11, 7:23 pm, Steven D'Aprano  wrote:
> On Sun, 11 Jul 2010 16:22:41 -0700, rantingrick wrote:
> > On Jul 11, 1:19 pm, Mark Dickinson  wrote:
>
> >> Okay.  What fix do you propose?  Would your fix maintain the identity
> >> "0 == False"?
>
> > No because all integers should bool True. An integer is a value that IS
> > NOT empty
>
> Integers aren't containers, the concept of "empty" or "full" doesn't
> apply to them.

And again you failed to follow along with the thread so you have no
idea where my statements is projected from. Of course integers are NOT
containers in the way a list or dict is a container! My remark was a
rebuff of comments made by Stephen earlier.

> > and IS NOT None.
>
> By this definition, the string "rantingrick hasn't thought this through"
> is an integer. It's not empty, and not None, so therefore an integer by
> your definition.

Again you show lack of reading and comprehension skills. The fact that
an integer IS NOT None does not mean this is the only definition of an
integer. And any blabbing otherwise is just complete nonsensical crap.
If you think you're going to fly in here and dis-credit me that easily
you'd better pack a lunch next time! I gots my think'in cap on today
fella!

> > We would't deal with backwards compatibility as this notion of bool(1)
> > == True and bool(0) == False if backwards way of thinking. Sure it saves
> > a few keystrokes but in the end only serves to obfuscate the code and
> > promote bad programming styles. WE SHOULD NEVER BE USING 1 IN PLACE OF
> > True AND 0 IN PLACE OF False!
>
> Nevertheless, what is done is done, and now you have to deal with it.
> Just wishing that it was never done is not dealing with backwards
> compatibility, and breaking existing code is not an acceptable option.

Yea and if Guido would have taking your defeatist attitude we'd all be
using braces for scope!

You know D'Aprano, i had once considered you one of the foremost
intelligent minds within this group. However, after your display
within this thread i am beginning to doubt my original beliefs of you.
Hopefully you're just having an "off" day?
-- 
http://mail.python.org/mailman/listinfo/python-list


Errno 9] Bad file descriptor

2010-07-11 Thread joblack
I get sometimes a

Errno 9 Bad file descriptor

the code is too long to show it here but what are the circumstances
this could happen? A web search showed nothing.

I have especially the feeling Python 2.6 has some problems with
Unicode ... and might not find the file. Is that possible?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

2010-07-11 Thread rantingrick
On Jul 11, 7:18 pm, Mark Lawrence  wrote:

> +1

Oh mark grow a spine already, really. I can't help but thinking of the
spineless Robert Ford every time you open your mouth.

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


Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

2010-07-11 Thread rantingrick
On Jul 11, 7:02 pm, Steven D'Aprano  wrote:

> Come back when you have profiled your code and
> can prove that the cost of building empty tuples is an actual bottleneck.

Did you even read this thread, i mean from head to tail. I NEVER said
building EMPTY tuples was the cause of my rant. My complaint (an oddly
enough the title of this thread!) concerns the fact that Python treats
0 as False and every integer above and below 0 as True. Which is
another example of how *some* aspects of Python support bad coding
styles.

The only reason i used the tuple was so that my conditional logic
worked as expected.

*Stephen* offered a solution in the form of using tuples within the
conditional expression. I countered his solution by showing that
creating tuples in a conditional expression is slower that testing for
bool-inity.

*Steven*, Please read the thread completely before making off hand
comments else you could make a complete fool of yourself!

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


Re: Why doesn't python's list append() method return the list itself?

2010-07-11 Thread News123
dhruvbird wrote:

> 
> On a side note, is there any other way to append to a list using
> slices (apart from the one below):
> x[len(x):len(x)] = [item to append]


dy you mean
x.extend([1,2,3])

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


Re: Naming Conventions, Where's the Convention Waldo?

2010-07-11 Thread Mark Lawrence

On 12/07/2010 01:06, Steven D'Aprano wrote:

On Sun, 11 Jul 2010 00:26:36 -0700, rantingrick wrote:


Another source of asininity seems to be the naming conventions of the
Python language proper! True/False start with an upper case and i
applaud this. However str, list, tuple, int, float --need i go on...?--
start with lowercase.

Q: Well what the hell is your problem Rick. Who cares right?

WRONG, I tell you what my problem is. Now i cannot "wisely" use
variables like...

str="this is a string"
list = [1,2,3]
def make_random_objs(range=10)
def show_message(str)
int = 12



Yes. So what? You can't wisely use variables like:

True = "rantingrick is an obnoxious loudmouth"

+1 QOTW

None = "the problem he is describing"

Nor can you wisely use variables like:

len = len("something")
chr = chr(48)


[...]

Just thoughts.


But not deep thoughts.


Well said Steven, or is it Stephen, or Stephan, or Stefen, or what?
Kindest regards.

Mark Lawrence.


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


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread Stephen Hansen
On 7/11/10 5:01 PM, rantingrick wrote:
> On Jul 11, 11:57 am, Stephen Hansen  wrote:
>> On 7/11/10 9:31 AM, Thomas Jollans wrote:
>>> trying to
>>> support both UNIX and Windows is NOT a good idea.
>>
>> And you can't lump the Mac in with "UNIX" here, even though it really is
>> UNIX at the foundation, because there's some very fundamental
>> differences between HFS+ (and some other details that are higher level)
>> and more traditional unix FS's. Not to mention that the Mac FS situation
>> is slightly schitzo since it has two very different ways at looking and
>> treating the files, the posix way and the Foundation way... and users
>> think more in terms of the latter, usually. At least less sophisticated
>> users.
> 
> 
> Sure you can! Have you ever heard of a *rare* module by the name of
> "os"? Yes i know *nobody* uses it but it works nonetheless!

Uh, "os" is beyond inadequate. Even shutil is severely lacking. For the
most basic operations, Python's provided tools basically work only in
very simple cases -- but only those simple cases -- and a file manager
would be an utter failure if it had those limitations.

See the big red box on top of the docs:
http://docs.python.org/library/shutil.html

Copying a file without the resource fork on a mac, *can* result in
essential data being lost (This is less common then it used to be). As
simple a task as chown/chmod for posix systems to take ownership of a
file and make it only readable by you is actually a *deeply* complex
task with the win32api. Check out
http://mail.python.org/pipermail/python-win32/2004-July/002111.html for
just an example of what it /looks/ like.

That's not even getting into the nitty-gritty details, like how Mac's
are *usually* case-insensitive, windows is always, linux is almost
always not, and yet some power users go out of their way to enable
case-sensitivity on mac filesystems (which has a tendency to break all
kinds of things).

Oh, and a LOT of the filesystem-details and how you could go around
handling them on a mac is *very* dependant on just what version of OSX
you have. It changes a lot.

>> You can't do a cross-platform file manager without either doing a huge
>> amount of work exposing each platform separately-- essentially getting
>> separate codebases for each-- or doing a least common denominator
>> situation, at which point I boggle: why the hell did you bother to begin
>> with? Even Finder is better then that, let alone windows' Explorer.
> 
> Nothing is worse than InternetExploder\Exploder, nothing! And whats
> wrong with seperate code bases, it's three modules and a startup
> script...
> 
> if sys.platform == 'win32':
> import fm32
> elif sys.platform == 'darwin':
> import fmdarwin
> elif sys.platform == 'nix':
> import fmnix
> 
> We just recently had a discussion about CONDITIONALS Stephen have you
> forgotten already?

You underestimate the significance of the differences and how that would
impact the resulting user interface; have you actually implemented
anything which targeted the big three OS's and did non-trivial file
operations? I have: just dealing with permissions and network shares and
other details is actually a pain in the ass. And in the end, there's
plenty of Explorer/Finder replacements out there which do their job
splendidly. And I assume not everyone on linux loves nautilus and uses it :P


>> (*): I do not argue that a non-default file manager on an OS might be a
>> great thing.
> 
> Now you're talking!

Selective quoting to make it sound like I'm agreeing in some way with
you = jerkoff move.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't python's list append() method return the list itself?

2010-07-11 Thread Steven D'Aprano
On Sun, 11 Jul 2010 08:59:06 -0700, dhruvbird wrote:

> Why doesn't python's list append() method return the list itself? For
> that matter, even the reverse() and sort() methods? I found this link
> (http://code.google.com/edu/languages/google-python- class/lists.html)
> which suggests that this is done to make sure that the programmer
> understands that the list is being modified in place, but that rules out
> constructs like:
> ([1,2,3,4].reverse()+[[]]).reverse()

Yes. So what? Where's the problem?

List methods work in place. If you're annoyed now, that's *nothing* to 
the annoyance you'll feel if they returned the list and you did this:

alist = [1,2,3]
blist = alist.append(4)  # Make a new list with 4 appended.
assert alist == [1,2,3]


> I want to prepend an empty list to [1,2,3,4]. This is just a toy
> example, since I can always do that with [[]]+[1,2,3,4].

Or:

L = [[]]
L.extend([1,2,3,4])

Or:

L = [1,2,3,4]
L.insert(0, [])



Not everything needs to be a one-liner.


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


Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

2010-07-11 Thread Steven D'Aprano
On Sun, 11 Jul 2010 16:22:41 -0700, rantingrick wrote:

> On Jul 11, 1:19 pm, Mark Dickinson  wrote:
> 
>> Okay.  What fix do you propose?  Would your fix maintain the identity
>> "0 == False"?
> 
> No because all integers should bool True. An integer is a value that IS
> NOT empty 

Integers aren't containers, the concept of "empty" or "full" doesn't 
apply to them.

> and IS NOT None. 

By this definition, the string "rantingrick hasn't thought this through" 
is an integer. It's not empty, and not None, so therefore an integer by 
your definition.

Possibly the integer two-thirds of the way between 3 and 4.


> Therefore the only logical way to handle
> integer bool-ing is to say they are all True.

For some definition of "logical".


>> For bonus points, explain how you'd deal with any backwards
>> compatibility problems that your fix introduces.
> 
> We would't deal with backwards compatibility as this notion of bool(1)
> == True and bool(0) == False if backwards way of thinking. Sure it saves
> a few keystrokes but in the end only serves to obfuscate the code and
> promote bad programming styles. WE SHOULD NEVER BE USING 1 IN PLACE OF
> True AND 0 IN PLACE OF False!

Nevertheless, what is done is done, and now you have to deal with it. 
Just wishing that it was never done is not dealing with backwards 
compatibility, and breaking existing code is not an acceptable option.

So if your plan is to refuse to deal with existing code, I am very glad 
indeed that your plan will go absolutely nowhere.


>> Have you considered forking Python?  That may be the way forward here.
> 
>  I have considered this many times in the past and continue to
> consider it even today. 

Please do. I think that this will be the best thing for the Python 
community.



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


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread rantingrick
On Jul 11, 5:28 pm, Fuzzyman  wrote:

> But why hijack someone else's announcement to do that? Congratulations
> alone would have been great. However good your intentions your message
> came across as "but it would really have been better if you had been
> doing something else instead...".

Micheal i think you're just simply projecting some inner feelings on
to my post resulting in a complete mis-understanding. And i *did not*
say the project was useless, on the contrary i am very happy the OP
resurrected this lost script. I only suggested a similar project that
the OP *may* find to be interesting. Maybe not, but lets leave the
decision for the OP, Ok.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread Steven D'Aprano
On Sun, 11 Jul 2010 18:31:39 +0200, Thomas Jollans wrote:

> Cross platform file manager. Hmm. Does "cross platform" involve UNIX and
> something that isn't UNIX, say, Windows? Erm, no. No, no, no. It won't
> work. Well, it would work, but it wouldn't be any good. The UNIX and
> Windows concepts of "file system" are similar enough for most programs
> not to care too much, but for something like a file manager, that works
> intimately with the file system, trying to support both UNIX and Windows
> is NOT a good idea.

Try telling that to the KDE people.


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


Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

2010-07-11 Thread Mark Lawrence

On 12/07/2010 01:02, Steven D'Aprano wrote:

On Sat, 10 Jul 2010 23:50:05 -0700, rantingrick wrote:


You do realize that
Python must build a tuple for ever conditional that uses this semantic?
This is more bad, bad, bad than integer bool-ing! My bin packer could
potentially compute millions of parts. I do not want to waste valuable
processor cycles building numerous tuples just for the sake of a
conditional "condition"! This is bad coding style Stephen.


No, premature optimization is bad coding.

Building a tuple is extremely fast:

$ python -m timeit "x = ()"
100 loops, best of 3: 0.316 usec per loop
$ python -m timeit "x = False"
100 loops, best of 3: 0.36 usec per loop


Testing is fast too:

$ python -m timeit "x = (); 1 if x else 2"
100 loops, best of 3: 0.663 usec per loop
$ python -m timeit "x = False; 1 if x else 2"
100 loops, best of 3: 0.969 usec per loop


You've been around here long enough that you should know better. Stop
wasting your time, and ours, ranting over the enormous cost of things
that aren't costly at all. Come back when you have profiled your code and
can prove that the cost of building empty tuples is an actual bottleneck.



+1

Kindest regards.

Mark Lawrence


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


Re: Naming Conventions, Where's the Convention Waldo?

2010-07-11 Thread Steven D'Aprano
On Sun, 11 Jul 2010 00:26:36 -0700, rantingrick wrote:

> Another source of asininity seems to be the naming conventions of the
> Python language proper! True/False start with an upper case and i
> applaud this. However str, list, tuple, int, float --need i go on...?--
> start with lowercase.
> 
> Q: Well what the hell is your problem Rick. Who cares right?
> 
> WRONG, I tell you what my problem is. Now i cannot "wisely" use
> variables like...
> 
> str="this is a string"
> list = [1,2,3]
> def make_random_objs(range=10)
> def show_message(str)
> int = 12


Yes. So what? You can't wisely use variables like:

True = "rantingrick is an obnoxious loudmouth"
None = "the problem he is describing"

Nor can you wisely use variables like:

len = len("something")
chr = chr(48)


[...]
> Just thoughts.

But not deep thoughts.



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


Re: Naming Conventions, Where's the Convention Waldo?

2010-07-11 Thread Steven D'Aprano
On Sun, 11 Jul 2010 01:30:36 -0700, rantingrick wrote:

> On Jul 11, 3:03 am, "Günther Dietrich"  wrote:
> 
>> So, it is not a disadvantage that the functions you listed above are
>> named in this way. In the contrary, it is an advantage, as it keeps
>> newcomers from using stupid variable names.
> 
> "int" for an Integer is stupid?
> "list" for a List is stupid?
> "str" for a String is stupid?
> 
> What am i missing?

If you're going to use generic names, why type three or four letters when 
one will do?

i, j, k, m, n, p, q for ints.
L, a, b, x for lists
s, t, a, b for strings.

If you don't want to use generic names, then int, list, str are useless 
because they don't mean anything. You need something like:

count_of_widgets
list_of_widgets
description




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


Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

2010-07-11 Thread Steven D'Aprano
On Sat, 10 Jul 2010 23:50:05 -0700, rantingrick wrote:

> You do realize that
> Python must build a tuple for ever conditional that uses this semantic?
> This is more bad, bad, bad than integer bool-ing! My bin packer could
> potentially compute millions of parts. I do not want to waste valuable
> processor cycles building numerous tuples just for the sake of a
> conditional "condition"! This is bad coding style Stephen.

No, premature optimization is bad coding.

Building a tuple is extremely fast:

$ python -m timeit "x = ()"
100 loops, best of 3: 0.316 usec per loop
$ python -m timeit "x = False"
100 loops, best of 3: 0.36 usec per loop


Testing is fast too:

$ python -m timeit "x = (); 1 if x else 2"
100 loops, best of 3: 0.663 usec per loop
$ python -m timeit "x = False; 1 if x else 2"
100 loops, best of 3: 0.969 usec per loop


You've been around here long enough that you should know better. Stop 
wasting your time, and ours, ranting over the enormous cost of things 
that aren't costly at all. Come back when you have profiled your code and 
can prove that the cost of building empty tuples is an actual bottleneck.



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


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread rantingrick
On Jul 11, 11:57 am, Stephen Hansen  wrote:
> On 7/11/10 9:31 AM, Thomas Jollans wrote:
> > trying to
> > support both UNIX and Windows is NOT a good idea.
>
> And you can't lump the Mac in with "UNIX" here, even though it really is
> UNIX at the foundation, because there's some very fundamental
> differences between HFS+ (and some other details that are higher level)
> and more traditional unix FS's. Not to mention that the Mac FS situation
> is slightly schitzo since it has two very different ways at looking and
> treating the files, the posix way and the Foundation way... and users
> think more in terms of the latter, usually. At least less sophisticated
> users.


Sure you can! Have you ever heard of a *rare* module by the name of
"os"? Yes i know *nobody* uses it but it works nonetheless!

> You can't do a cross-platform file manager without either doing a huge
> amount of work exposing each platform separately-- essentially getting
> separate codebases for each-- or doing a least common denominator
> situation, at which point I boggle: why the hell did you bother to begin
> with? Even Finder is better then that, let alone windows' Explorer.

Nothing is worse than InternetExploder\Exploder, nothing! And whats
wrong with seperate code bases, it's three modules and a startup
script...

if sys.platform == 'win32':
import fm32
elif sys.platform == 'darwin':
import fmdarwin
elif sys.platform == 'nix':
import fmnix

We just recently had a discussion about CONDITIONALS Stephen have you
forgotten already?

> (*): I do not argue that a non-default file manager on an OS might be a
> great thing.

Now you're talking!

> (**): The drop stack is a little corner of the window that you can drag
> files onto. Then drag more files onto. Then drag more files onto. Then
> you can navigate to another part of the system, and drag files off of
> said stack, in a LIFO manner, moving them as a result of this action.

This drop stack sound interesting. I've always hated the cut paste as
you could not add to the cut buffer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

2010-07-11 Thread geremy condra
On Sun, Jul 11, 2010 at 7:22 PM, rantingrick  wrote:
> On Jul 11, 1:19 pm, Mark Dickinson  wrote:
>
>> Okay.  What fix do you propose?  Would your fix maintain the identity
>> "0 == False"?
>
> No because all integers should bool True. An integer is a value that
> IS NOT empty and IS NOT None. Therefore the only logical way to handle
> integer bool-ing is to say they are all True.
>
>> For bonus points, explain how you'd deal with any
>> backwards compatibility problems that your fix introduces.
>
> We would't deal with backwards compatibility as this notion of bool(1)
> == True and bool(0) == False if backwards way of thinking. Sure it
> saves a few keystrokes but in the end only serves to obfuscate the
> code and promote bad programming styles. WE SHOULD NEVER BE USING 1 IN
> PLACE OF True AND 0 IN PLACE OF False!
>
>> Have you considered forking Python?  That may be the way forward here.
>
>  I have considered this many times in the past and continue to
> consider it even today. I believe the Python language to be the best
> high level language ever created up to this point. I also believe GvR
> to be a true genius who has forged the path of all 21st century high
> level languages. However, like all new inventions eventually the
> bright shiny paint job starts to oxidize and expose the rotten and
> rusting core that has been slowly disintegrating behind the scenes all
> along.
>
>  GvR stood on the shoulders of giants to reach the plateau of elegant
> bliss that we know today as Python programming. As we all know
> perfection will never be achieved, only lusted after forever and ever.
> A perpetual game of cat and mouse. So maybe it is now time for the
> next genius (Rick?) to stand on Guido's shoulders and reach the next
> "cookie-jar-of-programming-enlightenment" one shelf higher than
> Guido's cookies where found.
>
>  Maybe it was fate that CPython 3000 would disturb so many folks as to
> create a question in their minds... A splinter lodged deep within the
> mind constantly tickling new never before thoughts to form... "Is
> Python all it can be?". A lustful yearning to fix the warts that have
> been ignored for far too long and were scarified at the alter of the
> simplistic development cycle.
>
>  But i think we are now at a crossroads people. We must forge the new
> path and resist the temptation to circle around the familiar roads
> endlessly. Heck *maybe* Guido himself is the architect of this change?
> Maybe he *purposely* sowed discontent in an effort to ignite (or
> reignite?) a passion for change within this community...?
>
> The black monolith is before us. We have reached a crossroads. In the
> balance hangs the future of high level programming languages. Will we
> understand what the portal is and take the leap of faith forward, or
> just bang some bones around like toddlers for another 10,000 years?
> Only time will tell...? Only time will tell...?

I literally laughed out loud as I read this. Go write some code, might
help connect you back to reality.

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


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread rantingrick
On Jul 11, 11:31 am, Thomas Jollans  wrote:
> On 07/11/2010 07:44 AM, rantingrick wrote:

> > Congratulations on this effort Luke. However you know what project i
> > would really like to see the community get around? ...dramatic pause
> > here... a cross platform Python file browser!
>
> Cross platform file manager. Hmm. Does "cross platform" involve UNIX and
> something that isn't UNIX, say, Windows?
> Erm, no. No, no, no. It won't work... trying to
> support both UNIX and Windows is NOT a good idea.

Why is that a bad idea, Python does it all the time? Many software so
it all the time. This sounds like more fear than anything.

If you attempt to be full-featured, keeping it in one
> code base, let alone in one user interface, is destined to be a
> nightmare and induce suicides.

Thats False!

> The above might have been very slightly exaggerated.

Thats True!

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


Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

2010-07-11 Thread rantingrick
On Jul 11, 1:19 pm, Mark Dickinson  wrote:

> Okay.  What fix do you propose?  Would your fix maintain the identity
> "0 == False"?

No because all integers should bool True. An integer is a value that
IS NOT empty and IS NOT None. Therefore the only logical way to handle
integer bool-ing is to say they are all True.

> For bonus points, explain how you'd deal with any
> backwards compatibility problems that your fix introduces.

We would't deal with backwards compatibility as this notion of bool(1)
== True and bool(0) == False if backwards way of thinking. Sure it
saves a few keystrokes but in the end only serves to obfuscate the
code and promote bad programming styles. WE SHOULD NEVER BE USING 1 IN
PLACE OF True AND 0 IN PLACE OF False!

> Have you considered forking Python?  That may be the way forward here.

 I have considered this many times in the past and continue to
consider it even today. I believe the Python language to be the best
high level language ever created up to this point. I also believe GvR
to be a true genius who has forged the path of all 21st century high
level languages. However, like all new inventions eventually the
bright shiny paint job starts to oxidize and expose the rotten and
rusting core that has been slowly disintegrating behind the scenes all
along.

 GvR stood on the shoulders of giants to reach the plateau of elegant
bliss that we know today as Python programming. As we all know
perfection will never be achieved, only lusted after forever and ever.
A perpetual game of cat and mouse. So maybe it is now time for the
next genius (Rick?) to stand on Guido's shoulders and reach the next
"cookie-jar-of-programming-enlightenment" one shelf higher than
Guido's cookies where found.

 Maybe it was fate that CPython 3000 would disturb so many folks as to
create a question in their minds... A splinter lodged deep within the
mind constantly tickling new never before thoughts to form... "Is
Python all it can be?". A lustful yearning to fix the warts that have
been ignored for far too long and were scarified at the alter of the
simplistic development cycle.

 But i think we are now at a crossroads people. We must forge the new
path and resist the temptation to circle around the familiar roads
endlessly. Heck *maybe* Guido himself is the architect of this change?
Maybe he *purposely* sowed discontent in an effort to ignite (or
reignite?) a passion for change within this community...?

The black monolith is before us. We have reached a crossroads. In the
balance hangs the future of high level programming languages. Will we
understand what the portal is and take the leap of faith forward, or
just bang some bones around like toddlers for another 10,000 years?
Only time will tell...? Only time will tell...?

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


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread MRAB

John Bokma wrote:

Thomas Jollans  writes:


On 07/11/2010 07:44 AM, rantingrick wrote:

On Jul 10, 10:59 pm, Luke Kenneth Casson Leighton
 wrote:

source at:http://github.com/lkcl/grailbrowser

$ python grail.py (note the lack of "python1.5" or "python2.4")

conversion of the 80 or so regex's to re has been carried out.
entirely successfully or not is a matter yet to be determined.  always
a hoot to try browsinghttp://www.bbc.co.ukorhttp://www.youtube.com
with a browser from 11+ years ago, it still cannot be resisted as
grail is the only working graphical web browser in the world written
in pure python [pybrowser is still in development, stalled].

l.

Congratulations on this effort Luke. However you know what project i
would really like to see the community get around? ...dramatic pause
here... a cross platform Python file browser! Yes i know there are
tons of them out there already and Python is a bit slow, but i think
it would be useful to many peoples.

Cross platform file manager. Hmm. Does "cross platform" involve UNIX and
something that isn't UNIX, say, Windows?
Erm, no. No, no, no. It won't work. Well, it would work, but it wouldn't
be any good. The UNIX and Windows concepts of "file system" are similar
enough for most programs not to care too much, but for something like a
file manager, that works intimately with the file system, trying to
support both UNIX and Windows is NOT a good idea.


Can't think of why not. Of course not all operations are shared by each
OS, but /I/ know that I can't do chmod on Windows. But it doesn't mean
that on Windows I can't make a file only readable by me. Just give me
the Windows security options on Windows, and chmod on *nix and I would
be very happy.

>
On Windows the root folders of the different drives could be treated as
subfolders of a 'root' folder.


Especially if all can be done via a context menu a la RISC OS.


Ah, RISC OS!


I'd heard how user-friendly the Mac was, but when I was first introduced
to the Mac (circa MacOS 8) I was very surprised that even it still used
old-fashioned Open and Save dialog boxes with their own little file
browsers like on a Windows PC instead of drag-and-drop like I'd become
used to on RISC OS. And that menu bar not even at the top of the window
but at the top of the _screen_! And the way that bringing one Finder
window to the front brought _all_ the Finder windows in front of the
other windows! I was distinctly underwhelmed... :-(

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


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread Martin P. Hellwig

On 07/11/10 04:59, Luke Kenneth Casson Leighton wrote:

source at:
http://github.com/lkcl/grailbrowser

$ python grail.py (note the lack of "python1.5" or "python2.4")

conversion of the 80 or so regex's to re has been carried out.
entirely successfully or not is a matter yet to be determined.  always
a hoot to try browsing http://www.bbc.co.uk or http://www.youtube.com
with a browser from 11+ years ago, it still cannot be resisted as
grail is the only working graphical web browser in the world written
in pure python [pybrowser is still in development, stalled].

l.

Congrats!
Are you planning to take over the world with grail and pyjs? :-)

--
mph

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


Re: Naming Conventions, Where's the Convention Waldo?

2010-07-11 Thread rantingrick
On Jul 11, 12:23 pm, MRAB  wrote:

> If you're so unhappy with Python, why don't you create your own
> language. I suggest the name "Rantthon".

Ah yes, then i can finally assume my worthy title of the "Ranting
Dictator For Life"! ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy questions from a python beginner

2010-07-11 Thread MRAB

Alf P. Steinbach /Usenet wrote:

* Stephen Hansen, on 11.07.2010 21:00:

On 7/11/10 11:45 AM, wheres pythonmonks wrote:

Follow-up:
Is there a way to define compile-time constants in python and have the
bytecode compiler optimize away expressions like:

if is_my_extra_debugging_on: print ...

when "is_my_extra_debugging" is set to false?  I'd like to pay no
run-time penalty for such code when extra_debugging is disabled.


Any code wrapped in a __debug__ guard is utterly ommitted if you run
Python with the -O option. That, and asserts go away.


On #2:  My point regarding the impossibility of writing the swap
function for ints is to explicitly understand that this isn't
possible, so as not to look for solutions along those lines when
trying to write python code.


Its impossible because Python's calling and namespace semantics simply
don't work like that. There's no references in the traditional sense,
because there's no variables-- boxes that you put values in. There's
just concrete objects. Objects are passed into the function and given
new names; that those objects have names in the enclosing scope is
something you don't know, can't access, and can't manipulate.. even the
objects don't know what names they happen to be called.

Check out http://effbot.org/zone/call-by-object.htm


Oh, I wouldn't give that advice. It's meaningless mumbo-jumbo. Python 
works like Java in this respect, that's all; neither Java nor Python 
support 'swap'.


Of course there are variables, that's why the docs call them variables.


In Java a variable is declared and exists even before the first
assignment to it. In Python a 'variable' isn't declared and won't exist
until the first 'assignment' to it.

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


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread Fuzzyman
On Jul 11, 5:16 pm, rantingrick  wrote:
> On Jul 11, 9:01 am, a...@pythoncraft.com (Aahz) wrote:
>
> > As usual, you would rather tell other people what to do instead of doing
> > any work yourself.
>
> Dear God! My statement was intended to fetch responses like...
>
>   "Hey, that sounds like a great idea" or \
>   "Hey, lets get hacking on this".
>
> I am so sick of you people constantly accusing me of being lazy. You
> don't even know me. Also i think you're really a bit jealous because i
> have the brass cohones to initiate a coding project without your
> express written permission. I will not allow myself to be brow beaten
> by anyone!

But why hijack someone else's announcement to do that? Congratulations
alone would have been great. However good your intentions your message
came across as "but it would really have been better if you had been
doing something else instead...".

All the best,

Michael Foord
--
http://www.voidspace.org.uk/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to determine whether pathname1 is below bathname2

2010-07-11 Thread Dan Stromberg
You could probably:

cd to dir1
getcwd

cd to dir2
getcwd

repeat
   cd ..
   getcwd
   if getcwd == dir1's cwd, then under
until at /

cd to dir1
repeat
   cd ..
   getcwd
   if getcwd == dir2's cwd, then under
until at /

This should deal with symlinks and junctions, as long as you aren't worried
about permissions issues on directories.

On Sun, Jul 11, 2010 at 7:34 AM, Gelonida  wrote:

> Hi Thomas,
>
> Thomas Jollans wrote:
> > On 07/11/2010 03:37 PM, Gelonida wrote:
> >> #
> >> import os
> >> def is_below_dir(fname,topdir):
> >> relpath = os.path.relpath(fname,topdir)
> >> return not relpath.startswith('..'+os.sep)
> >>
> >> print is_below_dir(path1,path2)
> >> #
> >> The basic idea is, if the path name of path1
> >> relative to path2 does NOT start with '..', then
> >> it must be below path2
> >>
> >>
> >> Does anybody see pitfalls with that solution?
> >> Is there by any chance a function, that I overlooked,
> >> which does already what I'd like to do?
> >
> > It probably won't work on Windows because it isolates volumes (drive
> > letters). What does, for example, os.path.relpath do when
> > you pass r'c:\foo\bar', r'y:\drive\letters\are\silly' ? I see two
> > reasonably correct options:
> Thanks, Indeed. different drives raise an ecception.
> I could catch the ValueError and let it just return False
>
> >
> > either raise an exception (there is no relative path) or return the
> > absolute path, which doesn't start with ..
> >
> > On UNIX, the only potential problem I see is that it may or may not do
> > what you expect when symlinks are involved somewhere.
>
> Also true. In my case I'd prefer it would not follow, but
> it doesn't really matter.
>
>
> So my function in order to be portable
> had now to look like:
> #
> import os
> def is_below_dir(fname,topdir):
> try:
>relpath = os.path.relpath(fname,topdir)
> except ValueError:
>return False
> return not relpath.startswith('..'+os.sep)
>
> print is_below_dir(path1,path2)
> #
>
> if I wanted to folow symlinks, then had to apply
> os.path.realpath() on
> fname AND on topdir
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible to create a read-only complex object?

2010-07-11 Thread Chris Rebert
On Sun, Jul 11, 2010 at 9:51 AM,   wrote:
> I have a complex object with attributes that contain lists, sets,
> dictionaries, and other objects. The lists and dictionaries may themselves
> contain complex objects.
>
> I would like to provide a read-only version of this type of object for other
> developers to query for reporting.
>
> Is there a way to prevent other developers from changing the attributes of
> my complex and nested object?

Have you considered just making a deep copy of your object instead?
That way, others could inspect the copy and mess with it all they
want, without affecting the original.
http://docs.python.org/library/copy.html#copy.deepcopy

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


Re: Easy questions from a python beginner

2010-07-11 Thread News123
Chris Rebert wrote:
> On Sun, Jul 11, 2010 at 2:08 PM, News123  wrote:
>> Carl Banks wrote:
>>> On Jul 11, 10:48 am, wheres pythonmonks 
>>> wrote:
 I'm an old Perl-hacker, and am trying to Dive in Python.
>>> Welcome to the light.
>>>
>>>
  I have some
 easy issues (Python 2.6)
 which probably can be answered in two seconds:

 1.  Why is it that I cannot use print in booleans??  e.g.:

>>> True and print "It is true!"
 I found a nice work-around using eval(compile(.,"","exec"))...
 Seems ugly to this Perl Programmer -- certainly Python has something 
 better?
>>> I'll repeat other people's sentiments: if you drop nothing else from
>>> your perl habits, drop this one.
>>>
>>>
 2.  How can I write a function, "def swap(x,y):..." so that "x = 3; y
 = 7; swap(x,y);" given x=7,y=3??
 (I want to use Perl's Ref "\" operator, or C's &).
 (And if I cannot do this [other than creating an Int class], is this
 behavior limited to strings,
  tuples, and numbers)
>>> Can't do it, but you can get reference-like behavior if you don't mind
>>> a level of indirection.  For example:
>>>
>>> def swap(x,y):
>>> t = y[0]
>>> y[0] = x[0]
>>> x[0] = t
>>>
>>> a = [1]
>>> b = [2]
>>> swap(a,b)
>> or
>> def swap[x,y]:
>>x[0],y[0] = y[0],x[0]
> 
 def swap[x,y]:
>   File "", line 1
> def swap[x,y]:
apologies:

I meant
def swap(x,y):
x[0],y[0] = y[0],x[0]

a = [1]
b = [2]
swap(a,b)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy questions from a python beginner

2010-07-11 Thread Chris Rebert
On Sun, Jul 11, 2010 at 2:08 PM, News123  wrote:
> Carl Banks wrote:
>> On Jul 11, 10:48 am, wheres pythonmonks 
>> wrote:
>>> I'm an old Perl-hacker, and am trying to Dive in Python.
>>
>> Welcome to the light.
>>
>>
>>>  I have some
>>> easy issues (Python 2.6)
>>> which probably can be answered in two seconds:
>>>
>>> 1.  Why is it that I cannot use print in booleans??  e.g.:
>>>
>> True and print "It is true!"
>>> I found a nice work-around using eval(compile(.,"","exec"))...
>>> Seems ugly to this Perl Programmer -- certainly Python has something better?
>>
>> I'll repeat other people's sentiments: if you drop nothing else from
>> your perl habits, drop this one.
>>
>>
>>> 2.  How can I write a function, "def swap(x,y):..." so that "x = 3; y
>>> = 7; swap(x,y);" given x=7,y=3??
>>> (I want to use Perl's Ref "\" operator, or C's &).
>>> (And if I cannot do this [other than creating an Int class], is this
>>> behavior limited to strings,
>>>  tuples, and numbers)
>>
>> Can't do it, but you can get reference-like behavior if you don't mind
>> a level of indirection.  For example:
>>
>> def swap(x,y):
>>     t = y[0]
>>     y[0] = x[0]
>>     x[0] = t
>>
>> a = [1]
>> b = [2]
>> swap(a,b)
>
> or
> def swap[x,y]:
>    x[0],y[0] = y[0],x[0]

>>> def swap[x,y]:
  File "", line 1
def swap[x,y]:
^
SyntaxError: invalid syntax

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


Re: Easy questions from a python beginner

2010-07-11 Thread News123
Carl Banks wrote:
> On Jul 11, 10:48 am, wheres pythonmonks 
> wrote:
>> I'm an old Perl-hacker, and am trying to Dive in Python.
> 
> Welcome to the light.
> 
> 
>>  I have some
>> easy issues (Python 2.6)
>> which probably can be answered in two seconds:
>>
>> 1.  Why is it that I cannot use print in booleans??  e.g.:
>>
> True and print "It is true!"
>> I found a nice work-around using eval(compile(.,"","exec"))...
>> Seems ugly to this Perl Programmer -- certainly Python has something better?
> 
> I'll repeat other people's sentiments: if you drop nothing else from
> your perl habits, drop this one.
> 
> 
>> 2.  How can I write a function, "def swap(x,y):..." so that "x = 3; y
>> = 7; swap(x,y);" given x=7,y=3??
>> (I want to use Perl's Ref "\" operator, or C's &).
>> (And if I cannot do this [other than creating an Int class], is this
>> behavior limited to strings,
>>  tuples, and numbers)
> 
> Can't do it, but you can get reference-like behavior if you don't mind
> a level of indirection.  For example:
> 
> def swap(x,y):
> t = y[0]
> y[0] = x[0]
> x[0] = t
> 
> a = [1]
> b = [2]
> swap(a,b)

or
def swap[x,y]:
x[0],y[0] = y[0],x[0]

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


Re: Easy questions from a python beginner

2010-07-11 Thread Carl Banks
On Jul 11, 11:45 am, wheres pythonmonks 
wrote:
> On #4:  So there are some hacks, but not something as easy as "import
> unimportable" or an @noexport decorator.  The underscore works, so
> does "del".

Careful.  If you have a module that looks like this:


def foo():
bar()

def bar():
print "hello"

del bar # bar is an internal function


It won't work; foo will raise NameError on bar if you try that.
However, del is useful to clean up code you run at module import time,
for example:


squares = []
for i in xrange(101):
squares.append(i*i)
del i


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


Re: Easy questions from a python beginner

2010-07-11 Thread Carl Banks
On Jul 11, 10:48 am, wheres pythonmonks 
wrote:
> I'm an old Perl-hacker, and am trying to Dive in Python.

Welcome to the light.


> I have some
> easy issues (Python 2.6)
> which probably can be answered in two seconds:
>
> 1.  Why is it that I cannot use print in booleans??  e.g.:
>
> >>> True and print "It is true!"
>
> I found a nice work-around using eval(compile(.,"","exec"))...
> Seems ugly to this Perl Programmer -- certainly Python has something better?

I'll repeat other people's sentiments: if you drop nothing else from
your perl habits, drop this one.


> 2.  How can I write a function, "def swap(x,y):..." so that "x = 3; y
> = 7; swap(x,y);" given x=7,y=3??
> (I want to use Perl's Ref "\" operator, or C's &).
> (And if I cannot do this [other than creating an Int class], is this
> behavior limited to strings,
>  tuples, and numbers)

Can't do it, but you can get reference-like behavior if you don't mind
a level of indirection.  For example:

def swap(x,y):
t = y[0]
y[0] = x[0]
x[0] = t

a = [1]
b = [2]
swap(a,b)

There's no reason to do this for a swap() function, as you've already
seen.  But it is sometimes handy for other things. (This includes
certain idioms involving regualar expression that are common in Perl.
Perl uses some special semantics when performing regexp searches that
allow automatic binding of match results.  Python doesn't, so in some
cases it's helpful to define an object you can mutate to store that
information.)

In the more general sense, Python functions and methods that mutate
the object they operate on are pretty common.


> 3.  Why might one want to store "strings" as "objects" in numpy
> arrays?  (Maybe they wouldn't)?

numpy is a library designed mainly to store numerical data, with some
advanced slicing operations and other cool stuff like
multdimensionality.

Some people, however, want to use the cool slicing operations on
arrays of Python objects, so numpy has a storage mode for arbitrary
Python objects.

(If you're wondering why they use object instead of a character type,
it's because rows of such an array are fixed-length strings.  Main
reason to use those is to interface with Fortran string arrays, or
maybe to simulate crossword puzzles or something.)


> 4.  Is there a way for me to make some function-definitions explicitly
> module-local?
> (Actually related to Q3 below: Is there a way to create an anonymous scope?)

No.  The (loose) convention is to define local or private functions
with a leading underscore to label them as "intended for internal use
only".


> 5. Is there a way for me to introduce a indention-scoped variables in python?
> See for example:http://evanjones.ca/python-pitfall-scope.html

Yes, define a nested function.  In Python 2 it's limited since you
cannot rebind variables in the surrounding scope; that's possible in
Python 3, though.


> 6.  Is there a Python Checker that enforces Strunk and White and is
> bad English grammar anti-python?  (Only half 
> joking)http://www.python.org/dev/peps/pep-0008/

There's a few, PyChecker and PyLint get mentioned a lot.  I used to
use them until I noticed that it never actually caught anything
(except stuff I didn't care about like using "id" as a variable name).


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


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread John Bokma
Thomas Jollans  writes:

> On 07/11/2010 07:44 AM, rantingrick wrote:
>> On Jul 10, 10:59 pm, Luke Kenneth Casson Leighton
>>  wrote:
>>> source at:http://github.com/lkcl/grailbrowser
>>>
>>> $ python grail.py (note the lack of "python1.5" or "python2.4")
>>>
>>> conversion of the 80 or so regex's to re has been carried out.
>>> entirely successfully or not is a matter yet to be determined.  always
>>> a hoot to try browsinghttp://www.bbc.co.ukorhttp://www.youtube.com
>>> with a browser from 11+ years ago, it still cannot be resisted as
>>> grail is the only working graphical web browser in the world written
>>> in pure python [pybrowser is still in development, stalled].
>>>
>>> l.
>> 
>> Congratulations on this effort Luke. However you know what project i
>> would really like to see the community get around? ...dramatic pause
>> here... a cross platform Python file browser! Yes i know there are
>> tons of them out there already and Python is a bit slow, but i think
>> it would be useful to many peoples.
>
> Cross platform file manager. Hmm. Does "cross platform" involve UNIX and
> something that isn't UNIX, say, Windows?
> Erm, no. No, no, no. It won't work. Well, it would work, but it wouldn't
> be any good. The UNIX and Windows concepts of "file system" are similar
> enough for most programs not to care too much, but for something like a
> file manager, that works intimately with the file system, trying to
> support both UNIX and Windows is NOT a good idea.

Can't think of why not. Of course not all operations are shared by each
OS, but /I/ know that I can't do chmod on Windows. But it doesn't mean
that on Windows I can't make a file only readable by me. Just give me
the Windows security options on Windows, and chmod on *nix and I would
be very happy. Especially if all can be done via a context menu a la
RISC OS.

-- 
John Bokma   j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development
-- 
http://mail.python.org/mailman/listinfo/python-list


Getting started with python on macintosh snow leopard with mysql - need help

2010-07-11 Thread dk
I have been going round and round trying to configure python 2.6
running on osx 10.6.x to work with mySQL 5.1.44.
Python seems to work ... i have an installation of mysql 5.1.44
running and have used it in conjunction for other php/apache projects.

I want to learn python and think i need a better database then mysql
lite that installs with the web2py frame work, so my quest to connect
to mysql or postgres began.

I seem to be stuck stuck getting mySQLdb drivers installed.  I down
loaded python 2.6.5 from the python site and MySQL-python-1.2.3 from
the my sql site.
I have worked past numerous errors by i now get the errors below when
i try to compile.

-- some background that might help anyone kind enough to have read
this far and who might be inclined to take pitty --
I have (tried) to use macports to install setuptools (which MySQL-
python-1.2.3 says it needs).
MacPorts has put tons of stuff in /opt/local ... so i am not sure i am
using this tool the way its intended.
this could all be as simple as adding some path declarations in the
right place but where?

lots of the post i have seen on the subject talk about 32/64
installation ... it makes sense that you might need to be consistent
in getting your components to work together, but i am not sure how i
tell of the various parts i have install which and how they were
compiled.

whereis python  display  /usr/bin/python
python -v spits out lots ... but here is a sample:

# /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
encodings/utf_8.pyc matches /Library/Frameworks/Python.framework/
Versions/2.6/lib/python2.6/encodings/utf_8.py
import encodings.utf_8 # precompiled from /Library/Frameworks/
Python.framework/Versions/2.6/lib/python2.6/encodings/utf_8.pyc
Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin





when i try to compile mysql-python-1.2.3 i get the following error
returned from python setup.py build -

building '_mysql' extension
gcc-4.0 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing
-fno-common -dynamic -DNDEBUG -g -O3 -Dversion_info=(1,2,3,'final',0) -
D__version__=1.2.3 -I/usr/local/mysql/include -I/Library/Frameworks/
Python.framework/Versions/2.6/include/python2.6 -c _mysql.c -o build/
temp.macosx-10.3-fat-2.6/_mysql.o -g -Os -arch x86_64 -fno-common -
D_P1003_1B_VISIBLE -DSIGNAL_WITH_VIO_CLOSE -DSIGNALS_DONT_BREAK_READ -
DIGNORE_SIGHUP_SIGQUIT -DDONT_DECLARE_CXA_PURE_VIRTUAL
In file included from /Library/Frameworks/Python.framework/Versions/
2.6/include/python2.6/unicodeobject.h:4,
 from /Library/Frameworks/Python.framework/Versions/
2.6/include/python2.6/Python.h:85,
 from pymemcompat.h:10,
 from _mysql.c:29:
/Developer/SDKs/MacOSX10.4u.sdk/usr/include/stdarg.h:4:25: error:
stdarg.h: No such file or directory
In file included from _mysql.c:36:
/usr/local/mysql/include/my_config.h:1053:1: warning: "HAVE_WCSCOLL"
redefined
In file included from /Library/Frameworks/Python.framework/Versions/
2.6/include/python2.6/Python.h:8,
 from pymemcompat.h:10,
 from _mysql.c:29:
/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/
pyconfig.h:808:1: warning: this is the location of the previous
definition
error: command 'gcc-4.0' failed with exit status 1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy questions from a python beginner

2010-07-11 Thread Alf P. Steinbach /Usenet

* Stephen Hansen, on 11.07.2010 21:00:

On 7/11/10 11:45 AM, wheres pythonmonks wrote:

Follow-up:
Is there a way to define compile-time constants in python and have the
bytecode compiler optimize away expressions like:

if is_my_extra_debugging_on: print ...

when "is_my_extra_debugging" is set to false?  I'd like to pay no
run-time penalty for such code when extra_debugging is disabled.


Any code wrapped in a __debug__ guard is utterly ommitted if you run
Python with the -O option. That, and asserts go away.


On #2:  My point regarding the impossibility of writing the swap
function for ints is to explicitly understand that this isn't
possible, so as not to look for solutions along those lines when
trying to write python code.


Its impossible because Python's calling and namespace semantics simply
don't work like that. There's no references in the traditional sense,
because there's no variables-- boxes that you put values in. There's
just concrete objects. Objects are passed into the function and given
new names; that those objects have names in the enclosing scope is
something you don't know, can't access, and can't manipulate.. even the
objects don't know what names they happen to be called.

Check out http://effbot.org/zone/call-by-object.htm


Oh, I wouldn't give that advice. It's meaningless mumbo-jumbo. Python works like 
Java in this respect, that's all; neither Java nor Python support 'swap'.


Of course there are variables, that's why the docs call them variables.

We've had this discussion before and I know from that that it is a religious 
issue with a small subset of the Python community, where reason, facts, logic 
does not apply and is not even recognized as such. So be it. So I'm not out to 
convince you or other of that sub-community, or trying to reason with you folks 
on this issue (futile, and generates flames pretty fast), but I do not want 
newbies brainwashed into that non-reasoning nonsense pure faith religion.


For what it's worth, I'm sure that the effbot.org author, whose pages are 
otherwise quite technically meaningful & useful, in this case, after the flame 
war with some Java folks, decided that technical accuracy just wasn't worth it.


So, I believe, he punted, which is an eminently rational choice when one's goals 
require acceptance in a society dominated by a religious clique. And just as I'm 
not out to engage you in any debate on this issue (futile), neither am I calling 
you irrational. Perhaps your choice is the same as that author's.



Cheers,

- Alf

--
blog at http://alfps.wordpress.com>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Easy questions from a python beginner

2010-07-11 Thread Thomas Jollans
On 07/11/2010 08:45 PM, wheres pythonmonks wrote:
> Thanks for your answers -- it is much appreciated.
> 
> On #1:  I had very often used chained logic with both logging and
> functional purposes in Perl, and wanted to duplicate this in Python.
> "It reads like english"  Using the print_ print wrapper works for me.
> 
> Follow-up:
> Is there a way to define compile-time constants in python and have the
> bytecode compiler optimize away expressions like:
> 
> if is_my_extra_debugging_on: print ...
> 
> when "is_my_extra_debugging" is set to false?  I'd like to pay no
> run-time penalty for such code when extra_debugging is disabled.

no.

> On #3:  Sorry this is confusing, but I was browsing some struct array
> code from numpy, in which one of the columns contained strings, but
> the type information, supplied in numpy.array's dtype argument,
> specified the type as a an "object" not a string.  Just wondering why
> one would do that.

No expert on numpy, but maybe storing object references is cheaper than
storing strings here ?

> 
> On #5: Nesting the function was actually what I was thinking of doing,
> but alas, I cannot modify outer-scope variables within a function, and
> of course, I don't want to use globals.

yes you can. Well, at least since whenever the "nonlocal" keyword was
introduced (recent, might be 3.x only)

Or you can wrap what you want to change in a dict or list.

> I am programmer who likes to scope off variables as much as possible
> (I believe in minimal state).
> 
> The following is an example of what I am trying to protect against:
> http://stackoverflow.com/questions/938429/scope-of-python-lambda-functions-and-their-parameters

On the other hand, python scoping and namespace rules, while they may be
different to those in other languages, are nice and simple.

> Will try to avoid namespace mangling until next week.


Cheers

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


Re: Easy questions from a python beginner

2010-07-11 Thread Stephen Hansen
On 7/11/10 11:45 AM, wheres pythonmonks wrote:
> Follow-up:
> Is there a way to define compile-time constants in python and have the
> bytecode compiler optimize away expressions like:
> 
> if is_my_extra_debugging_on: print ...
> 
> when "is_my_extra_debugging" is set to false?  I'd like to pay no
> run-time penalty for such code when extra_debugging is disabled.

Any code wrapped in a __debug__ guard is utterly ommitted if you run
Python with the -O option. That, and asserts go away.

> On #2:  My point regarding the impossibility of writing the swap
> function for ints is to explicitly understand that this isn't
> possible, so as not to look for solutions along those lines when
> trying to write python code.

Its impossible because Python's calling and namespace semantics simply
don't work like that. There's no references in the traditional sense,
because there's no variables-- boxes that you put values in. There's
just concrete objects. Objects are passed into the function and given
new names; that those objects have names in the enclosing scope is
something you don't know, can't access, and can't manipulate.. even the
objects don't know what names they happen to be called.

Check out http://effbot.org/zone/call-by-object.htm

> On #3:  Sorry this is confusing, but I was browsing some struct array
> code from numpy, in which one of the columns contained strings, but
> the type information, supplied in numpy.array's dtype argument,
> specified the type as a an "object" not a string.  Just wondering why
> one would do that.

Strings are objects.

I don't use numpy, btu I'd assume "object" would basically mean,
"anything can go here", as everything is an object.

> On #5: Nesting the function was actually what I was thinking of doing,
> but alas, I cannot modify outer-scope variables within a function, and
> of course, I don't want to use globals.

You can modify outer-scope objects: if they are mutable. I.e., a
dictionary. What you can't do is modify outer *scopes*, the namespaces.
You can't re-bind a new/different object to a certain name in an outer
scope.

> I am programmer who likes to scope off variables as much as possible
> (I believe in minimal state).

That's a fine and nice goal. In Python your only real tool for this is
to break things up into more logical functions.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy questions from a python beginner

2010-07-11 Thread wheres pythonmonks
Thanks for your answers -- it is much appreciated.

On #1:  I had very often used chained logic with both logging and
functional purposes in Perl, and wanted to duplicate this in Python.
"It reads like english"  Using the print_ print wrapper works for me.

Follow-up:
Is there a way to define compile-time constants in python and have the
bytecode compiler optimize away expressions like:

if is_my_extra_debugging_on: print ...

when "is_my_extra_debugging" is set to false?  I'd like to pay no
run-time penalty for such code when extra_debugging is disabled.

On #2:  My point regarding the impossibility of writing the swap
function for ints is to explicitly understand that this isn't
possible, so as not to look for solutions along those lines when
trying to write python code.

On #3:  Sorry this is confusing, but I was browsing some struct array
code from numpy, in which one of the columns contained strings, but
the type information, supplied in numpy.array's dtype argument,
specified the type as a an "object" not a string.  Just wondering why
one would do that.

On #4:  So there are some hacks, but not something as easy as "import
unimportable" or an @noexport decorator.  The underscore works, so
does "del".

On #5: Nesting the function was actually what I was thinking of doing,
but alas, I cannot modify outer-scope variables within a function, and
of course, I don't want to use globals.

On #6: Always trying to improve my writing -- and I thought it was
cute that Guido tries to encourage this as well.


I am programmer who likes to scope off variables as much as possible
(I believe in minimal state).

The following is an example of what I am trying to protect against:
http://stackoverflow.com/questions/938429/scope-of-python-lambda-functions-and-their-parameters

Will try to avoid namespace mangling until next week.

Thanks again,

W



On Sun, Jul 11, 2010 at 2:17 PM, Duncan Booth
 wrote:
> wheres pythonmonks  wrote:
>
>> I'm an old Perl-hacker, and am trying to Dive in Python.  I have some
>> easy issues (Python 2.6)
>> which probably can be answered in two seconds:
>>
>> 1.  Why is it that I cannot use print in booleans??  e.g.:
> True and print "It is true!"
>>
>> I found a nice work-around using
>> eval(compile(.,"","exec"))... Seems ugly to this Perl
>> Programmer -- certainly Python has something better?
>
> In Python 2.x print is a statement. If you really wanted you could do:
>
>   True and sys.write("It is true!\n")
>
> In Python 3 you can do this:
>
>   True and print("It is true!")
>
> though I can't think of any situations where this would be better that just
> writing:
>
>   if somecondition: print "whatever"
>
>>
>> 2.  How can I write a function, "def swap(x,y):..." so that "x = 3; y
>>= 7; swap(x,y);" given x=7,y=3??
>
> Why use a function?
>
>   x, y = y, x
>
>> (I want to use Perl's Ref "\" operator, or C's &).
>> (And if I cannot do this [other than creating an Int class], is this
>> behavior limited to strings,
>>  tuples, and numbers)
>
> If you want to use perl's operators I suggest you use perl.
>
>>
>> 3.  Why might one want to store "strings" as "objects" in numpy
>> arrays?  (Maybe they wouldn't)?
>
> Why would one want to write incomprehensible questions?
>
>>
>> 4.  Is there a way for me to make some function-definitions explicitly
>> module-local?
>> (Actually related to Q3 below: Is there a way to create an anonymous
>> scope?)
>
> Not really.
>
>>
>> 5. Is there a way for me to introduce a indention-scoped variables in
>> python? See for example: http://evanjones.ca/python-pitfall-scope.html
>
> No. The page you reference effectively says 'my brain is used to the way
> Java works'. *My* brain is used to the way Python works. Who is to say
> which is better?
>
>>
>> 6.  Is there a Python Checker that enforces Strunk and White and is
>> bad English grammar anti-python?  (Only half joking)
>> http://www.python.org/dev/peps/pep-0008/
>>
> pylint will do quite a good job of picking over your code. Most people
> don't bother.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy questions from a python beginner

2010-07-11 Thread Stephen Hansen
On 7/11/10 10:48 AM, wheres pythonmonks wrote:
> I'm an old Perl-hacker, and am trying to Dive in Python.  I have some
> easy issues (Python 2.6)
> which probably can be answered in two seconds:
> 
> 1.  Why is it that I cannot use print in booleans??  e.g.:
 True and print "It is true!"

Because print is a statement. Statements have to start lines. If you
want to do this, use a function-- in Python 2.6 either via "from
__future__ import print_function" or writing your own, even if its just
a very thing wrapper around the print statement.

> 2.  How can I write a function, "def swap(x,y):..." so that "x = 3; y
> = 7; swap(x,y);" given x=7,y=3??
> (I want to use Perl's Ref "\" operator, or C's &).
> (And if I cannot do this [other than creating an Int class], is this
> behavior limited to strings,
>  tuples, and numbers)

You can't do that*. Its not limited to any certain type of objects. You
can't manipulate calling scopes: if you really want to do that sort of
explicit namespace mangling, use dictionaries (or objects, really) as
the namespace to mangle and pass them around.

> 3.  Why might one want to store "strings" as "objects" in numpy
> arrays?  (Maybe they wouldn't)?

I don't use numpy. No idea.

> 4.  Is there a way for me to make some function-definitions explicitly
> module-local?

In what sense? If you prepend them with an underscore, the function
won't be imported with "from x import *". You can also explicitly
control what is imported in that way with a module-level __all__ attribute.

Now that won't stop someone from doing "import x" and
"x._your_private_function" but Python doesn't believe in enforicng
restrictions.

> (Actually related to Q3 below: Is there a way to create an anonymous scope?)

No. You can create a limited anonymous function with lambda, but note it
takes only an expression-- no statements in it.

> 5. Is there a way for me to introduce a indention-scoped variables in python?
> See for example: http://evanjones.ca/python-pitfall-scope.html

No. Python only has three scopes historically; local, global, and
builtin. Then post-2.2(ish, I forget) limited nested scoping -- but only
with nested functions, and you can't (until Python 3) re-bind variables
in outer scopes (though you can modify them if they are mutable objects).

Python's scoping is very basic (we generally think this is a good thing;
others are never happy with it) and is not fully lexical scoped.

> 6.  Is there a Python Checker that enforces Strunk and White and is
> bad English grammar anti-python?  (Only half joking)
> http://www.python.org/dev/peps/pep-0008/

Check out pylint and/or pychecker, which do various style-based
checking. If you're asking for something else, I can't pierce your
sarcasm to figure out what.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

* Yes, I know its actually possible, to manipulate outer/calling scopes
with frame hacking. This is dangerous / bad / an implementation detail
that one should not rely on or use, generally speaking. If you need to
do this you're writing Java or Perl or C in Python, instead of writing
Python in Python, so are probably doing all kinds of things that are
slow / bad / dangerous / just not taking advantage of Python's strengths.



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

2010-07-11 Thread Mark Dickinson
On Jul 11, 6:38 am, rantingrick  wrote:
> Seems kinda dumb to build a tuple just so a conditional wont blow
> chunks! This integer bool-ing need to be fixed right away!

Okay.  What fix do you propose?  Would your fix maintain the identity
"0 == False"? For bonus points, explain how you'd deal with any
backwards compatibility problems that your fix introduces.

Have you considered forking Python?  That may be the way forward here.

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


Re: Easy questions from a python beginner

2010-07-11 Thread Duncan Booth
wheres pythonmonks  wrote:

> I'm an old Perl-hacker, and am trying to Dive in Python.  I have some
> easy issues (Python 2.6)
> which probably can be answered in two seconds:
> 
> 1.  Why is it that I cannot use print in booleans??  e.g.:
 True and print "It is true!"
> 
> I found a nice work-around using
> eval(compile(.,"","exec"))... Seems ugly to this Perl
> Programmer -- certainly Python has something better? 

In Python 2.x print is a statement. If you really wanted you could do:

   True and sys.write("It is true!\n")

In Python 3 you can do this:

   True and print("It is true!")

though I can't think of any situations where this would be better that just 
writing:

   if somecondition: print "whatever"

> 
> 2.  How can I write a function, "def swap(x,y):..." so that "x = 3; y
>= 7; swap(x,y);" given x=7,y=3??

Why use a function?

   x, y = y, x

> (I want to use Perl's Ref "\" operator, or C's &).
> (And if I cannot do this [other than creating an Int class], is this
> behavior limited to strings,
>  tuples, and numbers)

If you want to use perl's operators I suggest you use perl.

> 
> 3.  Why might one want to store "strings" as "objects" in numpy
> arrays?  (Maybe they wouldn't)?

Why would one want to write incomprehensible questions?

> 
> 4.  Is there a way for me to make some function-definitions explicitly
> module-local?
> (Actually related to Q3 below: Is there a way to create an anonymous
> scope?) 

Not really.

> 
> 5. Is there a way for me to introduce a indention-scoped variables in
> python? See for example: http://evanjones.ca/python-pitfall-scope.html

No. The page you reference effectively says 'my brain is used to the way 
Java works'. *My* brain is used to the way Python works. Who is to say 
which is better?

> 
> 6.  Is there a Python Checker that enforces Strunk and White and is
> bad English grammar anti-python?  (Only half joking)
> http://www.python.org/dev/peps/pep-0008/
> 
pylint will do quite a good job of picking over your code. Most people 
don't bother.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy questions from a python beginner

2010-07-11 Thread Michael Torrie
On 07/11/2010 11:48 AM, wheres pythonmonks wrote:
> I'm an old Perl-hacker, and am trying to Dive in Python.  I have some
> easy issues (Python 2.6)
> which probably can be answered in two seconds:
> 
> 1.  Why is it that I cannot use print in booleans??  e.g.:
 True and print "It is true!"

This works in Python 3, or 2.6 and later with the print function:
>>> True and print("It's true!")

That said, this is one particular perl-ism that most python programmers
don't really like.  I think most python programmers prefer:

if True: print "It's true!"

Other perlisms like "something or die" are also to be avoided in python
generally. Just state what you want:  if not something: sys.exit(1)

> I found a nice work-around using eval(compile(.,"","exec"))...
> Seems ugly to this Perl Programmer -- certainly Python has something better?

Seems ugly even to Python programmers!  And potentially dangerous.  Just
use an if statement.  It's cleaner, more readable, and explicitly
declares what you want.

> 2.  How can I write a function, "def swap(x,y):..." so that "x = 3; y
> = 7; swap(x,y);" given x=7,y=3??
> (I want to use Perl's Ref "\" operator, or C's &).
> (And if I cannot do this [other than creating an Int class], is this
> behavior limited to strings,
>  tuples, and numbers)

I'm not sure you can.  Python "variables" are names that are bound to
objects.  When you pass an object to a function, that object is bound to
the names declared in the function.

Python passes things by object, not by reference.  Names are merely for
convenience when accessing an object.  If you want a function to be able
to modify an object you have to make sure that object is mutable, or if
it's not, pass it in a list (which is mutable).

You probably could do something like this:
(x,y) = (y,x)

Seems pretty clean to me, cleaner than using a function to swap things.

> 3.  Why might one want to store "strings" as "objects" in numpy
> arrays?  (Maybe they wouldn't)?
> 
> 4.  Is there a way for me to make some function-definitions explicitly
> module-local?

The standard way is to declare them with a name beginning with a leading
_ (underscore) to indicate that they are private and should not be
accessed by others.  Someone could access them if they want, though;
python obviously lets programmers shoot themselves in the foot if they want.

> (Actually related to Q3 below: Is there a way to create an anonymous scope?)

Not that I know of.  A nested function usually does enough for me.

> 5. Is there a way for me to introduce a indention-scoped variables in python?
> See for example: http://evanjones.ca/python-pitfall-scope.html

Perhaps nest a function and call it?

> 6.  Is there a Python Checker that enforces Strunk and White and is
> bad English grammar anti-python?  (Only half joking)
> http://www.python.org/dev/peps/pep-0008/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't python's list append() method return the list itself?

2010-07-11 Thread dhruvbird
On Jul 11, 9:19 pm, Thomas Jollans  wrote:
> On 07/11/2010 05:59 PM, dhruvbird wrote:
>
> > Why doesn't python's list append() method return the list itself? For
> > that matter, even the reverse() and sort() methods?
> > I found this link (http://code.google.com/edu/languages/google-python-
> > class/lists.html) which suggests that this is done to make sure that
> > the programmer understands that the list is being modified in place,
>
> Yes!
>
> > but that rules out constructs like:
> > ([1,2,3,4].reverse()+[[]]).reverse()
>
> No!
>
> you can either approach this by imperatively modifying a list in-place:
>
> L = [1,2,3,4]
> L.reverse()
> L.append([])
> L.reverse()
>
> Or you can use a more functional style:
>
> L2 = reversed(reversed([1,2,3,4]) + [[]])

Okay, but this assumes that I have reversed/sorted/etc... type of
functions for all member functions that mutate the container.
Also, as Nathan mentioned, reversed returns an iterator, whereas
sorted returns a list. This asymmertic behaviour is a bit unnerving.

>
> (or ([1,2,3,4][::-1]+[[]])[::-1], if you like that kind of thing)
>
> Imagine list.reverse and list.append *did* return self:
>
> L1 = [1,2,3,4]
> L2 = L1.reverse().append([]).reverse()
>
> would you expect, after this code, that (L1 == L2) and (L1 is L2)? I
> think it would surprise a lot of people. Better clearly separate
> modifying an object and functionally processing an object.

I think this is a fair call. Honestly, I wouldn't expect them to be
the same.

However, there are cases when I want to be able to write down my
intent in one line.
Much like f(g(h(x))).

On a side note, is there any other way to append to a list using
slices (apart from the one below):
x[len(x):len(x)] = [item to append]

And while we are talking about python here, why does this statement:
y = x[:0] = [100] behave the way it does?
I mean everything except for the last value is assigned to the last
value rather than the assignments following the chain and every item
getting its succeeding item's reference?

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


Re: Easy questions from a python beginner

2010-07-11 Thread Thomas Jollans
On 07/11/2010 07:48 PM, wheres pythonmonks wrote:
> I'm an old Perl-hacker, and am trying to Dive in Python.  I have some
> easy issues (Python 2.6)
> which probably can be answered in two seconds:
> 
> 1.  Why is it that I cannot use print in booleans??  e.g.:
 True and print "It is true!"

prior to Python 3.0, print is a statement, not an expression, which
means that it's rather unflexible.

In Python 3.x, print is a function, and you can use it as one:

Python 3.1.2 (release31-maint, Jul  8 2010, 09:18:08)
[GCC 4.4.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> True and print('It is true!')
It is true!
>>>

> 
> I found a nice work-around using eval(compile(.,"","exec"))...
> Seems ugly to this Perl Programmer -- certainly Python has something better?

Either use good old if:

if True: print 'It is true!'

or use a function instead of the print statement:

def print_(s):
print s

True and print_("It is true!")

> 
> 2.  How can I write a function, "def swap(x,y):..." so that "x = 3; y
> = 7; swap(x,y);" given x=7,y=3??
> (I want to use Perl's Ref "\" operator, or C's &).
> (And if I cannot do this [other than creating an Int class], is this
> behavior limited to strings,
>  tuples, and numbers)

You can't. A function cannot modify the caller's namespace. "x" and "y"
are just names, not pointers you can edit directly.

But look at this:
>>> x = 1
>>> y = 2
>>> x,y = y,x
>>> x
2
>>> y
1
>>>

> 4.  Is there a way for me to make some function-definitions explicitly
> module-local?
> (Actually related to Q3 below: Is there a way to create an anonymous scope?)

Do you mean have the function visible inside the module, but not to the
importer?

Well, you could "del thefunc" at the end of the module, but then you
won't be able to access it from within other functions. You could in
principle create a function, pass it as a default argument to every
function that uses it, and then delete it. But that's just silly.

> 
> 5. Is there a way for me to introduce a indention-scoped variables in python?
> See for example: http://evanjones.ca/python-pitfall-scope.html

No.
exception: nested functions.

if you really want, you can always del variables after use.

> 
> 6.  Is there a Python Checker that enforces Strunk and White and is
> bad English grammar anti-python?  (Only half joking)
> http://www.python.org/dev/peps/pep-0008/

Huh?


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


Easy questions from a python beginner

2010-07-11 Thread wheres pythonmonks
I'm an old Perl-hacker, and am trying to Dive in Python.  I have some
easy issues (Python 2.6)
which probably can be answered in two seconds:

1.  Why is it that I cannot use print in booleans??  e.g.:
>>> True and print "It is true!"

I found a nice work-around using eval(compile(.,"","exec"))...
Seems ugly to this Perl Programmer -- certainly Python has something better?

2.  How can I write a function, "def swap(x,y):..." so that "x = 3; y
= 7; swap(x,y);" given x=7,y=3??
(I want to use Perl's Ref "\" operator, or C's &).
(And if I cannot do this [other than creating an Int class], is this
behavior limited to strings,
 tuples, and numbers)

3.  Why might one want to store "strings" as "objects" in numpy
arrays?  (Maybe they wouldn't)?

4.  Is there a way for me to make some function-definitions explicitly
module-local?
(Actually related to Q3 below: Is there a way to create an anonymous scope?)

5. Is there a way for me to introduce a indention-scoped variables in python?
See for example: http://evanjones.ca/python-pitfall-scope.html

6.  Is there a Python Checker that enforces Strunk and White and is
bad English grammar anti-python?  (Only half joking)
http://www.python.org/dev/peps/pep-0008/

Thanks,
W
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't python's list append() method return the list itself?

2010-07-11 Thread MRAB

Thomas Jollans wrote:

On 07/11/2010 05:59 PM, dhruvbird wrote:

Why doesn't python's list append() method return the list itself? For
that matter, even the reverse() and sort() methods?
I found this link (http://code.google.com/edu/languages/google-python-
class/lists.html) which suggests that this is done to make sure that
the programmer understands that the list is being modified in place,


Yes!


but that rules out constructs like:
([1,2,3,4].reverse()+[[]]).reverse()


No!

you can either approach this by imperatively modifying a list in-place:

L = [1,2,3,4]
L.reverse()
L.append([])
L.reverse()


[snip]
If you want to prepend an empty list in-place, use the .insert method:

L = [1,2,3,4]
L.insert(0, [])
--
http://mail.python.org/mailman/listinfo/python-list


Re: Naming Conventions, Where's the Convention Waldo?

2010-07-11 Thread MRAB

rantingrick wrote:

Another source of asininity seems to be the naming conventions of the
Python language proper! True/False start with an upper case and i
applaud this. However str, list, tuple, int, float --need i go
on...?-- start with lowercase.

Q: Well what the hell is your problem Rick. Who cares right?

WRONG, I tell you what my problem is. Now i cannot "wisely" use
variables like...

str="this is a string"
list = [1,2,3]
def make_random_objs(range=10)
def show_message(str)
int = 12

If we would have adopted proper naming conventions from dios numero
uno all this nonsense would be rectified! Str, Float, List, Range,
etc, etc. You think Python 3000 was a hump to climb over just wait for
Python 4000.

Just thoughts.


If you're so unhappy with Python, why don't you create your own
language. I suggest the name "Rantthon".
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't python's list append() method return the list itself?

2010-07-11 Thread Antoine Pitrou
On Sun, 11 Jul 2010 08:59:06 -0700 (PDT)
dhruvbird  wrote:
> Why doesn't python's list append() method return the list itself? For
> that matter, even the reverse() and sort() methods?
> I found this link (http://code.google.com/edu/languages/google-python-
> class/lists.html) which suggests that this is done to make sure that
> the programmer understands that the list is being modified in place,
> but that rules out constructs like:
> ([1,2,3,4].reverse()+[[]]).reverse()
> I want to prepend an empty list to [1,2,3,4]. This is just a toy
> example, since I can always do that with [[]]+[1,2,3,4].

>>> x = [1,2,3,4]
>>> y = [5,6]
>>> x[:0] = y
>>> x
[5, 6, 1, 2, 3, 4]



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


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread Stephen Hansen
On 7/11/10 9:31 AM, Thomas Jollans wrote:
> Cross platform file manager. Hmm. Does "cross platform" involve UNIX and
> something that isn't UNIX, say, Windows?
> Erm, no. No, no, no. It won't work. Well, it would work, but it wouldn't
> be any good. The UNIX and Windows concepts of "file system" are similar
> enough for most programs not to care too much, but for something like a
> file manager, that works intimately with the file system, trying to
> support both UNIX and Windows is NOT a good idea.

Indeed so.

And you can't lump the Mac in with "UNIX" here, even though it really is
UNIX at the foundation, because there's some very fundamental
differences between HFS+ (and some other details that are higher level)
and more traditional unix FS's. Not to mention that the Mac FS situation
is slightly schitzo since it has two very different ways at looking and
treating the files, the posix way and the Foundation way... and users
think more in terms of the latter, usually. At least less sophisticated
users.

You can't do a cross-platform file manager without either doing a huge
amount of work exposing each platform separately-- essentially getting
separate codebases for each-- or doing a least common denominator
situation, at which point I boggle: why the hell did you bother to begin
with? Even Finder is better then that, let alone windows' Explorer.

Even if you did the former... what the hell is the point, still? What
real problem needs solving here that people should drop something and
rally behind*?

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

(*): I do not argue that a non-default file manager on an OS might be a
great thing. I use Path Finder on the mac and have been very pleased
with it for years, and consider its purchase money very well spent. Its
hands-down the absolute best file management tool ever done, in my
opinion. But really. When I'm using windows (or ubuntu), the only thing
I miss is the drop stack(**). I'd *almost* consider a bare-bones LCD
file manager which brought only a drop stack to windows and linux to be
worth the effort-- except then I'd keep having to switch over to an
entirely different program whenever I wanted to do permissions, since
Windows and Linux have /completely/ different permission models.

(**): The drop stack is a little corner of the window that you can drag
files onto. Then drag more files onto. Then drag more files onto. Then
you can navigate to another part of the system, and drag files off of
said stack, in a LIFO manner, moving them as a result of this action.



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Possible to create a read-only complex object?

2010-07-11 Thread python
I have a complex object with attributes that contain lists, sets,
dictionaries, and other objects. The lists and dictionaries may
themselves contain complex objects.

I would like to provide a read-only version of this type of
object for other developers to query for reporting.

Is there a way to prevent other developers from changing the
attributes of my complex and nested object?

In researching this question, I have identified __setattr__ and
__delattr__ as possible ways to prevent changes to simple
attributes, but I don't believe these magic methods will prevent
others from fiddling with attributes containing lists and
dictionaries or the contents of these lists and dictionaries.

Another idea I had was to create a wrapper object to proxy all
access to the original object. Is there a generic reciepe for
this type of wrapper?

Thank you,
Malcolm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't python's list append() method return the list itself?

2010-07-11 Thread Thomas Jollans
On 07/11/2010 06:28 PM, Nathan Rice wrote:
> Do list(reversed(list(reversed([1, 2, 3, 4])) + [[]]))
> 
> Though TBH sometimes get annoyed at this behavior myself.  There are a
> lot of people who are very vocal in support of returning none, and it
> makes sense in some ways.  Since reversed returns an iterator though, it
> makes this code horrible and unreadable.
> 

ah yes, forgot about that nuance. casting reversed to list. Still, there
is slicing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Plot problem.. ?? No sign at all

2010-07-11 Thread Ritchy lelis
On 11 jul, 13:28, Johan Grönqvist  wrote:
> 2010-07-11 02:12, Ritchy lelis skrev:
>
> > On 7 jul, 08:38, Johan Grönqvist  wrote:
>
> > About the plot draw it's a curve that it's a set of points wich it's
> > the result of the comput of the Vref and Vi together. I don't know if
> > i had to make a break instruction (like in other's languages) after
> > the "If" instructions if i want the else-condition to be executed? ...
> > (do you have some sujestions?)
>
> I would have expected a code structure similar to this:
>
> (NOTE: This is a very inefficient solution, and not the one suggested
> earlier, but it is closer to the code snippet you posted originally, and
> it does produce a plot.)
>
> --
> import numpy as np
> import matplotlib.pyplot as plt
> Vref = np.linspace(1,20, 100)
> Vi = np.linspace(1,10,100)
>
> for ref in Vref: # Loop over Vref and Vi
>      for i in Vi:
>          if  i > ref/4: # Compute V0
>              V0 = 2*i-ref
>          elif (-ref/4) <= ref and ref <= ref/4:
>              V0 = 2*i
>          elif i < -ref/4:
>              V0 = 2*i+ref
>          plt.plot(i, V0, ".") # Plot one single point at x = i, y = V0
> plt.show() # Display the plot in a window
> --
>
> > Anyway i have a picture of a tuturial that i found but in this forum i
> > can't post it. That pic would show what a really want...
>
> Can you give a link?
>
>
>
> > Relatively to the axis, the Vi takes the x-axis and the Vref takes the
> > y-axis.
>
> To me this sound like you want to make a 3D-plot, as there is the
> x-axis, the y-axis, and V0. Is this correct? Is V0 on a z-axis?
>
>
>
> > As i said, i have a good 2 pic of a doc that has the information about
> > this ADC that i'm developing.
>
> I looked on wikipedia
> , and saw some
> figures. Is any of those similar to what you look for?
>
> I see that they have (Vi - Vref) on the x-axis, and the computed value
> on the y-axis.
>
> Regards
>
> Johan

Hi

Yes those fig look's familiar to me but for now the objective its to
get that residue transfer function (1.5-Bit-Per-Stage Pipelined ADC).

I found in http://amesp02.tamu.edu/~sanchez/ADC-pipeline_lecture.PDF
there are some fig and explanations on page's 9-13. Can you take a
look there please?

Also you can take a look in http://www.maxim-ic.com/app-notes/index.mvp/id/1023
(I think there it´s more information than the first link i gave you).

I'll be waiting for sujestions.

Thank's

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


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread Thomas Jollans
On 07/11/2010 07:44 AM, rantingrick wrote:
> On Jul 10, 10:59 pm, Luke Kenneth Casson Leighton
>  wrote:
>> source at:http://github.com/lkcl/grailbrowser
>>
>> $ python grail.py (note the lack of "python1.5" or "python2.4")
>>
>> conversion of the 80 or so regex's to re has been carried out.
>> entirely successfully or not is a matter yet to be determined.  always
>> a hoot to try browsinghttp://www.bbc.co.ukorhttp://www.youtube.com
>> with a browser from 11+ years ago, it still cannot be resisted as
>> grail is the only working graphical web browser in the world written
>> in pure python [pybrowser is still in development, stalled].
>>
>> l.
> 
> Congratulations on this effort Luke. However you know what project i
> would really like to see the community get around? ...dramatic pause
> here... a cross platform Python file browser! Yes i know there are
> tons of them out there already and Python is a bit slow, but i think
> it would be useful to many peoples.

Cross platform file manager. Hmm. Does "cross platform" involve UNIX and
something that isn't UNIX, say, Windows?
Erm, no. No, no, no. It won't work. Well, it would work, but it wouldn't
be any good. The UNIX and Windows concepts of "file system" are similar
enough for most programs not to care too much, but for something like a
file manager, that works intimately with the file system, trying to
support both UNIX and Windows is NOT a good idea.

If you stick to common functionality, the program will be rather useless
on both systems. Yes, you could *browse* the file system alright, but
that's about it. If you attempt to be full-featured, keeping it in one
code base, let alone in one user interface, is destined to be a
nightmare and induce suicides.

The above might have been very slightly exaggerated.

Cheers!
Thomas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't python's list append() method return the list itself?

2010-07-11 Thread Nathan Rice
Do list(reversed(list(reversed([1, 2, 3, 4])) + [[]]))

Though TBH sometimes get annoyed at this behavior myself.  There are a lot
of people who are very vocal in support of returning none, and it makes
sense in some ways.  Since reversed returns an iterator though, it makes
this code horrible and unreadable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't python's list append() method return the list itself?

2010-07-11 Thread Thomas Jollans
On 07/11/2010 05:59 PM, dhruvbird wrote:
> Why doesn't python's list append() method return the list itself? For
> that matter, even the reverse() and sort() methods?
> I found this link (http://code.google.com/edu/languages/google-python-
> class/lists.html) which suggests that this is done to make sure that
> the programmer understands that the list is being modified in place,

Yes!

> but that rules out constructs like:
> ([1,2,3,4].reverse()+[[]]).reverse()

No!

you can either approach this by imperatively modifying a list in-place:

L = [1,2,3,4]
L.reverse()
L.append([])
L.reverse()

Or you can use a more functional style:

L2 = reversed(reversed([1,2,3,4]) + [[]])

(or ([1,2,3,4][::-1]+[[]])[::-1], if you like that kind of thing)

Imagine list.reverse and list.append *did* return self:

L1 = [1,2,3,4]
L2 = L1.reverse().append([]).reverse()

would you expect, after this code, that (L1 == L2) and (L1 is L2)? I
think it would surprise a lot of people. Better clearly separate
modifying an object and functionally processing an object.


Cheers

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


Re: grailbrowser now running under python 2.5 (probably above too)

2010-07-11 Thread rantingrick
On Jul 11, 9:01 am, a...@pythoncraft.com (Aahz) wrote:

> As usual, you would rather tell other people what to do instead of doing
> any work yourself.

Dear God! My statement was intended to fetch responses like...

  "Hey, that sounds like a great idea" or \
  "Hey, lets get hacking on this".

I am so sick of you people constantly accusing me of being lazy. You
don't even know me. Also i think you're really a bit jealous because i
have the brass cohones to initiate a coding project without your
express written permission. I will not allow myself to be brow beaten
by anyone!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: integer >= 1 == True and integer.0 == False is bad, bad, bad!!!

2010-07-11 Thread Michael Torrie
On 07/11/2010 12:50 AM, rantingrick wrote:
> Ah yes, when nothing else seems to work fall back to you default 
> programming... FUD and ad hominem attacks

Please stop calling things what they are not.  Stephen's post was not an
ad hominem attack, nor was it FUD.  Someone who is countering your
premise and position (IE disagrees with you) is not automatically
attacking your character or some characteristic of your person.

http://en.wikipedia.org/wiki/Ad_hominem#Common_misconceptions_about_ad_hominem

Kudos to Stephen for replying in such a reasonable and even logical
fashion to your post.  Would that you would reply to his posts in a
similar fashion, rather than leveling silly false accusations of "FUD
and ad hominem attacks."
-- 
http://mail.python.org/mailman/listinfo/python-list


Why doesn't python's list append() method return the list itself?

2010-07-11 Thread dhruvbird
Why doesn't python's list append() method return the list itself? For
that matter, even the reverse() and sort() methods?
I found this link (http://code.google.com/edu/languages/google-python-
class/lists.html) which suggests that this is done to make sure that
the programmer understands that the list is being modified in place,
but that rules out constructs like:
([1,2,3,4].reverse()+[[]]).reverse()
I want to prepend an empty list to [1,2,3,4]. This is just a toy
example, since I can always do that with [[]]+[1,2,3,4].

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


I wish for a tool named "2to6".

2010-07-11 Thread Zooko O'Whielacronx
Folks:

I have been (I admit it) a Python 3 skeptic. I even speculated that
the Python 3 backward-incompatibility would lead to the obsolescence
of Python:

http://pubgrid.tahoe-lafs.org/uri/URI:DIR2-RO:ixqhc4kdbjxc7o65xjnveoewym:5x6lwoxghrd5rxhwunzavft2qygfkt27oj3fbxlq4c6p45z5uneq/blog.html

However, things are really looking up now because it turns out that it
is eminently practical to support both Python 2 and Python 3 with a
single codebase.

There have been some recent discussions about that on this list. A few
references:

http://mail.python.org/pipermail/python-list/2010-July/1249312.html
http://www.voidspace.org.uk/python/weblog/arch_d7_2010_03_20.shtml#e1167
http://nedbatchelder.com/blog/200910/running_the_same_code_on_python_2x_and_3x.html
http://www.mail-archive.com/numpy-discuss...@scipy.org/msg26524.html

Benjamin Peterson has even written a library intended to help
programmers who want to do that:

http://packages.python.org/six/

This note to the list is to express my wish for an automated tool
named "2to6" which converts my Python 2.6 codebase to being both py2-
and py2- compatible using Benjamin Peterson's six library.

Regards,

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


Re: Naming Conventions, Where's the Convention Waldo?

2010-07-11 Thread News123
Andreas Waldenburger wrote:
> 
> Having capitalized boolean values ... that is a bit odd, but as long as
> children are starving in Africa, this isn't very high on my gripe-list.
> 
+1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to determine whether pathname1 is below bathname2

2010-07-11 Thread Gelonida
Hi Thomas,

Thomas Jollans wrote:
> On 07/11/2010 03:37 PM, Gelonida wrote:
>> #
>> import os
>> def is_below_dir(fname,topdir):
>> relpath = os.path.relpath(fname,topdir)
>> return not relpath.startswith('..'+os.sep)
>>
>> print is_below_dir(path1,path2)
>> #
>> The basic idea is, if the path name of path1
>> relative to path2 does NOT start with '..', then
>> it must be below path2
>>
>>
>> Does anybody see pitfalls with that solution?
>> Is there by any chance a function, that I overlooked,
>> which does already what I'd like to do?
> 
> It probably won't work on Windows because it isolates volumes (drive
> letters). What does, for example, os.path.relpath do when
> you pass r'c:\foo\bar', r'y:\drive\letters\are\silly' ? I see two
> reasonably correct options:
Thanks, Indeed. different drives raise an ecception.
I could catch the ValueError and let it just return False

> 
> either raise an exception (there is no relative path) or return the
> absolute path, which doesn't start with ..
> 
> On UNIX, the only potential problem I see is that it may or may not do
> what you expect when symlinks are involved somewhere.

Also true. In my case I'd prefer it would not follow, but
it doesn't really matter.


So my function in order to be portable
had now to look like:
#
import os
def is_below_dir(fname,topdir):
try:
   relpath = os.path.relpath(fname,topdir)
except ValueError:
return False
return not relpath.startswith('..'+os.sep)

print is_below_dir(path1,path2)
#

if I wanted to folow symlinks, then had to apply
os.path.realpath() on
fname AND on topdir


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


Re: Naming Conventions, Where's the Convention Waldo?

2010-07-11 Thread Andreas Waldenburger
On Sun, 11 Jul 2010 15:46:40 +0200 News123  wrote:

> Andre Alexander Bell wrote:
> > On 07/11/2010 10:30 AM, rantingrick wrote:
> 
> >>> So, it is not a disadvantage that the functions you listed above
> >>> are named in this way. In the contrary, it is an advantage, as it
> >>> keeps newcomers from using stupid variable names.
> >> "int" for an Integer is stupid?
> >> "list" for a List is stupid?
> >> "str" for a String is stupid?
> >>
> >> What am i missing?
> > 
> > [snip]
> 
> hm, well sometimes I do write generic functions, that do something
> with a list or a string or an int.
> 
> [snip]
> 
> I must admit, that I have still problems
> to not use the variables range or id
> 

There are several approaches:

- Use range_, id_, and so on. I think this is the proposed convention.
  Slightly ugly, though.
- Use abbreviations, or misspellings like lst, Set, klass, ... Less
  ugly, but can get weird.
- Prepend 'a' to a type name: alist, aset, astr. Similar weirdness
  potential as above, but more consistent in terms of style. I
  sometimes take this to the extreme and prepend 'some_'.

So really, this is a non issue, at least for me.

Having capitalized boolean values ... that is a bit odd, but as long as
children are starving in Africa, this isn't very high on my gripe-list.

/W

-- 
INVALID? DE!

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


  1   2   >