Overcharged

2011-06-11 Thread Ethan
I mad a call last night and never even talked to anybody, I knew I was being 
charged to just look and I'm ok with that amount u was charged. There was 
another charge though of I think 26 dollers witch I was not told or warned 
about at all, I need to know who I can call and talk to about this 

Sent from my Samsung Epic™ 4G
-- 
http://mail.python.org/mailman/listinfo/python-list


Python POS/cash register projects?

2010-01-11 Thread ethan
Anybody have any experience with creating a basic POS register system
in Python?  Any existing projects out there you are aware of?  This
would be a GUI app, standalone with some basic export and print
functions.  I see this as a great opportunity to deepen my Python
experience but dont want to reinvent the wheel completely..  doesn't
look like there is a lot out there..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode humor

2013-05-10 Thread Ethan Furman

On 05/10/2013 09:07 AM, rusi wrote:

On May 10, 8:32 pm, Chris Angelico  wrote:

On Sat, May 11, 2013 at 1:24 AM, Ned Batchelder  wrote:

On 5/10/2013 11:06 AM, jmfauth wrote:



On 8 mai, 15:19, Roy Smith  wrote:



Apropos to any of the myriad unicode threads that have been going on
recently:



http://xkcd.com/1209/



--



This reflects a lack of understanding of Unicode.



jmf



And this reflects a lack of a sense of humor.  :)


Isn't that a crime in the UK?

ChrisA


The problem with English humour (as against standard humor) is that
its not unicode compliant


Is so!  It fits inside the first 127 code points!!

As a bonus it also takes less brain power^H^H^H^H^H^H^H^H^H space.  ;)

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


Re: Writing a blog post on the new Enum.

2013-05-13 Thread Ethan Furman

On 05/13/2013 02:44 PM, Fábio Santos wrote:

I have followed the process of the new PEP closely, and as such I know
that there is a repository containing the reference implementation, a
link to which was posted on the python-dev list. Is it okay to link to
this repository in my new blog post about the Enum, so my readers can
try it out? I will warn my readers about it not being final and not to
use in production code.

I am unsure whether the repository is not supposed to be shared with
too many people.


I just checked my settings there, and it looks like you're okay since the folks reading your blog would just be 
downloading, not logging and directly manipulating the repository.


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


Re: @staticmethods called more than once

2013-05-21 Thread Ethan Furman

On 05/21/2013 08:39 AM, Skip Montanaro wrote:

Don't confuse the use of "static" in Python with its use in C/C++.  From a post 
on StackOverflow:

A staticmethod is a method that knows nothing about the class or instance 
it was called on. It just gets the
arguments that were passed, no implicit first argument. It is basically 
useless in Python -- you can just use a
module function instead of a staticmethod.


For there record, staticmethod is useful when you want to make it possible for 
subclasses to change behavior.

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


Re: PEP 378: Format Specifier for Thousands Separator

2013-05-21 Thread Ethan Furman

On 05/21/2013 12:06 PM, Chris “Kwpolska” Warrick wrote:

On Tue, May 21, 2013 at 8:49 PM, Carlos Nepomuceno wrote:


Thank you, but let me rephrase it. I'm already using str.format() but I'd like 
to use '%' (BINARY_MODULO) operator instead.


There is no real reason to do this.  `str.format()` is the new shiny
thing you should be using all the time.


.format() is useful, and has it's place, but % formatting is not going away.



So, the question is: Where would I change the CPython 2.7.5 source code to 
enable '%' (BINARY_MODULO) to format using the thousands separator like 
str.format() does, such as:

--> sys.stderr.write('%,d\n' % 1234567)
1,234,567


This will make your code unportable and useless, depending on one
patch you made.  Please don’t do that.


Agreed.  Unless you're willing to have your programs either run differently, or not at all, on other systems this is the 
wrong way to fix it.




Where did you learn Python from?  “Python Worst Practice for Dummies”?


Chris Warrick,

Was that necessary? Useful?  Helpful in any way?  If you can't be civil, keep 
your posts to yourself.

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


Re: Myth Busters: % "this old style of formatting will eventually be removed from the language"

2013-05-21 Thread Ethan Furman

On 05/21/2013 07:26 PM, Carlos Nepomuceno wrote:

I was looking for something else and just found what I think is the place where 
I was first exposed to the myth[1]:

"Since str.format() is quite new, a lot of Python code still uses the % operator. 
However, because this old style of formatting will eventually be removed from the 
language, str.format() should generally be used."

Is this tutorial outdated or this still an issue?


It was exuberant wishful thinking.  ;)

While .format() does have its uses, % is in wide-spread use even among the 
core-devs.  It's not going away any time soon.

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


Re: Non-identifiers in dictionary keys for **expression syntax

2013-05-23 Thread Ethan Furman

On 05/23/2013 12:20 PM, Neil Cerutti wrote:

On 2013-05-23, Matthew Gilson  wrote:


That's fine, but what is a keyword argument?  According to the glossary
(http://docs.python.org/3.3/glossary.html):

/"keyword argument/: an argument preceded by an identifier (e.g. name=)
in a function call or passed as a value in a dictionary preceded by **."

As far as I'm concerned, this leads to some ambiguity in
whether the keys of the mapping need to be valid identifiers or
not.


I don't see any ambiguity. A keyword argument is an argument
preceded by an identifier according to the definition. Where are
you perceiving wiggle room?


--> def func(**kwargs):
... print(kwargs)
...

--> d = {'foo bar baz':3}

--> func(**d)
{'foo bar baz': 3}

Even though 'foo bar baz' is not a valid identifier, and could not be passed as `func(foo bar baz = 3)`, it still worked 
when going through a dict.


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


Re: Short-circuit Logic

2013-05-30 Thread Ethan Furman

On 05/30/2013 05:58 AM, Chris Angelico wrote:

On Thu, May 30, 2013 at 10:40 PM, Roy Smith  wrote:

if somebody were to accidentally drop three zeros into the source code:


x = 1000
while x < 173:
 print(x)
 x += 1


should the loop just quietly not execute (which is what it will do
here)?  Will that make your program correct again, or will it simply
turn this into a difficult to find bug?  If you're really worried about
that, why not:


If you iterate from 1000 to 173, you get nowhere. This is the expected
behaviour; this is what a C-style for loop would be written as, it's
what range() does, it's the normal thing. Going from a particular
starting point to a particular ending point that's earlier than the
start results in no iterations. The alternative would be an infinite
number of iterations, which is far far worse.


If the bug is the extra three zeros (maybe it should have been two), 
then silently skipping the loop is the "far, far worse" scenario.  With 
the infinite loop you at least know something went wrong, and you know 
it pretty darn quick (since you are testing, right? ;).


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


Re: Short-circuit Logic

2013-05-30 Thread Ethan Furman

On 05/30/2013 08:56 AM, Chris Angelico wrote:

On Fri, May 31, 2013 at 1:02 AM, Ethan Furman  wrote:

On 05/30/2013 05:58 AM, Chris Angelico wrote:

If you iterate from 1000 to 173, you get nowhere. This is the expected
behaviour; this is what a C-style for loop would be written as, it's
what range() does, it's the normal thing. Going from a particular
starting point to a particular ending point that's earlier than the
start results in no iterations. The alternative would be an infinite
number of iterations, which is far far worse.


If the bug is the extra three zeros (maybe it should have been two), then
silently skipping the loop is the "far, far worse" scenario.  With the
infinite loop you at least know something went wrong, and you know it pretty
darn quick (since you are testing, right? ;).


You're assuming you can casually hit Ctrl-C to stop an infinite loop,
meaning that it's trivial. It's not. Not everything lets you do that;
or possibly halting the process will halt far more than you intended.
What if you're editing live code in something that's had uninterrupted
uptime for over a year? Doing nothing is much safer than getting stuck
in an infinite loop. And yes, I have done exactly that, though not in
Python. Don't forget, your start/stop figures mightn't be constants,
so you might not see it in testing. I can't imagine ANY scenario where
you'd actually *want* the infinite loop behaviour, while there are
plenty where you want it to skip the loop, and would otherwise have to
guard it with an if.


We're not talking about skipping the loop on purpose, but on accident. 
Sure, taking a system down is no fun -- on the other hand, how much data 
corruption can occur before somebody realises there's a problem, and 
then how long to track it down to a silently, accidently, skipped loop?


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


Re: Re-using copyrighted code

2013-06-10 Thread Ethan Furman

On 06/10/2013 05:57 AM, Robert Kern wrote:

On 2013-06-08 22:31, Malte Forkel wrote:

Hello,

I have written a small utility to locate errors in regular expressions
that I want to upload to PyPI.  Before I do that, I would like to learn
a litte more about the legal aspects of open-source software. What would
be a good introductory reading?


Larry Rosen's free (open source, even!) book _Open Source Licensing_ is good 
introductory reading. Larry is an
intellectual property lawyer and helped draft the current PSF license.

   http://www.rosenlaw.com/oslbook.htm


Nice, thanks for the link!

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


Re: My son wants me to teach him Python

2013-06-12 Thread Ethan Furman
While I agree with Chris that 3.x is best, there is a free class from Udacity that is actually pretty good, even if it 
does target Python2 (.7 I believe).


https://www.udacity.com/course/cs101

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


Re: "Don't rebind built-in names*" - it confuses readers

2013-06-12 Thread Ethan Furman

On 06/12/2013 05:04 PM, Mark Janssen wrote:

Steven D'Aprono wrote:


Apart from Erlang, got any other examples? Because it seems to me that in
languages with nested scopes or namespaces, shadowing higher levels is
exactly the right thing to do.


Really?

--> int="five"
--> [int(i) for i in ["1","2","3"]]
TypeError:  str is not callable

Now how are you going to get the original int type back?


--> del int

Mark Janssen*, you would increase your credibility if you actually *learned* 
Python.

--
~Ethan~

*full name used to distinguish from at least one other Mark on the list.
--
http://mail.python.org/mailman/listinfo/python-list


Re: My son wants me to teach him Python

2013-06-12 Thread Ethan Furman

On 06/12/2013 10:30 PM, Modulok wrote:


If he wants to learn game programming, teach him game programming.  [. . .]


Oh, that reminds me:

http://inventwithpython.com/

Which has a number of free books; the two of interest for your son being:

Invent Your Own Computer Games with Python

Making Games with Python & Pygame

Both are for Python 3.x.

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


Re: My son wants me to teach him Python

2013-06-13 Thread Ethan Furman

On 06/13/2013 06:23 PM, Steven D'Aprano wrote:


I consider IDEs to be an attractive nuisance. It's like learning to be a
chef by putting food in a microwave and pushing the pre-set buttons.


+1 QOTW
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is the semantics meaning of 'object'?

2013-06-26 Thread Ethan Furman

On 06/23/2013 12:05 PM, Ian Kelly wrote:

On Sun, Jun 23, 2013 at 12:46 PM, Steven D'Aprano
 wrote:

All is not lost, there are ways to make your classes cooperative. The
trick is to have your classes' __init__ methods ignore keyword arguments
they don't know what to do with. object used to do the same thing, but it
no longer does, so you need to add an extra class just before object to
swallow any args before they read object.


class Blocker(object):
 def __init__(self, **kwargs):
 # Block kwargs from reaching object
 super(Blocker, self).__init__()


I don't like the idea of doing this with a cooperative __init__
method.  If any keyword arguments were passed that weren't consumed,
that is probably a bug, and this just swallows the exception instead
of reporting it.


+1

Z

Of course, if you're doing cooperative inheritance with some other
method that doesn't exist on object, then this technique is necessary
to prevent the topmost class from trying to call that method on object
and erroring out.


But in that case the Blocker wouldn't call super since it is acting as the base 
class.

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


Re: What is the semantics meaning of 'object'?

2013-06-26 Thread Ethan Furman

On 06/23/2013 11:50 AM, Steven D'Aprano wrote:

On Sun, 23 Jun 2013 12:04:35 -0600, Ian Kelly wrote:


On Sun, Jun 23, 2013 at 11:36 AM, Steven D'Aprano
 wrote:

On Sun, 23 Jun 2013 11:18:41 -0600, Ian Kelly wrote:


Incidentally, although super() is useful, it's not perfect, and this
is one of my grievances with it: that a user can, based upon the name,
draw an inaccurate assumption about what it does without reading or
fully understanding the documentation on it, which might then result
in misusing it.


Wait a second... are you saying that the Python developers created an
advanced language feature relating to multiple inheritance, one of the
most complex OOP concepts around, so difficult that most other
languages simply prohibit it completely, and it wasn't instantly and
correctly intuited by every single programmer based only on the name?
Oh my stars, somebody call Ranting Rick, he needs to write a PyWart
post to expose this scandal!!!


Mostly I'm saying that super() is badly named.



What else would you call a function that does lookups on the current
object's superclasses?


Well, I would call it super().  Trouble is, that is not all that super() does.  
Going back to Ian's example:


On 06/23/2013 10:08 AM, Ian Kelly wrote:


class Base1(object):
def __init__(self, foo, **kwargs):
   super(Base1, self).__init__(**kwargs)

class Base2(object):
def __init__(self, bar, **kwargs):
   super(Base2, self).__init__(**kwargs)

class Derived(Base1, Base2):
def __init__(self, **kwargs):
   super(Derived, self).__init__(**kwargs)


Notice how Base1 calls super(), but depending on circumstances, it could by Base2 that super() calls.  Surely you are 
not suggesting that Base2 is therefore an ancestor of Base1?


It's too late to change the name now, but pretending there is no good and valid 
reason for confusion doesn't help.

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


Re: What is the semantics meaning of 'object'?

2013-06-26 Thread Ethan Furman

On 06/26/2013 04:54 PM, Steven D'Aprano wrote:

On Wed, 26 Jun 2013 13:14:44 -0700, Ethan Furman wrote:


On 06/23/2013 11:50 AM, Steven D'Aprano wrote:



What else would you call a function that does lookups on the current
object's superclasses?


Well, I would call it super().  Trouble is, that is not all that super()
does.  Going back to Ian's example:


On 06/23/2013 10:08 AM, Ian Kelly wrote:


class Base1(object):
 def __init__(self, foo, **kwargs):
super(Base1, self).__init__(**kwargs)

class Base2(object):
 def __init__(self, bar, **kwargs):
super(Base2, self).__init__(**kwargs)

class Derived(Base1, Base2):
 def __init__(self, **kwargs):
super(Derived, self).__init__(**kwargs)


Notice how Base1 calls super(), but depending on circumstances, it could
by Base2 that super() calls.  Surely you are not suggesting that Base2
is therefore an ancestor of Base1?


No. But "the current object" is not Base1, but an instance of Derived,
and Base2 *is* an ancestor of Derived. Perhaps if I had said "self"
instead of current object, you wouldn't have made this error. If so, I
apologise for confusing you.


No apology necessary.  I understand both inheritance and super fairly well, and 
you did not confuse me.



When your inheritance chain begins from an instance of Base1, Base2
methods will never be called. It is only when the chain begins from
Derived that Base2 may be called, which is exactly as it should be.


Absolutely.  That doesn't change the fact that when writing Base1 you are still using the word 'super', and hopefully 
remembering that even though it's named 'super' it may in fact call an object that is sideways from where you're at now 
and have absolutely no relation to Base1's ancestors.




It's too late to change the name now, but pretending there is no good
and valid reason for confusion doesn't help.


The confusion is not with the name, or what super does, but with
inheritance itself.


Good names are important because a good name can help alleviate confusion.  A bad name can exacerbate it.  Given the 
terminology of superclasses and subclasses, naming a function 'super' that can in fact call another class that is in no 
way the superclass of the class in which it is written, can easily cause confusion.


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


Re: Why is the argparse module so inflexible?

2013-06-27 Thread Ethan Furman

On 06/27/2013 11:39 AM, Terry Reedy wrote:

On 6/27/2013 2:18 PM, Dave Angel wrote:

On 06/27/2013 02:05 PM, Terry Reedy wrote:

On 6/27/2013 8:54 AM, Andrew Berg wrote:

I've begun writing a program with an interactive prompt, and it needs
to parse input from the user.  I thought the argparse module would be
great for this,


It is outside argparse's intended domain of application -- parsing
command line arguments. The grammar for a valid string of command line
arguments is quite restricted.

Argparse is not intended for interactive processing of a domain-specific
language (DSL). There are other parsers for that. But if the grammar for
your DSL is restricted to what argparse can handle, using it is an
interesting idea. But you need non-default usage for the non-default
context.

 > but unfortunately it insists on calling sys.exit() at

any sign of trouble instead of letting its ArgumentError exception
propagate so that I can handle it.


When one tell argparse that something is *required*, that means "I do
not want to see the user's input unless it passes this condition." After
seeing an error message, the user can edit the command line and re-enter.

If you do not mean 'required' in the sense above, do not say so.
Catching SystemExit is another way to say 'I did not really mean
required, in the usual mean of that term.'.



That last sentence is nonsense.


Not if you understand what I said.


If one is parsing the line the user  enters via raw_input(),


input(), in 3.x


catching SystemExit so the program doesn't abort
is perfectly reasonable.  The user should be returned to his prompt,
which in this case is probably another loop through raw_input().


Right, because 'required' means something a little different in the interactive 
context.

I don't know if all the information in the original ArgumentError exception is 
transferred to the SystemExit exception.
I expect not, and if so, and if multiple people are using argparse this way, it 
would be reasonable to request on the
tracker that its current sys.exit behavior become default but optional in 3.4+. 
There might even be an issue already if
one searched.


If the OP is writing an interactive shell, shouldn't `cmd` be used instead of `argparse`?  argparse is, after all, 
intended for argument parsing of command line scripts, not for interactive work.


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


Re: Problems with subclassing enum34

2013-06-28 Thread Ethan Furman

On 06/28/2013 03:48 AM, Thomas Heller wrote:

trying out the enum34 module.

What I want to create is a subclass of enum.Enum that is also
based on ctypes.c_int so that I can better use enum instances
in ctypes api calls.


Have you tried using enum.IntEnum?  If you were able to pass ints in before, 
IntEnum should work.

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


Re: Problems with subclassing enum34

2013-06-28 Thread Ethan Furman

On 06/28/2013 08:32 AM, Thomas Heller wrote:

Am 28.06.2013 17:25, schrieb Thomas Heller:

Robert Kern:



enum.EnumMeta uses super() in its __new__() implementation but
_ctypes.PyCSimpleType doesn't. Thus, only
_ctypes.PyCSimpleType.__new__() gets a chance to run. Switching the
order of the two might work.



Robert found the problem but I'm unsure if there is a solution.
Also I'm unsure whether this is a bug in ctypes or in enum or if
they are simply incompatible.


I forgot to mention that switching the order of metaclasses didn't work.


Here's the traceback:

Traceback (most recent call last):
  File "ct.py", line 7, in 
class MyEnum(ctypes.c_int, Enum):
  File "/home/ethan/source/enum/enum/py2_enum.py", line 149, in __new__
enum_class = super(EnumMeta, metacls).__new__(metacls, cls, bases, 
classdict)
TypeError: Error when calling the metaclass bases
_ctypes.PyCSimpleType.__new__(MyEnum_meta) is not safe, use type.__new__()

Not sure how to fix that.

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


Re: Why is the argparse module so inflexible?

2013-06-28 Thread Ethan Furman

On 06/27/2013 03:49 PM, Steven D'Aprano wrote:


[rant]
I think it is lousy design for a framework like argparse to raise a
custom ArgumentError in one part of the code, only to catch it elsewhere
and call sys.exit. At the very least, that ought to be a config option,
and off by default.

Libraries should not call sys.exit, or raise SystemExit. Whether to quit
or not is not the library's decision to make, that decision belongs to
the application layer. Yes, the application could always catch
SystemExit, but it shouldn't have to.


So a library that is explicitly designed to make command-line scripts easier 
and friendlier should quit with a traceback?

Really?

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


Re: Why is the argparse module so inflexible?

2013-06-29 Thread Ethan Furman

On 06/28/2013 10:28 PM, Steven D'Aprano wrote:


I'm willing to concede that, just maybe, something like argparse could
default to "catch exceptions and exit" ON rather than OFF.


On this we can agree.  :)

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


Re: Default scope of variables

2013-07-07 Thread Ethan Furman

On 07/07/2013 06:43 AM, Chris Angelico wrote:

On Sun, Jul 7, 2013 at 11:13 PM, Wayne Werner  wrote:

Which you would then use like:


conn = create_conn()
with new_transaction(conn) as tran:
  rows_affected = do_query_stuff(tran)
  if rows_affected == 42:
   tran.commit()


Yep. There's a problem, though, when you bring in subtransactions. The
logic wants to be like this:


Is there some reason you can't simply do this?

 with new_transaction(conn) as tran1:
  tran1.query("blah")
  with tran1.subtransaction() as tran2:
  tran2.query("blah")
  with tran2.subtransaction() as tran3:
  tran3.query("blah")
  # roll this subtransaction back
  tran2.query("blah")
  tran2.commit()
  tran1.query("blah")
  tran1.commit()

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


Re: Default scope of variables

2013-07-07 Thread Ethan Furman

On 07/07/2013 06:43 AM, Chris Angelico wrote:


The 'with' statement doesn't allow this. I would need to use some kind
of magic to rebind the old transaction to the name, or else use a list
that gets magically populated:

with new_transaction(conn) as tran:
 tran[-1].query("blah")
 with subtransaction(tran):
 tran[-1].query("blah")
 with subtransaction(tran):
 tran[-1].query("blah")
 # roll this subtransaction back
 tran[-1].query("blah")
 tran[-1].commit()
 tran[-1].query("blah")
 tran[-1].commit()


The other option is to build the magic into the new_transaction class, then 
your code will look like:

 with new_transaction(conn) as tran:
  tran.query("blah")
  with tran.subtransaction():
  tran.query("blah")
  with tran.subtransaction():
  tran.query("blah")
  # roll this subtransaction back
  tran.query("blah")
  tran.commit()
  tran.query("blah")
  tran.commit()

This would definitely make more sense in a loop.  ;)

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


Re: A small question about PEP 8

2013-07-08 Thread Ethan Furman

On 07/08/2013 03:39 AM, Joshua Landau wrote:

On 8 July 2013 00:32, Xue Fuqiao  wrote:

Hi all,

(English is not my native language; please excuse typing errors.)

I'm a Python newbie and just started reading PEP 8.  PEP says:

---
|The closing brace/bracket/parenthesis on multi-line constructs may
|either line up under the last item of the list, as in:
|
|my_list = [
|1, 2, 3,
|4, 5, 6,
|]
|result = some_function_that_takes_arguments(
|'a', 'b', 'c',
|'d', 'e', 'f',
|)
---

I think the last item in my_list/result is 6/'f', respectively.  So why
doesn't the bracket/paren line up _under_ the last item?  ISTM the code
isn't consistent with the description.

I have searched the archive of c.l.p and the web, but nothing helped.
Can anyone point me in the right direction?


You will grow to be a wonderful pedant. What it means is that the
indentation will match the last one. Imagine:

"""
a_wonderful_set_of_things = {
 bannanas_made_of_apples,
 chocolate_covered_horns,
 doors_that_slide,
 china_but_on_the_moon,
 buffalo_with_windy_hair,
 not_missing_an_end_brace
"""¹

Now, there are several places you can put the end brace. You can (be a
massive fool and) put it after the last item:

"""
a_wonderful_set_of_things = {
 ...,
 not_missing_an_end_brace}
"""

You can also (be a fool and) put it at the same *indentation*:

"""
a_wonderful_set_of_things = {
 ...,
 not_missing_an_end_brace
 }
"""


Not only a fool but a crazy fool!  That next-to-last line should have a comma!

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


Re: Default scope of variables

2013-07-09 Thread Ethan Furman

On 07/09/2013 01:38 AM, Frank Millman wrote:


"Ian Kelly"  wrote in message
news:CALwzid=fzgjpebifx1stdbkh8iwltwggwwptphz1ykyg+05...@mail.gmail.com...

On Tue, Jul 9, 2013 at 1:35 AM, Frank Millman  wrote:

When any of them need any database access, whether for reading or for
updating, they execute the following -

 with db_session as conn:
 conn.transaction_active = True  # this line must be added if
updating
 conn.cur.execute(__whatever__)


I'd probably factor out the transaction_active line into a separate
DbSession method.

@contextmanager
def updating(self):
with self as conn:
conn.transaction_active = True
yield conn

Then you can do "with db_session" if you're merely reading, or "with
db_session.updating()" if you're writing, and you don't need to repeat
the transaction_active line all over the place.



I'll bear it in mind, but I will have to expend some mental energy to
understand it first , so it will have to wait until I can find some time.


You could also do it like this:

def updating(self):
self.transaction_active = True
return self

and a sample object:

class Tester(object):
def __init__(self):
self.transaction_active = False
print 'initializied'
def __enter__(self, *args):
print '__enter__: transaction_active =', self.transaction_active
return self
def __exit__(self, *args):
self.transaction_active = False
print '__exit__: transaction_active =', self.transaction_active
return
def updating(self):
self.transaction_active = True
print 'updating: self.transaction_active =', self.transaction_active
return self

with Tester() as conn:
print 'in first with block'

print '-' * 50

with Tester().updating() as conn:
print 'in second with block'

with it's test run:

ethan@hydra:~$ python test_cm.py
initialized
__enter__: transaction_active = False
in first with block
__exit__: transaction_active = False
--
initialized
updating: self.transaction_active = True
__enter__: transaction_active = True
in second with block
__exit__: transaction_active = False

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


Re: Help with 'self' and 'set_usage'

2013-07-09 Thread Ethan Furman

On 07/09/2013 10:03 AM, L O'Shea wrote:


Hi all,


Howdy!


I'm interning and have been given the job of extending a program that has been 
written by someone else. I've never used Python before so it's a bit of a 
struggle but I've got to say I'm loving the language so far.


Excellent way to start a question!  :)



In one of the scripts there is

def set_usage(self,s):
self.usage_str = s


Careful of whitespace when posting (I fixed that one for you).



Can you just create variables in that object by writing self.name = "david" self.hobby = 
"fishing"??


Yup, you sure can.

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


Re: Default scope of variables

2013-07-09 Thread Ethan Furman

On 07/09/2013 09:44 AM, Ian Kelly wrote:

On Tue, Jul 9, 2013 at 10:07 AM, Ethan Furman  wrote:

You could also do it like this:

 def updating(self):
 self.transaction_active = True
 return self


Yes, that would be simpler.  I was all set to point out why this
doesn't work, and then I noticed that the location of the
"transaction_active" attribute is not consistent in the original code.
  The DbSession class places it on self, and then the example usage
places it on the connection object


It looks like DbSession has a conn object, and in the example he has DbSession() named as conn -- ironic, considering 
this is a variable scoping thread.  ;)


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


Re: Default scope of variables

2013-07-09 Thread Ethan Furman

On 07/09/2013 11:41 AM, Ian Kelly wrote:

On Tue, Jul 9, 2013 at 11:23 AM, Ethan Furman  wrote:

On 07/09/2013 09:44 AM, Ian Kelly wrote:


On Tue, Jul 9, 2013 at 10:07 AM, Ethan Furman  wrote:


You could also do it like this:

  def updating(self):
  self.transaction_active = True
  return self



Yes, that would be simpler.  I was all set to point out why this
doesn't work, and then I noticed that the location of the
"transaction_active" attribute is not consistent in the original code.
   The DbSession class places it on self, and then the example usage
places it on the connection object



It looks like DbSession has a conn object, and in the example he has
DbSession() named as conn -- ironic, considering this is a variable scoping
thread.  ;)


The object returned by __enter__ is the conn object, not the
DbSession, so naming it "conn" is correct.



Huh.  I didn't realize a different object could be returned by __enter__ without affecting which object's __exit__ gets 
called.  Thanks for the lesson!  :)


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


Re: Recursive class | can you modify self directly?

2013-07-09 Thread Ethan Furman

On 07/09/2013 03:01 PM, Russel Walker wrote:


This is a simplified example of what I want to do:


# THIS DOESN'T WORK
from random import choice

class Expr(object):
 """
 Expr(expr, op, val) -> an expression object.
 """

 def __init__(self, expr, op='', val=''):
 self.expr = expr # can be another instance of Expression.
 self.op = op
 self.val = val

 def __str__(self):
 return ("%s %s %s" % (self.expr, self.op, self.val)).strip()

 def expand(self):
 self = Expr(self, choice('+-*/'), choice('12345'))


`self` is just a name.  In `expand()` you are rebinding the name `self` away from the object and to a new Expr instance. 
 If you want to change `self` the original object you have to do something like:


def expand(self):
self.op = choice('+-*/')
self.val = choice('12345')

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


Re: Default scope of variables

2013-07-10 Thread Ethan Furman

On 07/09/2013 10:54 PM, Frank Millman wrote:


"Ian Kelly"  wrote in message
news:calwzidnf3obe0enf3xthlj5a40k8hxvthveipecq8+34zxy...@mail.gmail.com...

On Tue, Jul 9, 2013 at 10:07 AM, Ethan Furman  wrote:

You could also do it like this:

 def updating(self):
 self.transaction_active = True
 return self


Yes, that would be simpler.  I was all set to point out why this
doesn't work, and then I noticed that the location of the
"transaction_active" attribute is not consistent in the original code.
The DbSession class places it on self, and then the example usage
places it on the connection object (which I had based my version on).
Since that seems to be a source of confusion, it demonstrates another
reason why factoring this out is a good thing.


You had me worried there for a moment, as that is obviously an error.

Then I checked my actual code, and I find that I mis-transcribed it. It
actually looks like this -

 with db_session as conn:
 db_session.transaction_active = True
 conn.cur.execute(...)

I am still not quite sure what your objection is to this. It feels
straightforward to me.

Here is one possible answer. Whenever I want to commit a transaction I have
to add the extra line. There is a danger that I could mis-spell
'transaction_active', in which case it would not raise an error, but would
not commit the transaction, which could be a hard-to-trace bug. Using your
approach, if I mis-spelled 'db_session.connect()', it would immediately
raise an error.

Is that your concern, or are there other issues?


That concern is big enough.  I've been bitten by that type of thing enough in my own code to want to avoid it where 
possible.  Plus the `with db_session.updating() as conn:` saves keystrokes.  ;)


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


Re: Stack Overflow moderator “animuson”

2013-07-10 Thread Ethan Furman

On 07/10/2013 08:54 AM, Joshua Landau wrote:

On 10 July 2013 10:00, Steven D'Aprano  wrote:

On Wed, 10 Jul 2013 07:55:05 +, Mats Peterson wrote:


A moderator who calls himself “animuson” on Stack Overflow doesn’t want
to face the truth. He has deleted all my postings regarding Python
regular expression matching being extremely slow compared to Perl.


That's by design. We don't want to make the same mistake as Perl, where
every problem is solved by a regular expression:

http://neilk.net/blog/2000/06/01/abigails-regex-to-test-for-prime-numbers/

so we deliberately make regexes as slow as possible so that programmers
will look for a better way to solve their problem. If you check the
source code for the re engine, you'll find that for certain regexes, it
busy-waits for anything up to 30 seconds at a time, deliberately wasting
cycles.


I hate to sound like this but do you realise that this is exactly what
you're arguing for when saying that sum() shouldn't use "+="?


my_obj = SomeKoolClass()
my_obj.modify_in_some_kool_way()
new_result = sum([SKC1, SKC2, SKC3], my_obj)

Guess what?  You've just changed my_obj.

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


Python 3: dict & dict.keys()

2013-07-23 Thread Ethan Furman

Back in Python 2.x days I had a good grip on dict and dict.keys(), and when to 
use one or the other.

Then Python 3 came on the scene with these things called 'views', and while range couldn't be bothered, dict jumped up 
and down shouting, "I want some!"


So now, in Python 3, .keys(), .values(), even .items() all return these 'view' 
thingies.

And everything I thought I knew about when to use one or the other went out the 
window.

For example, if you need to modify a dict while iterating over it, use .keys(), 
right?  Wrong:

--> d = {1: 'one', 2:'two', 3:'three'}
--> for k in d.keys():
...   if k == 1:
... del d[k]
...
Traceback (most recent call last):
  File "", line 1, in 
RuntimeError: dictionary changed size during iteration


If you need to manipulate the keys (maybe adding some, maybe deleting some) before doing something else with final key 
collection, use .keys(), right?  Wrong:


--> dk = d.keys()
--> dk.remove(2)
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'dict_keys' object has no attribute 'remove'


I understand that the appropriate incantation in Python 3 is:

--> for k in list(d)
......

or

--> dk = list(d)
--> dk.remove(2)

which also has the added benefit of working the same way in Python 2.

So, my question boils down to:  in Python 3 how is dict.keys() different from 
dict?  What are the use cases?

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


Re: Python 3: dict & dict.keys()

2013-07-24 Thread Ethan Furman

On 07/24/2013 05:51 AM, Oscar Benjamin wrote:


On Jul 24, 2013 7:25 AM, "Peter Otten" <__pete...@web.de 
<mailto:pete...@web.de>> wrote:


Ethan Furman wrote:

> So, my question boils down to:  in Python 3 how is dict.keys() different
> from dict?  What are the use cases?

I just grepped through /usr/lib/python3, and could not identify a single
line where some_object.keys() wasn't either wrapped in a list (or set,
sorted, max) call, or iterated over.

To me it looks like views are a solution waiting for a problem.


What do you mean? Why would you want to create a temporary list just to iterate 
over it explicitly or implicitly (set,
sorted, max,...)?


You wouldn't.  But you don't need .keys() for that either as you can just use 
the dict itself.

My point is that in 2.x .keys() did something different from the dict, while in 
3.x it appears to me that they are the same.

Peter's point is that in the stdlib the new functionality of .keys() is never 
used, not even once.

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


Re: Python 3: dict & dict.keys()

2013-07-24 Thread Ethan Furman

On 07/24/2013 10:23 AM, Stefan Behnel wrote:

Peter Otten, 24.07.2013 08:23:

Ethan Furman wrote:


So, my question boils down to:  in Python 3 how is dict.keys() different
from dict?  What are the use cases?


To me it looks like views are a solution waiting for a problem.


They reduce the API overhead. Previously, you needed values() and
itervalues(), with values() being not more than a special case of what
itervalues() provides anyway. Now it's just one method that gives you
everything. It simply has corrected the tradeoff from two special purpose
APIs to one general purpose API, that's all.


I started this thread for two reasons:

  1) Increase awareness that using `list(dict)` is a cross-version replacement 
for `dict.keys()`

  2) Hopefully learn something about when a view is useful.

So far #2 is pretty much a failure.  Only one use-case so far (and it feels pretty rare).  But hey, I have learned that 
while some set operations are allowed (&, ^, |, .isdisjoint()), others are not (.remove(), .discard(), .union(), etc.).


The old .keys(), .values(), and .items() (and their .iter...() variations) did something commonly useful.  Of what 
common use are these views?


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


Re: Python 3: dict & dict.keys()

2013-07-24 Thread Ethan Furman

On 07/24/2013 12:59 PM, Stefan Behnel wrote:


I think the question is: how else would you implement an interface that
doesn't restrict itself to returning a list? I mean, previously, the
following was totally inefficient in terms of memory:

 value in d.values()

It now avoids creating an intermediate list copy of the values, thus
running with no additional memory overhead (well, a constant, ok, but
definitely not linear) and keeps users from resorting to the much more
unfriendly

 for v in d.itervalues():
 if v == value:
 return True
 else:
 return False

in order to achieve the same thing. You can now even efficiently do this
for items, i.e.

 (key, value) in d.items()

That's equivalent to "d[key] == value", but uses a different protocol,
meaning that you don't have to make a copy of the dict items in order to
pass it into something that works on a set or iterable of 2-tuples (which
is a way more generic interface than requiring a dict as input). These
things chain much more cleanly now, without first having to explain the
difference between items() and iteritems() and when to use which.

It's all about replacing the old copy-to-list interface by something that
is efficiently processable step by step. All of this started back when
iterators became a part of the language, then generators, and now dict
views. They may not be the hugest feature ever, but they definitely fit
into the language much better and much more cleanly than the old
copy-to-list way.


Thank you. :)

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


Re: Python 3: dict & dict.keys()

2013-07-24 Thread Ethan Furman

On 07/24/2013 01:34 PM, Prasad, Ramit wrote:


I am still not clear on the advantage of views vs. iterators. What
makes d.viewkeys() better than d.iterkeys()? Why did they decide
not to rename d.iterkeys() to d.keys() and instead use d.viewkeys()?
Is the iteration over a set operation on keys really that common a
use case?


From a practical standpoint, iterkeys() is a one-shot deal, while viewkeys() 
can be iterated over multiple times:

--> d = {1: 'one', 2: 'two', 3: 'three'}

--> di = d.iterkeys()

--> list(di)
[1, 2, 3]

--> list(di)
[]

--> dv = d.viewkeys()

--> list(dv)
[1, 2, 3]

--> list(dv)
[1, 2, 3]

And views are not sets -- they just support a couple set-like operations.

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


Re: Python 3: dict & dict.keys()

2013-07-24 Thread Ethan Furman

On 07/23/2013 07:11 PM, Steven D'Aprano wrote:

On Tue, 23 Jul 2013 18:16:08 -0700, Ethan Furman wrote:


So now, in Python 3, .keys(), .values(), even .items() all return these
'view' thingies.

And everything I thought I knew about when to use one or the other went
out the window.


Surely not. The fundamental behaviour of Python's data model hasn't
changed.


Poetic effect.  Dramatic license.  Blah blah.  ;)



Repeat after me: "In Python 2, d.keys() returns a list of keys, so if I
want a list of keys in Python 3, call list explicitly list(d.keys())."


Actually, I would recommend `list(d)`, which also works the same in both 2 and 
3.

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


Re: Python 3: dict & dict.keys()

2013-07-25 Thread Ethan Furman

On 07/24/2013 11:01 PM, alex23 wrote:

On 25/07/2013 4:31 AM, Ethan Furman wrote:

   2) Hopefully learn something about when a view is useful.


I haven't seeen this mentioned - forgive me if it's a repeat - but views are 
constant references to whichever set they
represent.

Python 2.7:


dd = dict(a=1,b=2,c=3)
keys = dd.keys()
'a' in keys

True

dd['d'] = 4
'd' in keys

False

Python 3.3:

dd = dict(a=1,b=2,c=3)
keys = dd.keys()
'a' in keys

True

dd['d'] = 4
'd' in keys

True

If part of my code is only interested in what keys or values are present, it 
doesn't need to be given a reference to the
full dictionary, just to whichever view it cares about.


In these cases why is a view better than just using the dict?  Is it a safety 
so the you don't accidentally modify the dict?

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


Re: Python 3: dict & dict.keys()

2013-07-25 Thread Ethan Furman

On 07/24/2013 10:48 PM, Steven D'Aprano wrote:

On Wed, 24 Jul 2013 08:57:11 -0700, Ethan Furman wrote:


My point is that in 2.x .keys() did something different from the dict,
while in 3.x it appears to me that they are the same.


Then you aren't looking very closely.


Actually, I am.  That's why I started this thread.

Thank you for the insights.

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


Re: Python 3: dict & dict.keys()

2013-07-25 Thread Ethan Furman

On 07/25/2013 09:11 AM, Prasad, Ramit wrote:

Terry Reedy wrote:


On 7/24/2013 4:34 PM, Prasad, Ramit wrote:


I am still not clear on the advantage of views vs. iterators.


A1: Views are iterables that can be iterated more than once. Therefore,
they can be passed to a function that re-iterates its inputs, or to
multiple functions. They support 'x in view' as efficiently as possible.
Think about how you would write the non-view equivalent of '(0,None) in
somedict.views())'. When set-like, views support some set operations.
For .keys, which are always set-like, these operations are easy to
implement as dicts are based on a hashed array of keys.


Hmm, that is a change that makes some sense to me. Does the view
get updated when dictionary changes or is a new view needed? I
assume the latter.


Nope, the former.  That is a big advantage that the views have over concrete lists: they show the /current/ state, and 
so are always up-do-date.


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


Re: [Savoynet] G&S Opera Co: Pirates of Penzance

2013-07-28 Thread Ethan Furman

On 07/28/2013 10:57 AM, Chris Angelico wrote:
   .
   .
   .

Okay, how did you get confused that this was a Python List question?  ;)

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


MyOpenID.com no longer supported

2013-07-29 Thread Ethan Furman

Excerpt from http://meta.stackoverflow.com/q/190442/176681:

Janrain no longer actively supports MyOpenID, and announced on Twitter that 
their users should proceed with caution.

This decision was made by Janrain, [snip]

I know the Python bug tracker allows MyOpenID logins; if that is your only login method you should add another that 
doesn't depend on MyOpenID.


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


Re: MyOpenID.com no longer supported

2013-07-29 Thread Ethan Furman

On 07/29/2013 02:11 AM, Antoine Pitrou wrote:

Le Mon, 29 Jul 2013 00:55:53 -0700,
Ethan Furman  a écrit :

Excerpt from http://meta.stackoverflow.com/q/190442/176681:

Janrain no longer actively supports MyOpenID, and announced on
Twitter that their users should proceed with caution.

This decision was made by Janrain, [snip]

I know the Python bug tracker allows MyOpenID logins; if that is your
only login method you should add another that doesn't depend on
MyOpenID.


I don't understand. The tracker allows any (sufficently compliant)
OpenID provider, not just "MyOpenID" or
"MyCorporateOpenIDWithTrademarks".


That is true, but if your OpenID provider is MyOpenID (as mine was) then it 
would be wise to get another.

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


Re: Bitwise Operations

2013-07-29 Thread Ethan Furman

On 07/29/2013 04:34 PM, Devyn Collier Johnson wrote:


On 07/29/2013 05:53 PM, Grant Edwards wrote:

On 2013-07-29, Devyn Collier Johnson  wrote:


On Python3, how can I perform bitwise operations? For instance, I want
something that will 'and', 'or', and 'xor' a binary integer.

http://www.google.com/search?q=python+bitwise+operations


I understand the symbols. I want to know how to perform the task in a script or 
terminal. I have searched Google, but I
never saw a command. Typing "101 & 010" or "x = (int(101, 2) & int(010, 2))" 
only gives errors.


x = (int('101', 2) & int('010', 2))

Notice the quotes.

In the future you'll better answers quicker if you tell us what you did (such 
as your example above) as well as the errors.

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


Re: OrderedEnum examples

2013-07-30 Thread Ethan Furman

On 07/30/2013 11:18 AM, Bas van der Wulp wrote:

Using the enum34 0.9.13 package from PyPi in Python 2.7.3, the examples for 
OrderedEnum seem to be broken.


Thanks for catching that, I'll get it fixed asap.



Also, in the example in the Python 3.4 library documentation (section 8.17.2) 
has the __ordered__ attribute removed
(presumably because, in contrast to Python 2.x, Python 3 will respect the order 
of attribute definition).


Correct.  In 3.4 __ordered__ never came into being as it was not necessary.  I added that purely so that 2.x could be 
ordered if desired.



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


Re: OrderedEnum examples

2013-07-30 Thread Ethan Furman

On 07/30/2013 11:38 AM, Ethan Furman wrote:


Thanks for catching that, I'll get it fixed asap.


Latest code is on PyPI.

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


Re: OrderedEnum examples

2013-07-30 Thread Ethan Furman

On 07/30/2013 11:58 AM, Ian Kelly wrote:

On Tue, Jul 30, 2013 at 12:18 PM, Bas van der Wulp  wrote:

Replacing each occurrence of self._value with either self._value_ or
self.value in the examples seems to make them work as expected.

Are both examples incorrect, or not intended to work in Python 2.x?


The _value attribute was renamed _value_ in:

http://hg.python.org/cpython/rev/511c4daac102

It looks like the example wasn't updated to match.  You should
probably just use self.value here since the name of the private
attribute is an implementation detail.


In `__new__` it has to be `_value_`, but in the other methods `.value` works 
fine.  Updated the 3.4 example with `.value`.

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


Re: exception problem

2012-06-28 Thread Ethan Furman

Charles Hixson wrote:

On 06/25/2012 12:48 AM, Steven D'Aprano wrote:

"Catch any exception" is almost certainly the wrong thing to do, almost
always.
   

This time it was the right thing


No, it wasn't.  If you hadn't caught it, Python would have printed it 
out for you, along with the full trace-back, giving you most if not all 
the information you needed to track down the bug.


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


Re: I can't send images to this mail-list

2012-06-29 Thread Ethan Furman

Ben Finney wrote:

Chris Angelico writes:

梦幻草 wrote:

why can't I send images to python-list@python.org??

>>

It's a text-only list.


I'll take this opportunity to give heartfelt thanks to the
administrators for that policy; please keep this a text-only forum.


+1000

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


Re: Question about weakref

2012-07-06 Thread Ethan Furman

Ian Kelly wrote:

def del_b(self, b):
for i, x in enumerate(self.array):
if b is x:
del self.array[i]
break


Nice work, Ian.
--
http://mail.python.org/mailman/listinfo/python-list


API design question for dbf.py

2012-07-06 Thread Ethan Furman

I'm looking for some free advice.  ;)

My dbf module has three basic containers, all of which support list-like 
access:  Table, List, and Index, each of which is filled with _DbfRecords.


The fun part is that a _DbfRecord can compare equal to another 
_DbfRecord, a _DbfRecordTemplate, a tuple with the same values in the 
same locations, or a dict with the same keys/fields and values.


The really fun part is __contains__:  should the __contains__ method 
return True when a _DbfRecordTemplate, tuple, or dict is looked up in 
the Table, List, or Index and there is a matching record?


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


Re: API design question for dbf.py

2012-07-06 Thread Ethan Furman

MRAB wrote:

On 06/07/2012 22:34, Ethan Furman wrote:

I'm looking for some free advice.  ;)

My dbf module has three basic containers, all of which support list-like
access:  Table, List, and Index, each of which is filled with 
_DbfRecords.


The fun part is that a _DbfRecord can compare equal to another
_DbfRecord, a _DbfRecordTemplate, a tuple with the same values in the
same locations, or a dict with the same keys/fields and values.

The really fun part is __contains__:  should the __contains__ method
return True when a _DbfRecordTemplate, tuple, or dict is looked up in
the Table, List, or Index and there is a matching record?


Well, if x is in c and x == y, then y is in c. Does that help? ;-)


Heh, that's pretty much the conclusion I was coming to.  As a more 
concrete example:


--> x = 4.0
--> x in [1, 4, 7, 4, 9, 3, 4]
True

It's checking for equality, not identity.

Thinks for helping me think that through.

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


Re: API design question for dbf.py

2012-07-06 Thread Ethan Furman

Devin Jeanpierre wrote:

On Fri, Jul 6, 2012 at 6:46 PM, Ethan Furman  wrote:

It's checking for equality, not identity.


  >>> x = float('nan')
  >>> x in [x]
  True

It's checking for equality OR identity.


Good point.  In my case, checking for equality will cover both cases.

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


Re: Python Interview Questions

2012-07-10 Thread Ethan Furman

Jean-Michel Pichavant wrote:
Why would you want to hire someone that knows something pointless as the 
version where feature X has been introduced ?


As an example from today, if someone claimed to have 5+ years of Python 
experience, but didn't know that 'with' was standard in 2.6 (or at least 
the end of the 2.x cycle) I would be suspicious that they actually had 
the experience they claimed.


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


Re: Python Interview Questions

2012-07-10 Thread Ethan Furman

Chris Angelico wrote:

On Wed, Jul 11, 2012 at 2:34 AM, Steven D'Aprano
 wrote:

Of course, if they try to sell themselves as having
five years experience with Python 3.2...


... then they've been borrowing Guido's time machine for personal purposes.


Reminds me of a job posting a few years ago where the prospective 
employer wanted three plus years experience in some language, and that 
language had only been created a year and a half before.


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


Re: Python professional certification

2012-07-13 Thread Ethan Furman

Mark Lawrence wrote:
Google tells me that various certifications are available but I'd like 
to know if any of these are approved by the PSF or whoever would be 
responsible?  If there's anything out there I've missed it :-(




There is an O'Reilly Python Certification class offered in conjunction 
with the Illinois Institute of Technology (or something like that) which 
was created by Steve Holden, and taught by him and a couple others.


It's a great course of four classes.

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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Ethan Furman

Steven D'Aprano wrote:

On Sun, 15 Jul 2012 10:19:16 -0600, Ian Kelly wrote:

On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano wrote:

(For the record, I can only think of one trap for the unwary: time
objects are false at *exactly* midnight.)

>>

Ugh, that's irritating.  I can't think of any scenario where I would
ever want the semantics "if timeval (is not midnight):".


Yes, it is a genuine gotcha. Time values are numbers, and zero is falsey, 
so midnight is falsey even though it shouldn't be.


There's no good solution here, since we have a conflict between treating 
time values as time values ("midnight is nothing special") and as numbers 
("midnight == 0 which is falsey"). 


--> import datetime
--> mn = datetime.time(0)
--> mn
datetime.time(0, 0)
--> mn == 0
False

Apparently, midnight does not equal zero.  Possibly because it should be 
truthy.  ;)


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


Re: Implicit conversion to boolean in if and while statements

2012-07-16 Thread Ethan Furman

Andrew Berg wrote:

On 7/15/2012 9:38 PM, Steven D'Aprano wrote:

I would expect None to mean "doesn't exist" or "unknown" or
something like that - e.g., a value of 0 means 0 jelly beans in the jar
and None means there isn't a jar.

>>
How you interpret some_variable = None depends on what some_variable 
represents. If some_variable represents "number of jelly beans in a jar", 
then that should be 0 if there is no jar.

>

What is None supposed to mean then, and what should I do when I have to
make a distinction between "doesn't exist" and "empty"? Sure, if I need
to count the total number of jelly beans in all my stores, the
distinction is meaningless, but if I need to find out which stores sell
jelly beans so I know which stores need to be restocked, the distinction
is quite important.


I'm not sure what Steven was trying to say there, but for me:

jar with no jellybeans == 0

no jar == None

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


Re: Implicit conversion to boolean in if and while statements

2012-07-17 Thread Ethan Furman

Andrew Berg wrote:

To put it in duck-typing terms, why should everything have to quack like
True or False? Sure, I can see why 1 quacks like True or [] quacks like
False, but I don't see why say, a Logger or function should quack like
either. Should a Thread object be True if it's been started and False
otherwise?


True and False are red herrings.  It is more appropriate to think that 
True quacks like something and False like nothing than the other way 'round.


Maybe some examples from my own code will help:

DbfTable--> True if any records in table, False otherwise

DbfIndex--> True if any records in index, False otherwise

DbfList --> True if any records in list, False otherwise

DbfDate --> True if a date, False otherwise (could be eight spaces 
instead of a real date)


DbfDateTime --> True if a datetime, False otherwise

DbfRecord   --> True always

DbfRecordTemplate --> True always

DbfRecordVaporware --> False always

While I could have DbfRecord be False if, for example, it had no data 
stored in it, I have no use case for that scenario so haven't bothered. 
 Also, at this point I am using the distinction of True/False with 
regards to records to determine if I have a real record (True means a 
record/template I can read/write, False means I don't).




If it truly is about something vs. nothing, why is a NameError (or
AttributeError) raised when testing with an undefined variable? Being
undefined quacks like nothing, doesn't it?


It's about /representing/ something vs. nothing. An undefined name isn't 
representing anything (except a bug, of course ;).


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


Re: Encapsulation, inheritance and polymorphism

2012-07-17 Thread Ethan Furman

Terry Reedy wrote:

On 7/17/2012 10:23 AM, Lipska the Kat wrote:


Well 'type-bondage' is a strange way of thinking about compile time type
checking and making code easier to read (and therefor debug


'type-bondage' is the requirement to restrict function inputs and output 
to one declared type, where the type declaration mechanisms are usually 
quite limited.


 >>> def max(a, b):
if a <= b: return a
return b



Surely you meant 'if a >= b: . . .'

No worries, I'm sure your unittests would have caught it.  ;)

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


Re: Encapsulation, inheritance and polymorphism

2012-07-17 Thread Ethan Furman

Mark Lawrence wrote:

On 17/07/2012 18:29, Ethan Furman wrote:

Terry Reedy wrote:

On 7/17/2012 10:23 AM, Lipska the Kat wrote:

Well 'type-bondage' is a strange way of thinking about compile time 
type

checking and making code easier to read (and therefor debug


'type-bondage' is the requirement to restrict function inputs and
output to one declared type, where the type declaration mechanisms are
usually quite limited.

 >>> def max(a, b):
if a <= b: return a
return b



Surely you meant 'if a >= b: . . .'

No worries, I'm sure your unittests would have caught it.  ;)

~Ethan~


Wouldn't the compiler have caught it before the unittests? :-)


Silly me, the word processor would have caught it!

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


Foxpro goto command and deleted records

2012-07-17 Thread Ethan Furman

In Foxpro if you do a

GOTO 7

with deleted off and record 7 is deleted, the record pointer doesn't
move (at least in version 6).

I don't like that.

I see four other options:

0) don't move the pointer (listed for completeness)
1) go to that record anyway
2) go to the next undeleted record
3) go to the seventh undeleted record (possibly the least practical)
4) raise an exception

Any opinions?

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


Re: Foxpro goto command and deleted records

2012-07-17 Thread Ethan Furman

Ian Kelly wrote:

On Tue, Jul 17, 2012 at 4:57 PM, Ethan Furman  wrote:

In Foxpro if you do a

GOTO 7

with deleted off and record 7 is deleted, the record pointer doesn't
move (at least in version 6).

I don't like that.

I see four other options:

0) don't move the pointer (listed for completeness)
1) go to that record anyway
2) go to the next undeleted record
3) go to the seventh undeleted record (possibly the least practical)
4) raise an exception

Any opinions?


Relevance to Python?


I'm deciding how my python dbf module will handle this situation.

http://python.org/pypi/dbf for the curious.

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


Re: Foxpro goto command and deleted records

2012-07-17 Thread Ethan Furman

MRAB wrote:

On 17/07/2012 23:57, Ethan Furman wrote:

In Foxpro if you do a

GOTO 7

with deleted off and record 7 is deleted, the record pointer doesn't
move (at least in version 6).

I don't like that.

I see four other options:

0) don't move the pointer (listed for completeness)
1) go to that record anyway
2) go to the next undeleted record
3) go to the seventh undeleted record (possibly the least practical)
4) raise an exception

Any opinions?


What happens when you 'delete' a record? Does it disappear immediately,
or is it merely marked for deletion?


Marked for deletion.


If it is marked for deletion, can it be unmarked? Will a marked record
be removed when the file is closed, or does the file need to be
explicitly purged/compacted?


Yes, it can be unmarked.  No, the table must be explicitly packed.


If it is merely marked, then I think the best option is 1, or possibly
4 if the file is compacted when closed.


There is a use_deleted setting that controls whether deleted records are 
accessed or skipped.  Skipping is fine when looping, not so fine when 
going directly to a particular record.


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


Re: Foxpro goto command and deleted records

2012-07-17 Thread Ethan Furman

MRAB wrote:

On 18/07/2012 03:19, Ethan Furman wrote:

MRAB wrote:

On 17/07/2012 23:57, Ethan Furman wrote:

In Foxpro if you do a

GOTO 7

with deleted off and record 7 is deleted, the record pointer doesn't
move (at least in version 6).

I don't like that.

I see four other options:

0) don't move the pointer (listed for completeness)
1) go to that record anyway
2) go to the next undeleted record
3) go to the seventh undeleted record (possibly the least practical)
4) raise an exception

Any opinions?


What happens when you 'delete' a record? Does it disappear immediately,
or is it merely marked for deletion?


Marked for deletion.


If it is marked for deletion, can it be unmarked? Will a marked record
be removed when the file is closed, or does the file need to be
explicitly purged/compacted?


Yes, it can be unmarked.  No, the table must be explicitly packed.


If it is merely marked, then I think the best option is 1, or possibly
4 if the file is compacted when closed.


There is a use_deleted setting that controls whether deleted records are
accessed or skipped.  Skipping is fine when looping, not so fine when
going directly to a particular record.


If use_deleted is false, does that mean that deleted records are
hidden, or just that when iterating through the records the deleted
ones aren't yielded?


Definitely the latter, but I'm starting to wonder if the former should 
also be the case.


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


Re: Encapsulation, inheritance and polymorphism

2012-07-18 Thread Ethan Furman

Lipska the Kat wrote:

On 18/07/12 14:05, Steven D'Aprano wrote:

Even with a break, why bother continuing through the body of the function
when you already have the result? When your calculation is done, it's
done, just return for goodness sake. You wouldn't write a search that
keeps going after you've found the value that you want, out of some
misplaced sense that you have to look at every value. Why write code with
unnecessary guard values and temporary variables out of a misplaced sense
that functions must only have one exit?


Object Oriented programming is all about encapsulating human concepts in 
a way that makes sense to human beings. Make no mistake, it is NEVER the 
case that a software system is written for any other reason than to 
serve human beings. OO is more than just the mechanics of writing code, 
it's a state of mind.


I must admit I have no idea how we went from discussing Single Exit 
functions to the One True Purpose of Object Oriented Programming;  are 
you saying that SE is one of the basic tenets of OO?



OO was 'invented' to address the many problems that beset increasingly 
complex software systems. The main problem was maintainability. 
Encapsulating a concept in a clear and concise way makes the code easier 
to understand. Sometimes this means writing code that is not 'optimal' 
for the machine. Good code should be readable as well as efficient but I 
contend that it is better to write something that is clear, concise and 
well encapsulated than always go for the 'meanest dog in the scrapyard' 
approach where a developer is determined to write unreadable code that 
shows how jolly clever he is. More often than not he is forced to admit 
six months down the line that he has no idea what his code does as he 
'forgot' to comment it.


And one of the many reasons I love Python is that it is so easy to write 
clear, readable, and sometimes concise code (nested list comps are still 
a challenge for me).


. . .

Python looks like an interesting language and I will certainly spend 
time getting to know it but at the moment it seems to me that calling it 
an Object Oriented language is just plain misleading.


Since *everything* in Python is an object, how can you /not/ call it an 
OO language?  Sure, you don't have to use everything as an object -- 
plain functions exist -- kinda ;)  Even functions live in some 
namespace: len() lives in __builtin__, any top level function lives in 
its module, etc.  Oh, and namespaces are objects.


It seems to me that Python is more about providing tools, and then 
staying out of your way.


That works for me.  Maybe it will work for you, too.

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


Re: Foxpro goto command and deleted records

2012-07-18 Thread Ethan Furman

Ed Leafe wrote:

On Jul 17, 2012, at 5:57 PM, Ethan Furman wrote:


In Foxpro if you do a

GOTO 7

with deleted off and record 7 is deleted, the record pointer doesn't
move (at least in version 6).

I don't like that.

I see four other options:

0) don't move the pointer (listed for completeness)
1) go to that record anyway
2) go to the next undeleted record
3) go to the seventh undeleted record (possibly the least practical)
4) raise an exception

Any opinions?


It's been many years since I fired up VFP, but the above doesn't sound 
correct. If you have SET DELETED OFF and the GOTO 7, the pointer should move to 
the 7th record, whether it is marked deleted or not. With SET DELETED ON, the 
pointer should not move, since 7 is not a valid record.


Your memory is good!  I typed it in wrong.

I still don't like it.  Any opinion on the other four choices?  I'm
leaning towards 1, possibly with 4 as an option:

def goto(self, recno, raise_if_deleted=True):
if is_deleted(self[recno)) and raise_if_deleted:
raise DbfError(
   "Record %d is deleted and use_deleted is False" % recno)
self._index = recno

Part of the reason I feel this is reasonable is that with my dbf module
it is possible to create an index that does /not/ include certain records:

def ignore_deleted(record):
if dbf.deleted(record):
return dbf.DoNotIndex
return dbf.recno(record)

~Ethan~

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


ANN: dbf.py 0.94

2012-07-20 Thread Ethan Furman

Getting closer to a stable release.

Latest version has a simpler, cleaner API, and works on PyPy (and 
hopefully the other implementations as well ;), as well as CPython.


Get your copy at http://python.org/pypi/dbf.

Bug reports, comments, and kudos welcome!  ;)

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


Re: ANN: dbf.py 0.94

2012-07-20 Thread Ethan Furman

Steven D'Aprano wrote:

On Fri, 20 Jul 2012 16:59:21 -0700, Ethan Furman wrote:


Getting closer to a stable release.


Excellent! That's fantastic news! I've been waiting for a stable release 
of dbf for months! I just have one question.


What is dbf?


:)

dbf (also known as python dbase) is a module for reading/writing
dBase III, FP, VFP, and soon Clipper, .dbf database files.  It's
an ancient format that still finds lots of use.

It even reads and writes memo fields -- something which none of the 
other modules do (which is why I wrote this one -- I needed that! ;).


It supports unicode, and returns all fields as native Python types:

  Character --> unicode
  Date  --> datetime.date
  Logical   --> bool/None
  Memo  --> unicode
  Numeric   --> int/float depending on field definition

If a field is uninitialized (Date, Logical, Numeric) then None is 
returned for the value.


Tables are accessible as lists; Records are accessible as lists, dicts, 
and objects ( attribute access ).


Enjoy your weekend!
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: dbf.py 0.94

2012-07-21 Thread Ethan Furman

Steven D'Aprano wrote:
This mailing list is about helping our fellow Python developers improve 
their skills and solve problems. That doesn't just mean *coding* 
problems, it also means helping them to write better documentation and 
promote their software better.


Indeed it is, and your reminder is appreciated.  Hopefully my 
followup-post was more explanatory.



Unless the software is so well-known that everybody knows what it is, 
failure to mention what the software does gives the impression that: 

1) the software is so niche, or so ill-thought out, that the developer 
*can't* describe it succinctly;


Nah -- just the end of a long week, needed to go get my daughter, and 
wanted it out there for those few who actually need the bug fixes (which 
I neglected to mention).


2) the developer has such poor communication skills that trying to get 
support will be a nightmare;


My support is pretty good.  :)



3) that he just doesn't give a monkey's toss for anyone else's time


See point one.


or all three. Ethan is a good, helpful member of this community, and
so I'm pretty sure that neither 2) nor 3) are true, but others may get
the wrong impression.


Thank you.  The project is kinda niche, but very useful if you happen to 
be in that niche.




Here are a few randomly selected examples of good release announcements:

http://mail.python.org/pipermail/python-announce-list/2012-June/009528.html

http://mail.python.org/pipermail/python-announce-list/2012-June/009509.html

http://mail.python.org/pipermail/python-announce-list/2012-June/009524.html


Those are good.  My announcement will be better next time.

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


Re: ANN: dbf.py 0.94

2012-07-21 Thread Ethan Furman

Simon Cropper wrote:


Question 1 - What version of VFP will dbf work with? Is VFP9 OK?


As long as you don't use auto-incrementing fields nor varchar fields 
you'll be fine.




Question 2 - You statement of compatibility is unclear.


Works with CPython 2.4 - 2.7. (Tested)

Works with PyPy 1.8. (Tested)

Should work with the others.  (Not tested)


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


Re: ANN: dbf.py 0.94

2012-07-21 Thread Ethan Furman

Chris Angelico wrote:

On Sat, Jul 21, 2012 at 6:02 PM, Ethan Furman  wrote:

Works with CPython 2.4 - 2.7. (Tested)


Have you considered supporting 3.2/3.3 at all? It's often not
difficult to make your code compatible with both. Or is there some
dependency that is locked to 2.X?


I'll support 3.3+, but not with the same code base:  I want to use all 
the cool features that 3.3 has!  :)


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


Re: ANN: dbf.py 0.94

2012-07-21 Thread Ethan Furman

Alex Strickland wrote:

Hi


Getting closer to a stable release.

Latest version has a simpler, cleaner API, and works on PyPy (and
hopefully the other implementations as well ;), as well as CPython.

Get your copy at http://python.org/pypi/dbf.

Bug reports, comments, and kudos welcome!  ;)


"Not supported: index files":

I have been using http://sourceforge.net/projects/harbour-project/ for 
years where a guy called Przemyslaw Czerpak has written an absolutely 
bullet proof implementation of NTX and CDX for DBF. Maybe it will 
interest you.


I'll check it out, thanks!


PS : bareable is spelt bearable.


I wondered about that.  :/

~Ethan~

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


Re: ANN: dbf.py 0.94

2012-07-23 Thread Ethan Furman

Ethan Furman wrote:

Alex Strickland wrote:

"Not supported: index files":

I have been using http://sourceforge.net/projects/harbour-project/ for 
years where a guy called Przemyslaw Czerpak has written an absolutely 
bullet proof implementation of NTX and CDX for DBF. Maybe it will 
interest you.


I'll check it out, thanks!


Unfortunately his code is GPL'ed, so I can't use it.  :(

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


Re: ANN: dbf.py 0.94

2012-07-23 Thread Ethan Furman

Chris Angelico wrote:

On Sun, Jul 22, 2012 at 4:15 AM, Ethan Furman  wrote:

I'll support 3.3+, but not with the same code base:  I want to use all the
cool features that 3.3 has!  :)


The trouble with double-codebasing is that you have double
maintenance. But sure. So long as your time isn't under great
pressure, it can be quite effective.


Once I get dbf.py to 1.0 release, it will enter maintenance/bug-fix-only 
mode, and I'll start on the 3.3+ version.


The 1.0 release will have the final API, support for Clipper tables, 
hopefully support for auto-incrementing fields, maybe support for .idx 
files, plus everything there now.


.cdx files (and maybe .idx files) will have to wait for the 3.3+ version.


There, now I have a roadmap to follow!  :)

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


Re: Gender, Representativeness and Reputation in StackOverflow

2012-07-23 Thread Ethan Furman

Terry Reedy wrote:
Leaving aside the point that this is not directly related to Python, my 
opinion is that if the authors will not make past and future papers 
freely available, not even an abstract, they should not ask for valuable 
free data from freely donated time.


Thanks, Terry!  Save me some valuable time.

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


Re: the meaning of rユ.......ï¾

2012-07-24 Thread Ethan Furman

Ian Kelly wrote:

On Tue, Jul 24, 2012 at 8:50 AM, Chris Angelico  wrote:

Americans celebrate March 14th as 3.14; some Europeans celebrate July
22nd as 22/7 (which is 3.142857, fairly close to 3.14159). We claim
both, and also June 28th (aka Tau Day or Two Pi Day, 6.28).


Hey now, Tau Day is an American invention, so no claiming it as an
Australian thing.  We just need to get a few more people here to start
observing it; that's all.


I'm in!  At least for next year.  Assuming I remember...

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


Re: from future import pass_function

2012-07-25 Thread Ethan Furman

Ulrich Eckhardt wrote:
I just had an idea, it occurred to me that the pass statement is pretty 
similar to the print statement, and similarly to the print() function, 
there could be a pass() function that does and returns nothing.


Example:
   def pass():
   return

   try:
   do_something()
   except:
   pass()


Do you have a use case where `pass()` works but `pass` doesn't?

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


Re: from future import pass_function

2012-07-25 Thread Ethan Furman

Ross Ridge wrote:

Ross Ridge  wrote:

No, they're very much alike.  That's why all your arguments for print
as function also apply just as well to pass a function.  Your arguments
had very little to do what what print actually did.


Chris Angelico   wrote:

Except that print / print() is executable. Execution proceeds through
your code, comes to a "print", and goes off to handle that, then comes
back to your code. But "pass" doesn't have code attached to it. Why
should it be a function?


For consistancy with print.  What it does doesn't matter any more than
what print did mattered.


Of course what print did mattered.  `print` was not changed to `print()` 
because a function looks cooler; it was changed because it does stuff, 
and what it does could be changed with parameters, and overriding it 
with your own custom thingie was a useful thing to do.


What code does `pass` run?  When do we pass parameters to `pass`?   When 
do we need to override `pass`?


Answers:  None.  Never.  Still waiting for a reply from the OP for a use 
case.


How does that quote go?  "A foolish consistency is the hobgoblin of 
little minds"?  This definitely fits that category.


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


ANN: dbf.py 0.94.003

2012-07-26 Thread Ethan Furman
A few more bug fixes, and I actually included the documentation this 
time.  :)  It can be found at http://python.org/pypi/dbf, and has been 
tested on CPythons 2.4 - 2.7, and PyPy 1.8.




dbf v0.94.003
=

dbf (also known as python dbase) is a module for reading/writing
dBase III, FP, VFP, and Clipper .dbf database files.  It's
an ancient format that still finds lots of use (the most common
I'm aware of is retrieving legacy data so it can be stored in a
newer database system; other uses include GIS, stand-alone programs
such as Family History, Personal Finance, etc.).

Highlights
--

Table -- represents a single .dbf/.dbt (or .fpt) file combination
and provides access to records; suports the sequence access and 'with'
protocols.  Temporary tables can also live entirely in memory.

Record -- repesents a single record/row in the table, with field access
returning native or custom data types; supports the sequence, mapping,
attribute access (with the field names as the attributes), and 'with'
protocols.  Updates to a record object are reflected on disk either
immediately (using gather() or write()), or at the end of a 'with'
statement.

Fields:
dBase III (Null not supported)

Character --> unicode
Date  --> datetime.date or None
Logical   --> bool or None
Memo  --> unicode or None
Numeric   --> int/float depending on field definition or None

Float --> same as numeric

Clipper (Null not supported)

Character --> unicode  (character fields can be up to 65,519)

Foxpro (Null supported)

General   --> str (treated as binary)
Picture   --> str (treated as binary)

Visual Foxpro (Null supported)

Currency  --> decimal.Decimal
douBle--> float
Integer   --> int
dateTime  --> datetime.datetime

If a field is uninitialized (Date, Logical, Numeric, Memo, General,
Picture) then None is returned for the value.

Custom data types:

Null -->  used to support Null values

Char -->  unicode type that auto-trims trailing whitespace, and
  ignores trailing whitespace for comparisons

Date -->  date object that allows for no date

DateTime -->  datetime object that allows for no datetime

Time -->  time object that allows for no time

Logical  -->  adds Unknown state to bool's: instead of True/False/None,
  values are Truth, Falsth, and Unknown, with appropriate
  tri-state logic; while bool(None) is False, bool(Unknown)
  raises a TypeError;  __index__ of Unknown is 2

Quantum  -->  similar to Logical, but implements boolean algebra (I 
think)



Whirlwind Tour
--

import datetime
import dbf

table = dbf.Table(':test:', 'name C(25); age N(3,0); birth D; qualified L')
table.open()

for datum in (
('Spanky', 7, dbf.Date.fromymd('20010315'), False),
('Spunky', 23, dbf.Date(1989, 07, 23), True),
('Sparky', 99, dbf.Date(), dbf.Unknown),
):
table.append(datum)

for record in table:
print record
print ''
print record[0:3]
print record['name':'birth']
print [record.name, record.age, record.birth]
print ''

custom = table.new(
filename='test_on_disk',
default_data_types=dict(C=dbf.Char, D=dbf.Date, L=dbf.Logical),
)

with custom:# automatically opened and closed
for record in table:
custom.append(record)
for record in custom:
dbf.write(record, name=record.name.upper())
print record
print ''
print record[0:3]
print record['name':'birth']
print [record.name, record.age, record.birth]
print ''

table.close()
--
http://mail.python.org/mailman/listinfo/python-list


Re: dict: keys() and values() order guaranteed to be same?

2012-07-26 Thread Ethan Furman

Chris Angelico wrote:

On Tue, Jul 24, 2012 at 1:20 AM, Steven D'Aprano
 wrote:

(Although if you think about the implementation of dicts as hash tables,
it does seem likely that it is trivial to enforce this -- one would have
to work *harder* to break that promise than to keep it.)


However, it would be quite reasonable to implement a dict as a splay
tree, and have values() return them nearest-first. This would mean
that just reading from the dictionary could change the order of
values(), yet it wouldn't make the implementation non-conformant.


Yes, it would.  The docs say that .keys(), .values(), etc., will 
maintain order unless the dict is modified in between calls.


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


Re: dict: keys() and values() order guaranteed to be same?

2012-07-26 Thread Ethan Furman

Steven D'Aprano wrote:
Python's promise is much stronger than merely "deterministic": while it 
does not promise what order the keys will be returned, it does promise 
that whatever that order turns out to be, they will returned in the same 
order as the matching values (unless you modify the dict while iterating).


or modify the dict between iterations.

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


Re: from future import pass_function

2012-07-26 Thread Ethan Furman

John Ladasky wrote:

On Wednesday, July 25, 2012 9:32:33 PM UTC-7, Ethan Furman wrote:

What code does `pass` run?  When do we pass parameters to `pass`?   When 
do we need to override `pass`?


Answers:  None.  Never.  Still waiting for a reply from the OP for a use 
case.


When I brought up this same issue some months ago...

https://groups.google.com/forum/?fromgroups#!topic/comp.lang.python/CB_5fek2b8A

...it wasn't because I wanted to pass parameters to "pass", it was because I wanted to 
define a do-nothing function as an optional behavior within another function.  In other words, I 
wanted to pass "pass."


That's a reasonable thing to want, and quite easily accomplished by 
passing `lambda: None`  or `lambda *args, **kwargs: None` instead.  I 
don't think this is difficult to do, nor common enough to justify making 
every other `pass` a time-consuming do-nothing operation, instead of 
just a do-nothing operation


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


Re: from future import pass_function

2012-07-26 Thread Ethan Furman

John Ladasky wrote:

I had very similar thoughts about eight months ago, and posted them here:

https://groups.google.com/forum/?fromgroups#!topic/comp.lang.python/CB_5fek2b8A

I'm no computer science guru, but the idea that pass should be a function 
rather than a statement continues to appeal to me.  As you can see, I actually 
wrote just such a function so that I could use it as an argument in my code.


I would have called `no_op` or `nop` -- `pass` does just what it says: 
it passes and does zero work.  Your _pass does do work, just useless 
work.  Sometimes that's necessary, but I wouldn't call it `_pass`.


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


Re: ANN: dbf.py 0.94.003

2012-07-27 Thread Ethan Furman

Simon Cropper wrote:

On 27/07/12 05:31, Ethan Furman wrote:

A few more bug fixes, and I actually included the documentation this
time.  :)  It can be found at http://python.org/pypi/dbf, and has been
tested on CPythons 2.4 - 2.7, and PyPy 1.8.


[snip]

Ethan,

That's great.

Can you comment on the ultimate aim of the project?


To provide read/write access to the dbf format, from
dBase III to dBase 7, including memos and index files.
Currently supports dBase III, FoxPro, Clipper,
and Visual Foxpro (but not autoincrement nor varchar).


Is this package primarily a "universal dbf translator" that allows the 
data stored in DBFs (which I might add I have many in legacy VFP 
applications and GIS Shapefiles) to be accessed and extracted or is the 
module being designed to be used interactively to extract data from and 
update tables?


Some folk use it as a dbf translator, some folk use it for interactive 
work.  I use it for both those purposes as well as creating new dbf 
files which get processed by our in-house software as well as 
third-party software every day.



I remember on the last thread that someone mentioned that indexes are 
not supported. I presume then that moving around a table with a couple 
of million records might be a tad slow. Have you tested the package on 
large datasets, both DBFs with a large number of records as well as a 
large number of fields?


The largest tables I've had at my disposal so far were about 300,000 
records with roughly 50 fields with a total record length of about 
1,500.  Processing (for me) involves going through every single record, 
and yes it was a tad slow.  This is my most common scenario, and index 
files would not help at all.


For more typical work (for others) of selecting and using a subset of 
the dbf, an in-memory index can be created -- initial creation can take 
a few moments, but searches afterwards are quite quick.


This is a pure-python implementation, so speed is not the first goal. 
At some point in the future I would like to create a C accelerator, but 
that's pretty far down the to-do list.


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


Re: [ANN] pyknon: Simple Python library to generate music in a hacker friendly way.

2012-07-30 Thread Ethan Furman

Pedro Kroger wrote:

Pyknon is a simple music library for Python hackers.


Sounds cool.  How is 'Pyknon' pronounced?



It's available on PyPI and its homepage is
http://kroger.github.com/pyknon/


I would suggest you change the theme -- using Firefox 3.6 the page is 
very difficult to read.


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


Re: [ANN] pyknon: Simple Python library to generate music in a hacker friendly way.

2012-07-30 Thread Ethan Furman

Pedro Kroger wrote:


On Jul 30, 2012, at 3:33 PM, Ethan Furman <mailto:et...@stoneleaf.us>> wrote:



Pedro Kroger wrote:

Pyknon is a simple music library for Python hackers.


Sounds cool.  How is 'Pyknon' pronounced?


I pronounce it similarly as google translate does:


So the 'k' is pronounced.  Okay.


I would suggest you change the theme -- using Firefox 3.6 the page is 
very difficult to read.


Thanks for the report. Do you mind if I ask why you are using such an 
old version?

(It looks fine with Firefox 14.0.1)



That version works for me -- I don't like upgrading to a new version of 
bugs if I don't have to.  ;)


I checked the page on a coworker's machine who does have a recent 
version, and it is a little better, but it is still very faint (thin 
grey letters on a white background is hard to read).  With version 3 the 
thin grey letters are also broken, making it even worse.


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


Re: NameError vs AttributeError

2012-08-01 Thread Ethan Furman

Terry Reedy wrote:

On 7/31/2012 4:49 PM, Chris Kaynor wrote:

On Tue, Jul 31, 2012 at 1:21 PM, Terry Reedy wrote:

Another example: KeyError and IndexError are both subscript errors,
but there is no SubscriptError superclass, even though both work
thru the same mechanism -- __getitem__.  The reason is that there is
no need for one. In 'x[y]', x is usually intented to be either a
sequence or mapping, but not possibly both. In the rare cases when
one wants to catch both errors, one can easily enough. To continue
the example above, popping an empty list and empty set produce
IndexError and KeyError respectively:

   try:
 while True:
   process(pop())
   except (KeyError, IndexError):
 pass  # empty collection means we are done


There is a base type for KeyError and IndexError: LookupError.

http://docs.python.org/library/exceptions.html#exception-hierarchy


Oh, so there is. Added in 1.5 strictly as a never-directly-raised base 
class for the above pair, now also directly raised in codecs.lookup. I 
have not decided if I want to replace the tuple in the code in my book.


I think I'd stick with the tuple -- LookupError could just as easily 
encompass NameError and AttributeError.

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


dbf.py API question

2012-08-02 Thread Ethan Furman
SQLite has a neat feature where if you give it a the file-name of 
':memory:' the resulting table is in memory and not on disk.  I thought 
it was a cool feature, but expanded it slightly: any name surrounded by 
colons results in an in-memory table.


I'm looking at the same type of situation with indices, but now I'm 
wondering if the :name: method is not pythonic and I should use a flag 
(in_memory=True) when memory storage instead of disk storage is desired.


Thoughts?

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


Re: dbf.py API question

2012-08-03 Thread Ethan Furman

Peter Otten wrote:

Ethan Furman wrote:


SQLite has a neat feature where if you give it a the file-name of
':memory:' the resulting table is in memory and not on disk.  I thought
it was a cool feature, but expanded it slightly: any name surrounded by
colons results in an in-memory table.

I'm looking at the same type of situation with indices, but now I'm
wondering if the :name: method is not pythonic and I should use a flag
(in_memory=True) when memory storage instead of disk storage is desired.
 
For SQLite it seems OK because you make the decision once per database. For 
dbase it'd be once per table, so I would prefer the flag.


So far all feedback is for the flag, so that's what I'll do.



Random


Thoughts?


- Do you really want your users to work with multiple dbf files? I think I'd 
rather convert to SQLite, perform the desired operations using sql, then 
convert back.


Seems like that would be quite a slow-down (although if a user wants to 
do that, s/he certainly could).


- Are names required to manipulate the table? If not you could just omit 
them to make the table "in-memory".


At one point I had thought to make tables singletons (so only one copy 
of /user/bob/scores.dbf) but that hasn't happened and is rather low 
priority, so at this point the name is not required for anything beside 
initial object creation.


- How about a connection object that may either correspond to a directory or 
RAM:


db = dbf.connect(":memory:")
table = db.Table("foo", ...)


dbf.py does not support the DB-API interface, so no connection objects. 
  Tables are opened directly and dealt with directly.


All interesting thoughts that made me think.  Thank you.

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


Re: ANN: dbf.py 0.94

2012-08-03 Thread Ethan Furman

Mark Lawrence wrote:

On 21/07/2012 00:59, Ethan Furman wrote:

Getting closer to a stable release.

Latest version has a simpler, cleaner API, and works on PyPy (and
hopefully the other implementations as well ;), as well as CPython.

Get your copy at http://python.org/pypi/dbf.

Bug reports, comments, and kudos welcome!  ;)


Will this work with Recital software on VMS? :)


Does Recital use dBase III, Foxbase, Foxpro, or Visual Foxpro compatible 
files?  Does Python run on VMS?  If yes to both of those, then it 
should.  :)


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


Re: Calling Values

2012-08-03 Thread Ethan Furman

subhabangal...@gmail.com wrote:

On Friday, August 3, 2012 5:19:46 PM UTC+5:30, Subhabrata wrote:

Dear Group,



I am trying to call the values of one function in the another function in the 
following way:

def func1():

num1=10

num2=20

print "The Second Number is:",num2

return



def func2():

num3=num1+num2

num4=num3+num1

print "New Number One is:",num3

print "New Number Two is:",num4

return



I am preferring not to use argument passing or using class? Is there any 
alternate way?



Thanking in Advance,

Regards,

Subhabrata.


Dear Group,

def func1():

num1=10

num2=20

print "The Second Number is:",num2

return


def func2():

func1()
num3=num1+num2

num4=num3+num1

print "New Number One is:",num3

print "New Number Two is:",num4


This works. 


No, it doesn't.  If it does work for you then you have code you aren't 
showing us.


~Ethan~

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


Re: dbf.py API question

2012-08-05 Thread Ethan Furman

Ole Martin Bjørndalen wrote:

On Thu, Aug 2, 2012 at 5:55 PM, Ethan Furman  wrote:

SQLite has a neat feature where if you give it a the file-name of ':memory:'
the resulting table is in memory and not on disk.  I thought it was a cool
feature, but expanded it slightly: any name surrounded by colons results in
an in-memory table.

I'm looking at the same type of situation with indices, but now I'm
wondering if the :name: method is not pythonic and I should use a flag
(in_memory=True) when memory storage instead of disk storage is desired.

Thoughts?


I agree that the flag would be more pythonic in dbf.py.

I was not aware that you are adding sqlite functionality to your
library. This is very cool!


Actually, I'm not.  I had stumbled across that one tidbit and thought it 
was cool, but cool is not always pythonic.  ;)




I am considering adding a "streaming=True" flag which would make the
table class a record generator,


You can do this by implementing either __getitem__ or __iter__, unless 
the streaming flag would also make your table not in memory.




I hope this can help you somehow in your decision making process.


All comments appreciated.  Thanks!

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


Re: On-topic: alternate Python implementations

2012-08-05 Thread Ethan Furman

Mark Lawrence wrote:

With arrogance like that German by any chance?


Comments like that are not appropriate on this list.  Please don't make 
them.


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


Re: dbf.py API question

2012-08-06 Thread Ethan Furman

[redirecting back to list]

Ole Martin Bjørndalen wrote:

On Sun, Aug 5, 2012 at 4:09 PM, Ethan Furman  wrote:

Ole Martin Bjørndalen wrote:
You can do this by implementing either __getitem__ or __iter__, unless the
streaming flag would also make your table not in memory.


Cool!

Wow! I realize now that this could in fact be fairly easy to
implement. I just have to shuffle around the code a bit to make both
possible. The API would be:

   # Returns table object which is a subclass of list
   table = dbfget.read('cables.dbf')
   for rec in table:
   print rec

   # Return a table object which behaves like an iterator
   table = dbfget.read('cables.dbf', iter=True)
   for rec in table:
  print rec

I have a lot of questions in my mind about how to get this to work,
but I feel like it's the right thing to do. I will make an attempt at
a rewrite and get back to you all later.

One more API question: I am uncomfortable with:


   dbfget.read()

Should it just be:

   dbfget.get()

?

- Ole


`dbfget` is the package name, and `read()` or `get` is the 
class/function that loads the table into memory and returns it?


Maybe `load()`?

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


Re: Intermediate Python user needed help

2012-08-06 Thread Ethan Furman

John Mordecai Dildy wrote:

I am currently using python 2.6 and am not going to install the newer versions 
of python and i am looking for people that are still using ver 2.6 in python to 
help with with the code line:

sentence = "All good things come to those who wait."

then im getting this error message when i dont see the problem with it:

  File "ex26.py", line 77
sentence = "All good things come to those who wait."
   ^
SyntaxError: invalid syntax


John Mordecai Dildy wrote:
> Current Problem at the moment
>
> Traceback (most recent call last):
>   File "ex26.py", line 66, in 
> beans, jars, crates = secret_formula(start-point)
> NameError: name 'start' is not defined
>
> anyone know how to make start defined

In your subject line you state that you are an intermediate Python user. 
 These are not the errors an intermediate user would make, nor the 
questions an intermediate user would ask.  These are the errors that 
somebody who doesn't know Python would make.


Please do not misrepresent yourself.

~Ethan~

P.S.  The scale I am accustomed to is Novice -> Intermediate -> Advanced 
-> Master


Are there scales out there that would put these types of questions in 
the "intermediate" category?

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


Re: looking for a neat solution to a nested loop problem

2012-08-06 Thread Ethan Furman

Tom P wrote:

consider a nested loop algorithm -

for i in range(100):
for j in range(100):
do_something(i,j)

Now, suppose I don't want to use i = 0 and j = 0 as initial values, but 
some other values i = N and j = M, and I want to iterate through all 
10,000 values in sequence - is there a neat python-like way to this? I 
realize I can do things like use a variable for k in range(1): and 
then derive values for i and j from k, but I'm wondering if there's 
something less clunky.


for i in range(N, N+100):
for j in range(M, M+100):
do_something(i, j)


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


Re: dbf.py API question

2012-08-08 Thread Ethan Furman

Ed Leafe wrote:

When converting from paradigms in other languages, I've often been 
tempted to follow the accepted pattern for that language, and I've almost 
always regretted it.


+1



When in doubt, make it as Pythonic as possible.


+1 QOTW

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


  1   2   3   4   5   6   7   8   9   10   >