Re: Instant File I/O

2011-03-24 Thread Charles

"jam1991"  wrote in message 
news:c0c76bc4-8923-4a46-9c36-6e1a0375f...@l11g2000yqb.googlegroups.com...
[snip]
> they sign into the program with; however, this information doesn't
> appear in the file until after the program has closed. This poses a
> problem for retrieving the up-to-date statistics data during the same
> session. Is there anyway I can fix this? I'm using .write() to write
[snip]

.flush() ?
>From http://www.tutorialspoint.com/python/file_methods.htm
file.flush()
Flush the internal buffer, like stdio's fflush. This may be a no-op on some 
file-like objects.
Charles


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


Re: English Idiom in Unix: Directory Recursively

2011-05-26 Thread Charles

"Thorsten Kampe"  wrote in message 
news:mpg.284834d227e3acd1989...@news.individual.de...
>
> If someone has learned what a directory or folder is, you don't have to
> explain what "include sub-folders" means. Instead of creating a new
> mysterious term ("recursively delete"), you simply explain stuff by re-
> using an already existing term. It's just that simple.

I'm a native english speaker, and to me there is a difference between
"delete directory and sub-directories" (or folders and sub-folders if you
follow Microsoft's naming conventions) and "recursively delete". I know
english is very ambiguous, but to me "directory and sub-directories"
does not necessarily imply sub-directories of sub-directories and so
on, while "recursively delete" does carry the connotation of deleting the
sub-directories of sub-directories and sub-directories of sub-directories
of sub-directories and so on.


Charles



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


Can I compile Python for the web?

2005-09-23 Thread Charles
Dear sirs,

I'm doing some investigations on the Python language.
I'd like to know if it is possible to compile Python code made for the web  
(an online database for instance), and to run it using mod_python. How is  
it possible? I think it would be very fast to execute the code if it were  
compiled.
Thanks,

-- 
Charles.

Desenvolvimento e criação de sites: www.auriance.com
Hospedagem de sites e servidores dedicados: www.auriance.net
-- 
http://mail.python.org/mailman/listinfo/python-list


How can I find a freelance programmer?

2006-02-14 Thread Charles
Hello,

I am looking for a freelance Python programmer to create a cross-platform  
application with wxPython.
Any idea where I could find one?
Thanks,

-- 
Charles.
landemaine[at]gmail[dot]com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I find a freelance programmer?

2006-02-14 Thread Charles
On Tue, 14 Feb 2006 17:46:46 -0300, Tim Parkin <[EMAIL PROTECTED]> wrote:

> You could ask Steve Holden?  -  that'll be 10% commission Steve! ;-)

Him: http://sholden.typepad.com/ ?


-- 
Charles.

Desenvolvimento e criação de sites: www.auriance.com
Hospedagem de sites e servidores dedicados: www.auriance.net
-- 
http://mail.python.org/mailman/listinfo/python-list


mod_python and open HTTP connection

2006-02-16 Thread Charles
Hello, I'm think about using mod_python for a project but I need to make  
sure: Does mod_python time out after a minute ? (I hope not). If I leave  
an HTTP connection open so that the content keeps loading inside the  
browser window indefinately, and if I close the browser window, the  
mod_python process is terminated, right?
Thanks,

-- 
Charles.

Desenvolvimento e criação de sites: www.auriance.com
Hospedagem de sites e servidores dedicados: www.auriance.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mod_python and open HTTP connection

2006-02-17 Thread Charles
On Thu, 16 Feb 2006 21:35:13 -0300, Kane <[EMAIL PROTECTED]> wrote:

> btw, 'ping' as written above is horrible.  If a code review turned
> _that_ up on production someone would be fired, along with whoever
> hired them, whoever ate lunch with them and anyone that waves goodbye.

Really? Wow... Gotta be carefull from now on...


-- 
Charles.

Desenvolvimento e criação de sites: www.auriance.com
Hospedagem de sites e servidores dedicados: www.auriance.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Firefighters at the site of WTC7 "Move away the building is going to blow up, get back the building is going to blow up."

2007-05-04 Thread Charles
On Fri, 04 May 2007 20:19:33 -0700, James Stroud
<[EMAIL PROTECTED]> wrote:

>MooseFET wrote:
>> On May 4, 12:32 pm, James Stroud <[EMAIL PROTECTED]> wrote:
>> []
>> 
>>>The Marxist contribution to western thought is that it put everything in
>>>terms of labor and thus allowed us to quantify the human component of
>>>economies.
>> 
>> 
>> No the great insight by Marx was in the selling of ducks.  "Anybody
>> want to buy a duct"  has done more to advance economic thinking than
>> the works of most economists.
>> 
>> Economists have a vested interest in preventing people from
>> understanding economics.  They are well paid and know that they
>> wouldn't be for long if people really understood what was going on.
>> 
>
>You must be an economist because you provide absolutely no 
>interpretation of what the hell you were saying in ghe first paragraph 
>(as if you actually know what you were trying to say). Duct or duck, 
>first of all. Second of all--make a point.
>
>James


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


Re: Python and Regular Expressions

2010-04-08 Thread Charles

"Nobody"  wrote in message 
news:pan.2010.04.08.10.12.59.594...@nowhere.com...
> On Wed, 07 Apr 2010 18:25:36 -0700, Patrick Maupin wrote:
>
>>> Regular expressions != Parsers
>>
>> True, but lots of parsers *use* regular expressions in their
>> tokenizers.  In fact, if you have a pure Python parser, you can often
>> get huge performance gains by rearranging your code slightly so that
>> you can use regular expressions in your tokenizer, because that
>> effectively gives you access to a fast, specialized C library that is
>> built into practically every Python interpreter on the planet.
>
> Unfortunately, a typical regexp library (including Python's) doesn't allow
> you to match against a set of regexps, returning the index of which one
> matched. Which is what you really want for a tokeniser.
>
[snip]

Really !,
 I am only a python newbie, but what about ...

import re
rr = [
  ( "id",'([a-zA-Z][a-zA-Z0-9]*)' ),
  ( "int",   '([+-]?[0-9]+)' ),
  ( "float", '([+-]?[0-9]+\.[0-9]*)' ),
  ( "float", '([+-]?[0-9]+\.[0-9]*[eE][+-]?[0-9]+)' )
]
tlist = [ t[0] for t in rr ]
pat = '^ *(' + '|'.join([ t[1] for t in rr ]) + ') *$'
p = re.compile(pat)

ss = [ ' annc', '1234', 'abcd', '  234sz ', '-1.24e3', '5.' ]
for s in ss:
  m = p.match(s)
  if m:
ix = [ i-2 for i in range(2,6) if m.group(i) ]
print "'"+s+"' matches and has type", tlist[ix[0]]
  else:
print "'"+s+"' does not match"

output:
' annc' matches and has type id
'1234' matches and has type int
'abcd' matches and has type id
'  234sz ' does not match
'-1.24e3' matches and has type float
'5.' matches and has type float

seems to me to match a (small) set of regular expressions and
indirectly return the index of the matched expression, without
doing a sequential loop over the regular expressions.

Of course there is a loop over the reults of the match to determine
which sub-expression matched, but a good regexp library (which
I presume Python has) should match the sub-expressions without
looping over them. The techniques to do this were well known in
the 1970's when the first versons of lex were written.

Not that I would recommend tricks like this. The regular
expression would quickly get out of hand for any non-trivial
list of regular expresssions to match.

Charles



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


Re: [OT] strange interaction between open and cwd

2010-05-03 Thread Charles

"Grant Edwards"  wrote in message 
news:hrn3qn$nh...@reader1.panix.com...
> On 2010-05-03, Chris Rebert  wrote:
>
>>> open(path) -> "IOError: [Errno 2] No such file or directory"
>>>
>>> i think that if the first of these seemingly "impossible" requests 
>>> fails, it
>>> is reasonable to expect that the second one also fails. but the second 
>>> one
>>> (sometimes) doesn't.
>>>
>>> i think they should always either both succeed, or both fail.
>>
>> Well, that's Unix and Worse-is-Better[1] for ya. Inelegant
>> theoretically,
>
> I don't see how it's inelegant at all.  Perhaps it's counter-intuitive
> if you don't understand how a Unix filesystem works, but the
> underlying filesystem model is very simple, regular, and elegant.
>
>> but probably makes some bit of the OS's job slightly easier and is
>> usually good enough in practice. Pragmatism is a bitch sometimes. :-)
>

I agree that the Unix file system is quite elegant, but can be 
counter-intuitive
for people who are used to the "one file, one name" paradigm.

Simplifying, if I recall correctly from Unix courses in the early 1980's,
Unix knows a file by the triple (device major number, device minor
number, inode number). Ignoring mount points, directories are simply files
that contain a map from names (components of a path) to inode numbers,
assumed to be on the same device as the directory. There can be many
references to the same inode ("hard" links). The OS keeps track of
how many references there are to a file and deletes files when they no 
longer
have any references.

Opening a file, or using a directory as the current working directory, count 
as
references. Removing a file or directory removes the reference in the file
system, but leaves the in memory references for open files or current 
directories.
Thus, removing a file (or directory) while one or more processes have an 
open
file descriptor referring to it (or have it as their current directory) does 
not
result in it being deleted. The in-memory references keep it alive, but it
is no longer accessible to other processes as it no longer has a name
in the file system.

It is (or used to be) a common unix idiom to create and open a temporary 
file
(or create a temporary directory and cd to it), and then delete it. This 
ensured
that no other processes could then access the file/directory (it no longer 
had a
name in the file system), and that the file (directory) will usually be 
deleted
by the OS when the process exits, as the only reference to the 
file/directory
is the open file descriptor/current directory in the process, which 
disappears
when the process exits. This applies even if the normal end of process
cleanup does not happen because of a (Unix) kill -9 or other major problem,
and usually applies even in case of a system crash.

In the OP's case, references to the directory have been removed from the 
file
system, but his process still has the current working directory reference to 
it,
so it has not actually been deleted. When he opens "../abc.txt", the OS 
searches
the current directory for ".." and finds the inode for /home/baz/tmp, then 
searches
that directory (/home/baz/tmp) for abc.txt and finds it.

Note that, on unix, hard links and possible duplicate NFS mounts make it 
impossible
to guarantee a unique "name" for a file. Even on windows, multiple CIFS 
mounts can
result in in being impossible to guarantee a unique name.


Charles


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


Re: Recursive functions not returning lists as expected

2010-05-03 Thread Charles

"rickhg12hs"  wrote in message 
news:2ff16113-4f79-4dcf-8310-35d2b91e8...@o11g2000yqj.googlegroups.com...
> Would a kind soul explain something basic to a python noob?
>
> Why doesn't this function always return a list?
>
> def recur_trace(x,y):
>  print x,y
>  if not x:
>return y
>  recur_trace(x[1:], y + [x[0]])
>

shouldn't it be
   return recur_trace(x[1:], y + [x[0]])
otherwise the recursive call returns nothing

Charles 


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


Re: [OT] strange interaction between open and cwd

2010-05-04 Thread Charles

"Gregory Ewing"  wrote in message 
news:84a1mcffn...@mid.individual.net...
> Charles wrote:
>
>> In the OP's case, references to the directory have been removed
>> from the file system, but his process still has the current working
>> directory reference to it, so it has not actually been deleted.
>> When he opens "../abc.txt", the OS  searches the current directory
>> for ".." and finds the inode for /home/baz/tmp,
>
> This doesn't seem to be quite correct. An experiment I just did
> reveals that the link count on the parent directory goes down by
> one when the current directory is deleted, suggesting that the ..
> link has actually been removed... yet it still works!
>
> I think what must be happening is that the kernel is maintaining
> an in-memory reference to the parent directory, and treating ".."
> as a special case when looking up a name.
>
> (This probably shouldn't be too surprising, because ".." is special
> in another way as well -- at the root of a mounted file system, it
> leads to the parent of the mount point, even though the actual ".."
> link on disk just points back to the same directory. Probably it
> simplifies the name lookup logic to always treat it specially.)

I am by no means an expert in this area, but what I think
happens (and I may well be wrong) is that the directory
is deleted on the file system. The link from the parent
is removed, and the parent's link count is decremented,
as you observed, but the directory itself is still intact with
it's original contents, including the "." and ".." names and
associated inode numbers. Unix does not normally zero
out files on deletion - the file's blocks usually retain their
contents, and I would not expect directories to be
a special case.

The blocks from the directory will be re-cycled
when the memory reference (the process's current
working directory) disappears, but until then the directory
and its contents are still accessible via the process's current
directory. This is all supposition, and based on distant
memories form the mid 1980s, I could very well be
wrong.


Charles



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


Re: global variable not working inside function. Increment

2013-05-13 Thread charles benoit
On Friday, September 4, 2009 4:52:11 PM UTC-7, Rami Chowdhury wrote:
> > global no_picked
> > no_picked = 0
> >
> > def picked(object, event):
> >   no_picked += 1
> >   print no_picked
> 
> In order to be able to affect variables in the global scope, you need to  
> declare them global inside the function, and not at the global scope. So  
> your code should read:
> 
>   no_picked = 0
> 
>   def picked(object, event):
>   global no_picked
>   no_picked += 1
>   print no_picked
> 
> I believe that will work.
> 
> On Fri, 04 Sep 2009 16:43:27 -0700, Helvin  wrote:
> 
> > Hi,
> >
> > This increment thing is driving me nearly to the nuts-stage. > <
> >
> > I have a function that allows me to pick points. I want to count the
> > number of times I have picked points.
> >
> > global no_picked
> > no_picked = 0
> >
> > def picked(object, event):
> >   no_picked += 1
> >   print no_picked
> >
> > Error msg says: UnboundLocalError: local variable 'no_picked'
> > referenced before assignment
> > For some reason, no_picked does not increment, but the printing
> > statement works.
> >
> > Do you know why?
> >
> > (I'm actually writing this for a vtkrenderwindowinteractor.)
> >
> > Helvin
> 
> 
> 
> -- 
> Rami Chowdhury
> "Never attribute to malice that which can be attributed to stupidity" --  
> Hanlon's Razor
> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)

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


executing python scripts that are symlinked

2013-05-16 Thread Charles Smith
Hi.

How can I say, from the cmd line, that python should take my CWD as my
CWD, and not the directory where the script actually is?


I have a python script that works fine when it sits in directory WC,
but if I move it out of WC to H and put a symlink from H/script to WC,
it doesn't find the packages that are in WC.  Also, if I use the
absolute path to H, it won't find them, but I guess I can understand
that.

Someone said on the net that python doesn't know whether a file is
real or a symlink, but I think that somehow, python is able to find
out where the real file is and treat that as its base of operations.

Charles.

--
http://www.creative-telcom-solutions.de
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: executing python scripts that are symlinked

2013-05-16 Thread Charles Smith
On 16 Mai, 10:18, Dave Angel  wrote:
> On 05/16/2013 03:48 AM, Charles Smith wrote:
>
> > Hi.
>
> > How can I say, from the cmd line, that python should take my CWD as my
> > CWD, and not the directory where the script actually is?
>
> > I have a python script that works fine when it sits in directory WC,
> > but if I move it out of WC to H and put a symlink from H/script to WC,
> > it doesn't find the packages that are in WC.  Also, if I use the
> > absolute path to H, it won't find them, but I guess I can understand
> > that.
>
> > Someone said on the net that python doesn't know whether a file is
> > real or a symlink, but I think that somehow, python is able to find
> > out where the real file is and treat that as its base of operations.
>
> You'd really better specify your environment - exact OS and Python
> version.  symlink and cwd usually imply a Unix-type system, but cmd is a
> Windows thing.
>
> Then give examples of what your cwd is, what string you're typing at the
> shell prompt, and what's happening.


Well, I'm on a ubuntu platform, running subversion, but I can't commit
this debugging tool into the working copy where I'm using it, so I
maintain it in my home directory.  The tool does use production
packages, though.

So, if I say,

  $ python fapi-test.py

and fapi-test.py really is there, then it works, using the codec
production package.  But if I use a symlink instead, it says

Traceback (most recent call last):
  File "test2", line 1, in 
from codec.support import *
ImportError: No module named codec.support


Python tells me Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)



--
http://www.creative-telcom-solutions.de

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


Re: executing python scripts that are symlinked

2013-05-16 Thread Charles Smith
On 16 Mai, 11:04, Steven D'Aprano  wrote:
> Python does use your current working directory as your current working
> directory. I think you are misdiagnosing the problem.


That's usually how it ends up ...



>
> Here's a demonstration:
>
> steve@runes:~$ cat test.py
> import os
> print os.getcwd()
>
> steve@runes:~$ ln -s ~/test.py /tmp/test
> steve@runes:~$ ls -l /tmp/test
> lrwxrwxrwx 1 steve steve 19 May 16 18:58 /tmp/test -> /home/steve/test.py
> steve@runes:~$ cd /etc/
> steve@runes:/etc$ python /tmp/test
> /etc


You're right.  I can believe that python doesn't really change it's
notion of the CWD.

It seems like when I'm in WC and invoke ./script (which is symlinked
to H/script), python says, "I have a specification somewhere that says
I can look for modules where my script is, and since I'm really smart,
I happen to know that I'm in WC but the script is not, but is really
in H, where the stupid operator better have his packages set up"


>
> > I have a python script that works fine when it sits in directory WC, but
> > if I move it out of WC to H and put a symlink from H/script to WC, it
> > doesn't find the packages that are in WC.  Also, if I use the absolute
> > path to H, it won't find them, but I guess I can understand that.
>
> The obvious solution is to make sure that WC is in the Python path.
...

> but that's a crappy solution,

Right.  Other tools don't try to figure out what I really want to do
with a symlink, but just accept that it's a file.  Python should do
the same ...

But, as you say, I'm surely misdiagnosing the problem.

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


subclassing from unittest

2013-05-22 Thread Charles Smith
Hi,

I'd like to subclass from unittest.TestCase.  I observed something
interesting and wonder if anyone can explain what's going on... some
subclasses create  null tests.

I can create this subclass and the test works:

  class StdTestCase (unittest.TestCase):
  blahblah

and I can create this subsubclass and the test works:

  class aaaTestCase (StdTestCase):
  moreblahblah

but if I create this subsubclass (or any where the first letter is
capital):

  class AaaTestCase (StdTestCase):
  differentblahblah

the test completes immediately without any work being done.

I suspect that the answer is in the prefix printed out by the test.  I
have diffed both the long output (tests works, on the left) and the
short output (null test, on the right):

test
(TC_02.TestCase_F__ULLA05__AM_Tx) ...  <
test suite has  ,   test suite has  ,
 
>,
 ]><
 
>   -->  test_api_socket:the address specified is:  127.0.0.1
 
>
 
>
 
>
 
>
--
 
>   Ran 0 tests in 0.000s
 
>
 
>   OK


I see an empty test somehow gets sorted to the beginning of the list.
How could that be a result of whether the first letter of the class is
capitalized or not?

Thanks in advance...
cts


http://www.creative-telcom-solutions.de
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subclassing from unittest

2013-05-22 Thread Charles Smith
On 22 Mai, 17:32, Charles Smith  wrote:
> Hi,
>
> I'd like to subclass from unittest.TestCase.  I observed something
> interesting and wonder if anyone can explain what's going on... some
> subclasses create  null tests.
>
> I can create this subclass and the test works:
>
>   class StdTestCase (unittest.TestCase):
>       blahblah
>
> and I can create this subsubclass and the test works:
>
>   class aaaTestCase (StdTestCase):
>       moreblahblah
>
> but if I create this subsubclass (or any where the first letter is
> capital):
>
>   class AaaTestCase (StdTestCase):
>       differentblahblah
>
> the test completes immediately without any work being done.
>
> I suspect that the answer is in the prefix printed out by the test.  I
> have diffed both the long output (tests works, on the left) and the
> short output (null test, on the right):
>
> test
> (TC_02.TestCase_F__ULLA05__AM_Tx) ...                  <
> test suite has   tests=[]>,       test suite has   tests=[,
>
> >    ,
>
>   tests=[    tests=[    tests=[    tests=[    tests=[    tests=[    tests=[]>]>                                        <
>
> >   -->  test_api_socket:the address specified is:  127.0.0.1
>
> --
>
> >   Ran 0 tests in 0.000s
>
> >   OK
>
> I see an empty test somehow gets sorted to the beginning of the list.
> How could that be a result of whether the first letter of the class is
> capitalized or not?
>
> Thanks in advance...
> cts
>
> http://www.creative-telcom-solutions.de


Unfortunately, the side-by-side diff didn't come out so well  ...

---
http://www.creative-telcom-solutions.de
-- 
http://mail.python.org/mailman/listinfo/python-list


python adds an extra half space when reading from a string or list

2013-06-28 Thread charles benoit
number_drawn=()
def load(lot_number,number_drawn):
first=input("enter first lot: ")
last=input("enter last lot: ")
for lot_number in range(first,last):
line_out=str(lot_number)
for count in range(1,5):
number_drawn=raw_input("number: ")
line_out=line_out+(number_drawn)
print line_out
finale_line.append(line_out)
finale_line2=finale_line

load(lot_number,number_drawn)


print finale_line
print(" "*4),
for n in range(1,41):
print n,  #this is to produce a line of numbers to compare to
output#
for a in finale_line:
print"\n",
print a[0]," ",
space_count=1
for b in range(1,5):
if int(a[b])<10:
 print(" "*(int(a[b])-space_count)),int(a[b]),
 space_count=int(a[b])
else:
print(" "*(a[b]-space_count)),a[b],
space_count=a[b]+1







number_drawn=()
def load(lot_number,number_drawn):
first=input("enter first lot: ")
last=input("enter last lot: ")
for lot_number in range(first,last):
line_out=str(lot_number)
for count in range(1,5):
number_drawn=raw_input("number: ")
line_out=line_out+(number_drawn)
print line_out
finale_line.append(line_out)
finale_line2=finale_line

load(lot_number,number_drawn)


print finale_line
print(" "*4),
for n in range(1,41):
print n,  #this is to produce a line of numbers to compare to
output#
for a in finale_line:
print"\n",
print a[0]," ",
space_count=1
for b in range(1,5):
if int(a[b])<10:
 print(" "*(int(a[b])-space_count)),int(a[b]),
 space_count=int(a[b])
else:
print(" "*(a[b]-space_count)),a[b],
space_count=a[b]+1








this generates

enter first lot: 1
enter last lot: 4
number: 2
number: 3
number: 4
number: 5
12345
number: 1
number: 2
number: 3
number: 4
21234
number: 3
number: 4
number: 5
number: 6
33456
['12345', '21234', '33456']
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
27 28 29 30 31 32 33 34 35 36 37 38 39 40
1 2   3   4   5
21   2   3   4
3  3   4   5   6
>#as you can see many numbers are between the lines of a normal print#
#I thought this was due to "white space" int he format .So I tried  a list
of strings and got the same results.#
-- 
http://mail.python.org/mailman/listinfo/python-list


exception problem

2012-06-24 Thread Charles Hixson

The code:
print("pre-chunkLine")
chunks=[]
try:
chunks=self.chunkLine (l)
except:
print("caught exception")
print (sys.exc_info()[:2])
finally:
print ("at finally")
print ("chunks =")
print (repr(chunks), ".", end = ":")
produces this result:
  . . ., by
pre-chunkLine
caught exception
at finally
path  3...

Any suggestions as to what's wrong with the code?
FWIW, chunkLine begins:
def chunkLine (self, line):
print("chunkLine: ")
print ("line = ", line)
ifline == None:
return[]
assert(isinstance (line, str) )

--
Charles Hixson

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


Re: exception problem

2012-06-24 Thread Charles Hixson

Sorry, I left out:
er$ python3 --version
Python 3.2.3rc1

On 06/24/2012 03:26 PM, Charles Hixson wrote:

The code:
print("pre-chunkLine")
chunks=[]
try:
chunks=self.chunkLine (l)
except:
print("caught exception")
print (sys.exc_info()[:2])
finally:
print ("at finally")
print ("chunks =")
print (repr(chunks), ".", end = ":")
produces this result:
  . . ., by
pre-chunkLine
caught exception
at finally
path  3...

Any suggestions as to what's wrong with the code?
FWIW, chunkLine begins:
def chunkLine (self, line):
print("chunkLine: ")
print ("line = ", line)
ifline == None:
return[]
assert(isinstance (line, str) )




--
Charles Hixson

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


Re: exception problem

2012-06-24 Thread Charles Hixson

On 06/24/2012 03:43 PM, MRAB wrote:

On 24/06/2012 23:26, Charles Hixson wrote:

The code:
  print("pre-chunkLine")
  chunks=[]
  try:
  chunks=self.chunkLine (l)
  except:
  print("caught exception")
  print (sys.exc_info()[:2])
  finally:
  print ("at finally")
  print ("chunks =")
  print (repr(chunks), ".", end = ":")
produces this result:
. . ., by
pre-chunkLine
caught exception
at finally
path  3...

Any suggestions as to what's wrong with the code?
FWIW, chunkLine begins:
  def chunkLine (self, line):
  print("chunkLine: ")
  print ("line = ", line)
  ifline == None:
  return[]
  assert(isinstance (line, str) )


Don't use a bare "except"; it'll catch _any__exception. Catch only what
you expect.

For all I know, it could be that the name "l" doesn't exist.
But what I wanted was to catch any exception.  A problem was happening 
and I had no clue as to what it was.  (It turned out to be "self is not 
defined".  A silly mistake, but a real one.)


The odd thing was that if I ran it without the try block, I didn't get 
any exceptions at all.  (Which I clearly should have, except that since 
self wasn't defined, I'd usually expect the interpreter to detect the 
error before trying to execute the code.)


--
Charles Hixson

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


Re: exception problem

2012-06-24 Thread Charles Hixson

On 06/24/2012 03:43 PM, Charles Hixson wrote:

On 06/24/2012 03:36 PM, Chris Angelico wrote:

On Mon, Jun 25, 2012 at 8:26 AM, Charles Hixson
  wrote:

The code:
finally:
print ("at finally")
print ("chunks =")
produces this result:
path  3...

Can you state more clearly the problem, please? I'm seeing output that
can't have come from the code posted (for instance, immediately after
the "at finally", I'm expecting to see the "chunks =" line), and I'm
not seeing any exception information, so I can't even hazard a guess
as to what's throwing the exception.

Presumably these are two methods in the same class, since you're
calling it as "self.chunkLine", but beyond that, it's hard to know.
Take off the try/except and let your exception go to console, that's
usually the easiest thing to deal with.

Chris Angelico
Sorry, but it *DID* come from the code posted.  Which is why I was so 
confused.  I finally tracked it down to "self was not defined" by 
altering the except section to read:

except BaseException as ex:
print("caught exception")
print (ex)
finally:
print ("at finally")

The documentation section covering the except statement could stand to 
be a *LOT* clearer.   I read the sections on the except statement and 
exception handlers several times and couldn't figure out was the "as" 
argument of the except statement was for.  "Target" doesn't communicate 
much to me.  The one I finally used as indicated above was modified from 
some code that I found through Google.  I still don't really know what 
"as" means, except that if you use it, and you print out the "target", 
you'll get some kind of informative message.  (The one that I got said 
"self was not defined" .. that's a paraphrase.  I can't remember the 
precise wording.)  And that interpretation is based on what the result 
was, not on anything said in the documentation.


IIRC, the Python2 documentation used code examples to indicate what was 
the right way to write an exception handler.  I realize that Python3 is 
much different, but that approach was a very good one.





--
Charles Hixson

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


Re: exception problem

2012-06-25 Thread Charles Hixson

On 06/24/2012 11:23 PM, Andrew Berg wrote:

On 6/25/2012 12:27 AM, Charles Hixson wrote:
   

The documentation section covering the except statement could stand to
be a *LOT* clearer.   I read the sections on the except statement and
exception handlers several times and couldn't figure out was the "as"
argument of the except statement was for.
 

I agree that the tutorial doesn't explain the use of "as" very well, but
it does cover that a bare except is not normally good to use:
"The last except clause may omit the exception name(s), to serve as a
wildcard. Use this with extreme caution, since it is easy to mask a real
programming error in this way!"

   

I still don't really know what
"as" means, except that if you use it, and you print out the "target",
you'll get some kind of informative message.
 

"as" lets you refer to the exception object that was caught. I find this
useful mainly for exceptions that have attributes (most built-in
exceptions don't, but many user-defined exceptions do). A full traceback
is much more useful for debugging than what a simple print(exc) will give.
There are a few different ways to get traceback information without
letting the exception simply propagate and terminate the program. You
can get some simple information from sys.exc_info() (and you can feed
the traceback object to a function in the traceback module), or you can
log it with the logging.exception() function or the exception() method
of a Logger from the same module. I recommend using logging. However,
it's generally best to just let any unexpected exceptions propagate
unless the program absolutely must continue, especially when debugging.
   
I read that that would happen, but "  print (sys.exc_info()[:2]) " 
didn't even yield a blank line.  It must have executed, because the 
print statement on the line before it executed, and there wasn't a loop 
or a jump (and also execution continued "normally" [the code still has 
bugs] afterward even if the finally isn't included).


--
Charles Hixson

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


Re: exception problem

2012-06-27 Thread Charles Hixson

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

On Sun, 24 Jun 2012 16:16:25 -0700, Charles Hixson wrote:

   

But what I wanted was to catch any exception.
 

Be careful of what you ask for, since you might get it.

"Catch any exception" is almost certainly the wrong thing to do, almost
always. The one good reason I've seen for a bare except is to wrap the
top level of an application in order to redirect uncaught exceptions to
something other than the console (such as a GUI error dialog box). And
even then, you probably don't want to catch *all* exceptions, but only
those that inherit from Exception:

try:
 main()  # run my application
except Exception as err:
 display_error_dialog(err)
 # or log to a file, or something...



   
This time it was the right thing, as I suspected that *SOME* exception 
was being thrown, but had no idea what one.  The problem was I didn't 
know how to print the result when I caught the exception.  This has 
since been cleared up, but first I found it on Google, and then I was 
told about it on the list.  The documentation left me totally ... well, 
not uninformed, but confused.  As I said it turned out to be a method 
call on an uninitialized variable, as I found out once I figured out how 
to list the result of catching the exception.  Which is what I expected 
the documentation to show me how to do.


The comments on the list have been vastly helpful, even if they still 
tend to assume that I know more than I do.  (And even if some of them 
seem to be a bit ... off.  E.g., suggesting that I generate the 
exception on purpose so I can find out what it is, when I started off 
with no idea as to WHAT the problem was.)


What really annoys me is the way the documentation has worsened since 
python 2.5, but if you know what it is trying to tell you, then I guess 
you aren't bothered by undefined terms and lack of examples.  I went 
away from programming in Python for a couple of years though, and I 
guess I missed the transition, or something.


--
Charles Hixson

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


How do I display unicode value stored in a string variable using ord()

2012-08-16 Thread Charles Jensen
Everyone knows that the python command

 ord(u'…')

will output the number 8230 which is the unicode character for the horizontal 
ellipsis.

How would I use ord() to find the unicode value of a string stored in a 
variable?  

So the following 2 lines of code will give me the ascii value of the variable 
a.  How do I specify ord to give me the unicode value of a?

 a = '…'
 ord(a)
-- 
http://mail.python.org/mailman/listinfo/python-list


Which Version of Python?

2012-09-11 Thread Charles Hottel
 I have a lot of programming experience in many different languages and now 
I want to learn Python.  Which version do you suggest I download, Python 2.x 
or Python 3.x ?  Also why should I prefer one over the other?

Right now I am thinkng Python 3.x as it has been out since 2008, but I have 
some concerns about backward compatibility with older packages that I might 
want to use.

Thanks for your ideas and help. 


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


'generator ignored GeneratorExit''

2012-10-20 Thread Charles Hixson
If I run the following code in the same module, it works correctly, but 
if I import it I get the message:
Exception RuntimeError: 'generator ignored GeneratorExit' in object getNxtFile at 0x7f932f884f50> ignored


def getNxtFile (startDir, exts = ["txt", "utf8"]):
try:
forpathingetNxtPath (startDir, exts):
try:
fil=open (path, encoding = "utf-8-sig")
yieldfil
except:
print ("Could not read:  ", path)
exceptGeneratorExit:
raiseStopIteration

The message appears to be purely informational, but I *would* like to 
fix whatever problem it's reporting, and none of the changes that I've 
tried have worked.  What *should* I be doing?


--
Charles Hixson

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


Re: 'generator ignored GeneratorExit''

2012-10-20 Thread Charles Hixson

On 10/20/2012 04:28 PM, Ian Kelly wrote:

On Sat, Oct 20, 2012 at 2:03 PM, Charles Hixson
  wrote:

If I run the following code in the same module, it works correctly, but if I
import it I get the message:
Exception RuntimeError: 'generator ignored GeneratorExit' in  ignored

def getNxtFile (startDir, exts = ["txt", "utf8"]):
 try:
 forpathingetNxtPath (startDir, exts):
 try:
 fil=open (path, encoding = "utf-8-sig")
 yieldfil
 except:
 print ("Could not read:  ", path)
 exceptGeneratorExit:
 raiseStopIteration

The message appears to be purely informational, but I *would* like to fix
whatever problem it's reporting, and none of the changes that I've tried
have worked.  What *should* I be doing?

The bare except is probably catching the GeneratorExit exception and
swallowing it.  Try catching a more specific exception like OSError or
even just Exception instead.

Also, you don't need to explicitly catch GeneratorExit just to raise
StopIteration.  The generator will normally stop on GeneratorExit,
provided the exception is actually able to propagate up.
Thank you.  That was, indeed the problem.  Removing all the try ... 
excepts made it work on my test case.  Now I've got to figure out what 
to catch in case it's not a utf8 file.  I guess that I'll hope that 
IOError will work, as nothing else sounds reasonable.  It's general 
enough that it ought to work.



--
Charles Hixson

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


bit count or bit set && Python3

2012-10-25 Thread Charles Hixson
In Python3 is there any good way to count the number of on bits in an 
integer (after an & operation)?
Alternatively, is there any VERY light-weight implementation of a bit 
set?  I'd prefer to use integers, as I'm probably going to need 
thousands of these, if the tests work out.  But before I can test, I 
need a decent bit counter.  (shift, xor, &, and | are already present 
for integer values, but I also need to count the number of "true" items 
after the logical operation.  So if a bitset is the correct approach, 
I'll need it to implement those operations, or their equivalents in 
terms of union and intersection.)


Or do I need to drop into C for this?

--
Charles Hixson

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


bit count or bit set && Python3

2012-10-25 Thread Charles Hixson
In Python3 is there any good way to count the number of on bits in an 
integer (after an & operation)?
Alternatively, is there any VERY light-weight implementation of a bit 
set?  I'd prefer to use integers, as I'm probably going to need 
thousands of these, if the tests work out.  But before I can test, I 
need a decent bit counter.  (shift, xor, &, and | are already present 
for integer values, but I also need to count the number of "true" items 
after the logical operation.  So if a bitset is the correct approach, 
I'll need it to implement those operations, or their equivalents in 
terms of union and intersection.)


Or do I need to drop into C for this?

--
Charles Hixson

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


Re: bit count or bit set && Python3

2012-10-25 Thread Charles Hixson

On 10/25/2012 08:57 AM, Steven D'Aprano wrote:

On Fri, 26 Oct 2012 02:31:53 +1100, Chris Angelico wrote:


On Fri, Oct 26, 2012 at 2:25 AM, Christian Heimes
wrote:

Simple, easy, faster than a Python loop but not very elegant:

bin(number).count("1")

Unlikely to be fast.

Oh I don't know about that. Here's some timing results using Python 2.7:

py>  from timeit import Timer
py>  t = Timer('bin(number).count("1")', setup='number=2**10001-1')
py>  min(t.repeat(number=1, repeat=7))
0.6819710731506348

Compare to MRAB's suggestion:

def count_set_bits(number):
  count = 0
  while number:
  count += 1
  number&= number - 1
  return count

py>  t = Timer('count_set_bits(number)',
... setup='from __main__ import count_set_bits; number=2**10001-1')
py>  min(t.repeat(number=100, repeat=7))
4.141788959503174


That makes the "inelegant" solution using bin() and count() about 600
times faster than the mathematically clever solution using bitwise
operations.

On the other hand, I'm guessing that PyPy would speed up MRAB's version
significantly.



Really nice and good to know.  I had guessed the other way.   (As you 
point out this is compiler dependent, and I'll be using Python3, 
but...conversion from an int to a bit string must be a *lot* faster than 
I had thought.)


--
Charles Hixson

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


bit count or bit set && Python3

2012-10-25 Thread Charles Hixson
In Python3 is there any good way to count the number of on bits in an 
integer (after an & operation)?
Alternatively, is there any VERY light-weight implementation of a bit 
set?  I'd prefer to use integers, as I'm probably going to need 
thousands of these, if the tests work out.  But before I can test, I 
need a decent bit counter.  (shift, xor, &, and | are already present 
for integer values, but I also need to count the number of "true" items 
after the logical operation.  So if a bitset is the correct approach, 
I'll need it to implement those operations, or their equivalents in 
terms of union and intersection.)


Or do I need to drop into C for this?

--
Charles Hixson

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


Re: bit count or bit set && Python3

2012-10-26 Thread Charles Hixson

cas...@gmail.com wrote:

On Thursday, October 25, 2012 7:56:25 AM UTC-7, Charles Hixson wrote:

In Python3 is there any good way to count the number of on bits in an
integer (after an&  operation)?

You may want to look at gmpy2[1] and the popcount() function.


Alternatively, is there any VERY light-weight implementation of a bit
set?  I'd prefer to use integers, as I'm probably going to need
thousands of these, if the tests work out.  But before I can test, I
need a decent bit counter.  (shift, xor,&, and | are already present
for integer values, but I also need to count the number of "true" items
after the logical operation.  So if a bitset is the correct approach,


Whether or not gmpy2 is considered light-weight is debateable. :)


I'll need it to implement those operations, or their equivalents in
terms of union and intersection.)



Or do I need to drop into C for this?


[1] http://code.google.com/p/gmpy/



--

Charles Hixson
I can see many times when that would be useful, but for this particular 
case I think that bin(val).count("1") is probably the better solution.  
The other options that I need are already available directly in integer 
numbers, and I will be surprised if I need more than a 32-bit set, so 
integers should be a reasonable approach.  It doesn't seem to have the 
overhead that I feared a string conversion would have (possibly because 
converting an integer to a bit string is trivial),  so I don't think 
that gmpy would add value to this program.


Next I need to decide about weak pointers, and then shelve vs. 
tokyocabinet.  (I sort of don't like shelve, because of its use of 
pickle, with the attendent security risks.  OTOH, the file will be local 
to the computer, not going over the net, which minimizes that.  Still, I 
may decide to reimplement it using ast.literal_eval, as I'm not 
intending to store anything that it won't handle.

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


except clause syntax question

2012-01-30 Thread Charles Yeomans
To catch more than one exception type in an except block, one writes

except (A, B, C) as e:

I'm wondering why it was decided to match tuples, but not lists:

except [A, B, C] as e:

The latter makes more sense semantically to me -- "catch all exception types in 
a list" as opposed to "catch this single thing composed of three exception 
types".


Charles Yeomans


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


Re: except clause syntax question

2012-01-30 Thread Charles Yeomans

On Jan 30, 2012, at 12:56 PM, Aaron wrote:

> On 01/30/2012 06:41 PM, Charles Yeomans wrote:
>> To catch more than one exception type in an except block, one writes
>> 
>> except (A, B, C) as e:
>> 
>> I'm wondering why it was decided to match tuples, but not lists:
>> 
>> except [A, B, C] as e:
>> 
>> The latter makes more sense semantically to me -- "catch all exception types 
>> in a list" as opposed to "catch this single thing composed of three 
>> exception types".
>> 
>> 
>> Charles Yeomans
>> 
>> 
> 
> Then,  semantically, shouldn't it be a set?

Why, I suppose that would make even more sense.


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


Re: except clause syntax question

2012-01-31 Thread Charles Yeomans

On Jan 30, 2012, at 7:00 PM, Steven D'Aprano wrote:

> On Mon, 30 Jan 2012 12:41:00 -0500, Charles Yeomans wrote:
> 
>> To catch more than one exception type in an except block, one writes
>> 
>> except (A, B, C) as e:
>> 
>> I'm wondering why it was decided to match tuples, but not lists:
>> 
>> except [A, B, C] as e:
> 
> Simplicity.
> 
> If you also allow lists, then why not allow arbitrary sequences? What 
> about iterators, do you allow them? That could be awkward, because 
> iterators can only be run through once. Dictionaries are also iterable, 
> so once you allow arbitrary iterables, you get dicts. The whole thing 
> becomes a mess. Better to keep it simple and only allow a single 
> canonical collection type, and in Python, that type is tuple, not list.
> 
> Tuples are that canonical collection type because they have a number of 
> desirable properties:
> 
> - Tuples are small and memory efficient, using the smallest amount of
>  memory needed to hold their items. Lists typically carry a block of
>  spare memory, to make insertions fast.
> 
> - Consequently the Python virtual machine can create them rapidly and
>  efficiently.
> 
> - Tuples are immutable, so you don't have to worry about passing one to a
>  function and having the function modify it behind your back.
> 
> - Tuples are ordered, for the times where that matters.
> 
> - Since the typical use-case is to iterate over the items in fixed order,
>  there's no need to pay the extra expense for a dict or set.
> 
> - Tuples are simple to write: in general you only need commas between
>  items. Sometimes, to avoid ambiguity or change the precedence of
>  calculation, you also need round brackets (parentheses for Americans).
>  Except clauses are one of those times.
> 
> - Frozensets and sets are ruled out for historical reasons: they didn't
>  exist until Python 2.3. Besides, which would you rather write?
> 
>  ("abc", "def")
>  frozenset([abc", "def"])
> 
> - Sets and lists are ruled out because they are mutable, both require
>  much more memory, and sets have a heavier computational burden.
> 
> 
> 
>> The latter makes more sense semantically to me -- "catch all exception
>> types in a list" as opposed to "catch this single thing composed of
>> three exception types".
> 
> Then you are labouring under a misunderstanding. You're not catching a 
> tuple, because tuples are never thrown. You're catching any of the 
> exceptions that are contained in that tuple.
> 
> Both lists and tuples *are* single things in themselves. Both lists and 
> tuples are containers:
> 
> A list is a single thing that contains other things. 
> 
> A tuple is a single thing that contains other things.
> 

I don't think of a tuple as a container, and I don't think it a 
misunderstanding on my part to think this.  But I am aware that it is common to 
use tuples as immutable lists.  

I don't see that performance was really a consideration, given that one can use 
any expression in an except statement --

except IOError if today == 'Monday' else OSError as e

or 

L = []
try:
#code

except tuple(L) as e:
pass

except Exception, e:
L.append(e.__class__)

In any case, though I appreciate your attempt at a post hoc justification, I 
was hoping for a positive explanation. 

Charles Yeomans


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


Re: except clause syntax question

2012-01-31 Thread Charles Yeomans

On Jan 31, 2012, at 9:51 AM, Steven D'Aprano wrote:

> On Tue, 31 Jan 2012 08:57:31 -0500, Charles Yeomans wrote:
> 
>> I don't think of a tuple as a container, and I don't think it a
>> misunderstanding on my part to think this.
> 
> Well, it is a misunderstanding, because tuples ARE containers. You might 
> as well say "I don't think of boxes as containers". What exactly are they 
> if not containers?


Tuple is a heterogenous datatype that allows one to define objects ad hoc. That 
is to say, a tuple represents a single thing distinct from its components.  For 
example, suppose you need to represent a location in text by line number and 
offset within a line.  A tuple object makes it easy to do so without writing a 
class having no methods other than a constructor.  Here, the components, a line 
number and an offset, define a new object distinct from the pieces.

One can certainly view a tuple as a list, just as one can view a string as a 
list of characters, and sometimes that's useful; the Python dictum "there 
should only be one way to do it" doesn't imply that there is only one way to 
think of it.

Nor am I the only person who sees such a distinction between tuple and list.


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


Re: except clause syntax question

2012-01-31 Thread Charles Yeomans

On Jan 31, 2012, at 11:38 AM, Devin Jeanpierre wrote:

> On Tue, Jan 31, 2012 at 11:23 AM, Charles Yeomans
>  wrote:
>> 
>> On Jan 31, 2012, at 9:51 AM, Steven D'Aprano wrote:
>> 
>>> On Tue, 31 Jan 2012 08:57:31 -0500, Charles Yeomans wrote:
>>> 
>>>> I don't think of a tuple as a container, and I don't think it a
>>>> misunderstanding on my part to think this.
>>> 
>>> Well, it is a misunderstanding, because tuples ARE containers. You might
>>> as well say "I don't think of boxes as containers". What exactly are they
>>> if not containers?
>> 
>> 
>> Tuple is a heterogenous datatype that allows one to define objects ad hoc. 
>> That is to say, a tuple represents a single thing distinct from its 
>> components.  For example, suppose you need to represent a location in text 
>> by line number and offset within a line.  A tuple object makes it easy to do 
>> so without writing a class having no methods other than a constructor.  
>> Here, the components, a line number and an offset, define a new object 
>> distinct from the pieces.
>> 
>> One can certainly view a tuple as a list, just as one can view a string as a 
>> list of characters, and sometimes that's useful; the Python dictum "there 
>> should only be one way to do it" doesn't imply that there is only one way to 
>> think of it.
>> 
>> Nor am I the only person who sees such a distinction between tuple and list.
> 
> Perhaps it'd be useful to look at how the Python language reference
> defines containers?
> 
> Quote:
> 
> Some objects contain references to other objects; these are called
> containers. Examples of containers are tuples, lists and dictionaries.
> The references are part of a container’s value. In most cases, when we
> talk about the value of a container, we imply the values, not the
> identities of the contained objects; however, when we talk about the
> mutability of a container, only the identities of the immediately
> contained objects are implied. So, if an immutable container (like a
> tuple) contains a reference to a mutable object, its value changes if
> that mutable object is changed.
> 
> End quote.
> (Offtopic: How do I do an external block quote appropriately in an email?)
> 
> Tuples are most certainly containers, precisely _because_ they're an
> ad-hoc way to define objects, where the only purpose of the object is
> to contain the values inside the tuple.
> 
> But these are just words and it's beside the point. We should talk of
> things as if the word "container" didn't matter, because I don't think
> that's what you meant, but neither do I want to put words in your
> mouth.
> 
> My interpretation is that you see tuples as an object where you can
> get meaningfully things by field, rather than just grab arbitrarily
> from a bag of things. This isn't the only way they are used, see the
> except statement (hee) and their use as keys in dictionaries. But it
> is true that their immutable length makes them very well suited to the
> task of representing product types.

I had read that bit of documentation, and don't entirely agree with it.  
Certainly many objects contain references to other objects, but are not 
considered containers.

And I claim that tuples are most certainly not containers, when they are used 
to define an object as a collection of other objects, like the text-location 
example I offered earlier.  On the other hand, it is certainly true that tuples 
quack like containers, as do strings.


Charles Yeomans


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


Re: except clause syntax question

2012-01-31 Thread Charles Yeomans

On Jan 31, 2012, at 8:24 AM, Mel Wilson wrote:

> Charles Yeomans wrote:
> 
>> To catch more than one exception type in an except block, one writes
>> 
>> except (A, B, C) as e:
>> 
>> I'm wondering why it was decided to match tuples, but not lists:
>> 
>> except [A, B, C] as e:
>> 
>> The latter makes more sense semantically to me -- "catch all exception
>> types in a list" as opposed to "catch this single thing composed of three
>> exception types".
> 
> On reflection, it seems to hint at a style that Python extensions were made 
> in.  (IIRC) the first operand in an `except` statement was originally just 
> an arbitrary marker to identify the exception.  Unique string values were 
> customary, although the Python library defined things with standard 
> exception names.  Using a string means that general exceptions weren't to be 
> collected in general sequences; `except "Serious Error"` was never meant to 
> catch `raise "r"`.  If only tuples were used for collections, it would 
> create havoc for fewer of any weirdos who had used strange markers of their 
> own devising.
> 
> It looks like tuples were chosen as the most "lightweight", or maybe least 
> intrusive, sequence type to require to denote a collection of exceptions.
> 
> You see a similar decision, with the opposite emphasis, with the string 
> modulo operator.  The second operand is supposed to be a tuple, but if the 
> template string needs only one value, then the rules are relaxed and any 
> single non-tuple value is used as-is.
> 

Compatilbility; that makes sense.  I came to python well after strings were 
used for exceptions.  Thanks.


Charles Yeomans

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


Re: except clause syntax question

2012-01-31 Thread Charles Yeomans

On Jan 31, 2012, at 7:12 PM, Terry Reedy wrote:

> On 1/31/2012 8:57 AM, Charles Yeomans wrote:
> 
>> In any case, though I appreciate your attempt at a post hoc justification,
> > I was hoping for a positive explanation.
> 
> I think the best you are going to get is that Python somewhat consistently*, 
> for both practical and historical reasons#, uses tuples when the syntax 
> allows an object or collection of objects.
> 
> * except, isinstance, isubclass, ''%x, perhaps other places.
> 
> In the last case, that creates a problem when one wants to interpolate a 
> tuple as an object rather than having it viewed as a container of several 
> objects to be interpolated. That was on
> 
> # Python once treated tuples as different from lists in ways that is not true 
> now. (Read the 1.5 docs if really interested.)
> 


I'll do that.  Thanks.


Charles Yeomans

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


indexed property? Can it be done?

2012-05-07 Thread Charles Hixson

class Node:

def__init__(self, nodeId, key, value, downRight, downLeft, parent):
dirty=True
dlu=utcnow()
self.node=[nodeId, downLeft, [key], [value], 
[downRight], parent, dirty, dlu]


Note that node[3] is a list of keys (initially 1) and node[3] is a list 
of values, etc.


What I'd like to do is to be able to address them thusly:
k = node.key[2]
v = node.value[2]
but if there's a way to do this, I haven't been able to figure it out.  
Any suggestions?


--
Charles Hixson

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


Re: indexed property? Can it be done?

2012-05-07 Thread Charles Hixson

On 05/07/2012 08:33 PM, Chris Rebert wrote:

On Mon, May 7, 2012 at 8:15 PM, Charles Hixson
  wrote:
   

class Node:

def__init__(self, nodeId, key, value, downRight, downLeft, parent):
dirty=True
dlu=utcnow()
self.node=[nodeId, downLeft, [key], [value], [downRight],
parent, dirty, dlu]
 

Why are you using a single opaque list instead of separate, meaningful
attributes for each datum?

Cheers,
Chris

   
Because that's the most reasonable implementation.  The various list 
items would not be the same from instance to instance.  I could pull the 
top-level list items off as separate variables, but this would leave the 
problem exactly where it is, and ordinary properties allow me to address 
the entries like id, and dlu without problem.  But the list variables 
are a separate problem, and not so readily soluble.


FWIW, if I must I can operate with only a list, and define functions to 
do the access and manipulation.  I'd rather not, which is why I'm 
exploring whether an indexed property is feasible.


Note that I *could* return, e.g., the entire keys list, but I'd rather 
use a bit more data protection than that.  Which is what an indexed 
setter property would allow.  And node.key[3] is as fully informative a 
name as I can construct for that entry.  But the number of items in the 
keys list varies from node to node, so defining a key3 property is not 
reasonable.  (Besides, that's so ugly that I'd rather use a function, 
even though indexing in Python really should be done with brackets 
rather than parens.)


--
Charles Hixson

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


Re: indexed property? Can it be done?

2012-05-07 Thread Charles Hixson

On 05/07/2012 08:44 PM, Dan Sommers wrote:

On Mon, 07 May 2012 20:15:36 -0700
Charles Hixson  wrote:

   

class Node:

  def__init__(self, nodeId, key, value, downRight, downLeft,
parent): dirty=True
  dlu=utcnow()
  self.node=[nodeId, downLeft, [key], [value],
[downRight], parent, dirty, dlu]

Note that node[3] is a list of keys (initially 1) and node[3] is a
list of values, etc.

What I'd like to do is to be able to address them thusly:
k = node.key[2]
v = node.value[2]
but if there's a way to do this, I haven't been able to figure it
out. Any suggestions?
 

Untested:

def __init__(self, nodeId, key, value, downRight, downLeft, parent):
 dirty = True
 dlu = utcnow()
 self.node = [nodeId, downLeft, dict(key=value),
  [downRight], parent, dirty, dlu]

Now you can use self.node[2][key] to get/set value.

But why not make the elements of node their own attributes?

Untested:

def __init__(self, nodeId, key, value, downRight, downLeft, parent):
 self.dirty = True
 self.dlu = utcnow()
 self.nodeId = nodeId
 self.downLeft = downLeft
 self.downRight = downRight
 self.values = dict(key=value)
 self.parent = parent

And then you don't have to remember that node[2] is the key/value pairs
(note the typo (the two "3"s) in your original post).  With each
attribute in its own, well, attribute, you can always use
node.values[key] to access the value associated with a particular key.

HTH,
Dan
   
Did you notice that the node list contained sublists?  I can access the 
top level node items through ordinary properties, and that is my 
intent.  So I don't need to remember what top level index represents 
what item.  But the second level items are variable in length, so I 
really want to do an indexed access to them.


Yes, I admit that in the snipped defined by the __init__ method those 
secondary lists only received one entry.  Other method would extend 
their length, to a variable amount for different class instances.


A part of the reason that the class retains that top level list is so 
that if I can't create an indexed property to get and set them, I can 
revert to an alternative that is a bit uglier than this, but might be 
more efficient.  (It would have methods that operated directly on the 
list rather than using properties for ANY of the approach...and avoid 
creating a class that they handle.  Not as clean as what I'm hoping for, 
but so far I haven't come up with any way except functions that doesn't 
directly expose the data...and if I must use that approach, then the 
class doesn't buy me anything for the overhead.)


--
Charles Hixson

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


Re: indexed property? Can it be done?

2012-05-08 Thread Charles Hixson

On 05/08/2012 12:50 AM, Peter Otten wrote:

Charles Hixson wrote:

   

class Node:

  def__init__(self, nodeId, key, value, downRight, downLeft,
  parent):
  dirty=True
  dlu=utcnow()
  self.node=[nodeId, downLeft, [key], [value],
[downRight], parent, dirty, dlu]

Note that node[3] is a list of keys (initially 1) and node[3] is a list
of values, etc.

What I'd like to do is to be able to address them thusly:
k = node.key[2]
v = node.value[2]
but if there's a way to do this, I haven't been able to figure it out.
Any suggestions?
 

I don't see the problem:

   

class Node(object):
 

... def __init__(self, key):
... self.node = ["foo", "bar", [key], "baz"]
... @property
... def key(self):
... return self.node[2]
...
   

node = Node(42)
node.key
 

[42]
   

node.key[0]
 

42
   

node.key.append(7)
node.key
 

[42, 7]
   

del node.key[0]
node.key[:] = [3, 2, 1]
node.key
 

[3, 2, 1]
   

node.key = "foo"
 

Traceback (most recent call last):
   File "", line 1, in
AttributeError: can't set attribute

But the design proposed by Dan Sommers really is the way to go...

   
That depends on what you're doing.  For many, perhaps most, purposes I 
would agree.  Not for this one.  And I couldn't use an internal dict, as 
the order in which the items of the sub-lists occur is significant.  The 
sub-lists need to be lists, though they could be separated out as named 
variables (which would be lists).


The approach of returning the entire list would, indeed, work, but it 
exposes things that I would prefer to keep internal to the class (i.e., 
all the, e.g., keys that aren't currently being addressed).  I suppose 
it isn't too inefficient, as IIUC, all you're really passing back and 
forth are pointers, but it doesn't *feel* like the right answer.  So I 
can handle it by using getter and setter functions that recognize 
indicies, but it's less elegant than using indexing to access them.  So 
I thought I'd ask.


The ActiveState recipe *might* do what I want.  I honestly can't tell 
after a brief study.  But it's much too complex to be a worthwhile 
choice.  I was hoping that I'd just overlooked one of the standard 
features of Python.


To be truthful, the main benefit I see from using a class rather than a 
naked list structure is that I can readily test the type of the data.  A 
secondary benefit would be the nicer syntax, as with the list all 
manipulation would be done via specialized functions, and for some of 
the terms indexed access would be syntactically nicer.  But it looks 
like that isn't one of the possibilities.  Using a native list structure 
and manipulatory functions is nicer except in two ways:
1) There's no data hiding, so discipline must substitute for language 
structure.
2) There's excess names apparent at an upper level.  I wouldn't exactly 
call it namespace pollution, but it's certainly an increase in the 
higher-level namespace background noise level, even though it's all 
functional.


--
Charles Hixson

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


Re: indexed property? Can it be done?

2012-05-08 Thread Charles Hixson

On 05/08/2012 01:19 PM, Adam Tauno Williams wrote:

On Mon, 2012-05-07 at 20:15 -0700, Charles Hixson wrote:
   

class Node:
  def__init__(self, nodeId, key, value, downRight, downLeft, parent):
  dirty=True
  dlu=utcnow()
  self.node=[nodeId, downLeft, [key], [value],
[downRight], parent, dirty, dlu]
Note that node[3] is a list of keys (initially 1) and node[3] is a list
of values, etc.
What I'd like to do is to be able to address them thusly:
k = node.key[2]
v = node.value[2]
but if there's a way to do this, I haven't been able to figure it out.
Any suggestions?
 

Do not do this;  this is bad code in any language.
   


I'm sorry, but why do you say that?  In D or Eiffel it is a standard 
approach, with compiler support.  I will admit that one shouldn't do it 
in C++, or, it appears, in Python.  This is far from justifying saying 
one should never do it.


--
Charles Hixson

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


non-pickle persistance for dicts?

2012-05-16 Thread Charles Hixson
I want to persist simple dicts, but due to the security problems with 
(un)pickle, I'd prefer to not use shelve, and the only way I could see 
to persist them onto sqlite also invoked pickle.


As (un)pickle allows arbitrary system commands to be issued, I'd really 
rather just use a simple convert to and from either bytes or strings.  
repr works well for the conversion into string (I said they were 
simple), but I'd really rather be able to turn "{'a': 'A', 1: 23, 2: 
['b', 2]}" back into a dict without allowing the execution of arbitrary 
commands.


Any suggestions?

--
Charles Hixson

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


Re: non-pickle persistance for dicts?

2012-05-16 Thread Charles Hixson

On 05/16/2012 03:11 PM, Ian Kelly wrote:

On Wed, May 16, 2012 at 3:52 PM, Charles Hixson
  wrote:
   

I want to persist simple dicts, but due to the security problems with
(un)pickle, I'd prefer to not use shelve, and the only way I could see to
persist them onto sqlite also invoked pickle.

As (un)pickle allows arbitrary system commands to be issued, I'd really
rather just use a simple convert to and from either bytes or strings.  repr
works well for the conversion into string (I said they were simple), but I'd
really rather be able to turn "{'a': 'A', 1: 23, 2: ['b', 2]}" back into a
dict without allowing the execution of arbitrary commands.

Any suggestions?
 

Either json, or repr with ast.literal_eval will be safe.

   

import json
d = {'a': 'A', 1: 23, 2: ['b', 2]}
json.dumps(d)
 

'{"a": "A", "1": 23, "2": ["b", 2]}'
   

json.loads(json.dumps(d))
 

{'a': 'A', '1': 23, '2': ['b', 2]}
   

import ast
ast.literal_eval(repr(d))
 

{'a': 'A', 1: 23, 2: ['b', 2]}

Cheers,
Ian

   
Thanks.  It looks like either would do what I need.  Any suggestion as 
to how to choose between them?  E.g., is AST better supported?  faster?  
(I'm tending towards AST purely because it seems more tied to Python, 
but of course that *could* be a disadvantage, if there were more 
external tools for working with json.)


--
Charles Hixson

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


Questions on __slots__

2012-05-18 Thread Charles Hixson

Does __slots__ make access to variables more efficient?
If one uses property() to create a few read-only pseudo-variables, does 
that negate the efficiency advantages of using __slots__?

(Somehow I feel the documentation needs a bit of improvement.)

--
Charles Hixson

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


Re: Questions on __slots__

2012-05-19 Thread Charles Hixson

On 05/19/2012 06:39 AM, Adam Tauno Williams wrote:

On Fri, 2012-05-18 at 09:53 -0700, Charles Hixson wrote:
   

Does __slots__ make access to variables more efficient?
 

Absolutely, yes.

   

If one uses property() to create a few read-only pseudo-variables, does
that negate the efficiency advantages of using __slots__?
(Somehow I feel the documentation needs a bit of improvement.)
 

If you are tempted to use property, setattr, etc... then do not use
__slots__.  __slots__ should really only be used for Fly Weight pattern
type work, or at least for objects with a limited scope and will not be
inherited from.
   
Thank you.  What I really wanted was a "named list", sort of like a 
"named tuple", only modifiable, but since the only way to do it was to 
create a class, I started thinking of reasonable operations for it to 
perform (data hiding, etc.)  Sounds like I should go back to the "named 
list" idea.


--
Charles Hixson

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


Unexpected exception thrown in __del__

2012-05-21 Thread Charles Hixson

message excerpt:
flush: sql =  insert or replace into persists (id, name, data, rdCnt, 
rdTim, wrCnt, wrTim, deprecation) values (?, ?, ?, ?, ?, ?, ?, ?)
Exception TypeError: "'NoneType' object is not callable" in method Shelve2.__del__ of <__main__.Shelve2 object at 0x7ff4c0513f90>> 
ignored


flush is being called from within __del__.  I've narrowed it down to:
print ("flush: sql = ", sql)
curTim=nowI()
print ("flush: curTim = ", curTim)

nowI() is a function defined at the top of the file, and before the 
class, thus:

defnowI():
t=int (time() * 100)
returnt

All I can guess is that there's some reason that an external to the 
class function shouldn't be called during a __del__.  Is this correct?


--
Charles Hixson

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


Re: Unexpected exception thrown in __del__

2012-05-21 Thread Charles Hixson

On 05/21/2012 08:29 AM, Charles Hixson wrote:

message excerpt:
flush: sql =  insert or replace into persists (id, name, data, rdCnt, 
rdTim, wrCnt, wrTim, deprecation) values (?, ?, ?, ?, ?, ?, ?, ?)
Exception TypeError: "'NoneType' object is not callable" in method Shelve2.__del__ of <__main__.Shelve2 object at 0x7ff4c0513f90>> 
ignored


flush is being called from within __del__.  I've narrowed it down to:
print ("flush: sql = ", sql)
curTim=nowI()
print ("flush: curTim = ", curTim)

nowI() is a function defined at the top of the file, and before the 
class, thus:

defnowI():
t=int (time() * 100)
returnt

All I can guess is that there's some reason that an external to the 
class function shouldn't be called during a __del__.  Is this correct?


That seems to be the answer, as replacing the call to nowI() in flush() 
with:

curTim = int (time() * 100)
fixes the problem.

Rereading the documentation, I guess that this should have been 
expected, but if nowI() were a static method of the class, would that 
have avoided the problem?  A class method?



--
Charles Hixson

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


Re: Purely historic question: VT200 text graphic programming

2011-03-10 Thread Charles Turner

On Thu, 10 Mar 2011 00:38:11 -0600, GrayShark 
declaimed the following in gmane.comp.python.general:


Once, many, many, years ago, I programmed some type of 'graphical'
interface on a VT200 terminal


A wild guess: Prestel? Bildschirmtext? Telidon? Teletex? NAPLPS?

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


Re: Purely historic question: VT200 text graphic programming

2011-03-11 Thread Charles Turner

On 2011-03-10 14:55:02 -0500, Grant Edwards said:


Eh?  Those are viddotex/teletext systems aren't they?

I thought the OP was talking about a character-based windowing and
form-handling library used by applications that ran under VAX/VMS on
vt200 terminals.  The vt200 wasn't a TV.  It was a character-based,
mostly-ANSI-escape-sequence, computer terminal connected via async
serial (RS-232 typically) to a mini/mainframe computer (a DEC VAX
running VMS in this context).


NAPLPS isn't, but you're correct about the others. NAPLPS had character 
encoded graphics as well as vector drawing codes. It was based on an 
earlier ANSI x.500 protocol that was used in Teleltex, etc., but I've 
forgotten the exact name/designation.


In the US, most of the Teletex work was done on DEC hardware, AFAIK...

Best, Charles

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


RE: [IronPython] IronPython 2.7 Now Available

2011-03-13 Thread Medcoff, Charles
Can someone on the list clarify differences or overlap between the tools 
included in this release, and the PTVS release?
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: [IronPython] IronPython 2.7 Now Available

2011-03-13 Thread Medcoff, Charles
Thanks that helps. I've tried the first option. Not doing much Python stuff at 
the moment, but I'll follow up if I experience any issues with this approach.

I'm very excited that both the language and tools support is forging ahead - 
thanks all.

-Original Message-
From: users-boun...@lists.ironpython.com 
[mailto:users-boun...@lists.ironpython.com] On Behalf Of Dino Viehland
Sent: Sunday, March 13, 2011 2:22 PM
To: Discussion of IronPython; python-list
Subject: Re: [IronPython] IronPython 2.7 Now Available

The PTVS release is really an extended version of the tools in IronPython 2.7.  
It adds support for CPython including debugging, profiling, etc...  while still 
supporting IronPython as well.  We'll likely either replace the tools 
distributed w/ IronPython with this version (maybe minus things like HPC 
support) or we'll pull the IpyTools out of the distribution and encourage 
people to go for the separate download.  No changes will likely happen until 
IronPython 3.x though as 2.7 is now out the door and it'd be a pretty 
significant change.

For the time being you'll need to choose one or the other - you can always 
choose to not by either not installing the IpyTools w/ the IronPython install 
and install the PTVS or you can just stick w/ the existing IronPython tools.

> -Original Message-
> From: users-boun...@lists.ironpython.com [mailto:users- 
> boun...@lists.ironpython.com] On Behalf Of Medcoff, Charles
> Sent: Sunday, March 13, 2011 2:15 PM
> To: Discussion of IronPython; python-list
> Subject: Re: [IronPython] IronPython 2.7 Now Available
> 
> Can someone on the list clarify differences or overlap between the 
> tools included in this release, and the PTVS release?
> ___
> Users mailing list
> us...@lists.ironpython.com
> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com
___
Users mailing list
us...@lists.ironpython.com
http://lists.ironpython.com/listinfo.cgi/users-ironpython.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new sorting algorithm

2022-05-02 Thread charles hottel

On 5/1/2022 7:45 PM, Chris Angelico wrote:

On Mon, 2 May 2022 at 09:20, Dan Stromberg  wrote:



On Sun, May 1, 2022 at 1:44 PM Chris Angelico  wrote:


On Mon, 2 May 2022 at 06:43, Dan Stromberg  wrote:

On Sun, May 1, 2022 at 11:10 AM Chris Angelico  wrote:


On Mon, 2 May 2022 at 01:53, Nas Bayedil  wrote:

We believe that using this method to develop completely new, fast
algorithms, approaching the speed of the famous *QuickSort*, the speed of
which cannot be surpassed, but its drawback can be circumvented, in the
sense of stack overflow, on some data.


Hmm, actually TimSort *does* exceed the speed of quicksort for a lot
of real-world data. For instance, if you take a large sorted list,
append a handful of (unsorted) items to it, and then sort the list,
TimSort can take advantage of the fact that the bulk of the list is
sorted. It ends up significantly faster than re-sorting the entire
list.



In fact, Timsort is O(n) for already-sorted data, while many quicksorts are 
O(n^2) for already-sorted data.

Quicksort can be salvaged by using a median-of-3 partitioning, but it's still 
O(n^2) in the (less common) worst case.



This is true, but purely sorted data isn't a very practical case. The
case of mostly-sorted data IS practical, though, so it's a quite big
win that it can be close to O(n), and still faster than inserting each
item individually.



You seem to be of the impression that nearly-sorted data isn't an uphill battle 
with a straightforward quicksort.

I'm having a hard time convincing myself of that.



The median-of-three partitioning technique makes that work reasonably
well, so it won't be pathologically slow. It's hardly Quicksort's best
feature, but it could easily be a lot worse. I'd have to check, but I
think it still manages to be O(n log n). Merge sort, of course, is a
lot more consistent, but the asymptotic cost is still broadly the
same.

But Timsort manages to be close to O(n) for sorted data, reversed
data, nearly-sorted or nearly-reversed data, etc. Makes it very handy
for jobs like "click a heading to sort by it", where you might add
multiple sort keys.

(Plus, Python's implementation has some cool tricks for small
collections that make it quite efficient.)

ChrisA


Some versions of Quicksort switch over to Straight Insertion Sort when 
the partitions become small enough. The correct size will vary depending 
on the hardware.


I have not kept up with the latest improvements and I am not familiar 
with TimSort.  However Heapsort  should always be O(n log n) and there 
are modifications to Heapsort that can make it faster than vanilla 
Heapsort and closer to the speed of Quicksort.

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


Python-pickle error

2023-04-19 Thread charles wiewiora
Hello,
I am experincing problems with the pickle moducle
the folowing code was working before,

import pickle
number=2
my_pickeld_object=pickle.dumps(number)
print("this is my pickled object",{my_pickeld_object},)
with open('file.pkl', 'rb') as file:
number=pickle.load(file)
my_unpickeled_object=pickle.loads(my_pickeld_object)
print("this is my unpickeled object",{my_unpickeled_object},)

but now i get error

Traceback (most recent call last):
  File "C:\Users\lukwi\Desktop\python\tester2.py", line 5, in 
with open('file.pkl', 'rb') as file:
FileNotFoundError: [Errno 2] No such file or directory: 'file.pkl'

im get this problem after this,
a .pkl came into my Python script files
i though this could be a spare file made from python becauce i was doing this 
first,

import pickle
number=2
my_pickeld_object=pickle.dumps(number)
print("this is my pickled object",{my_pickeld_object},)
with open('file.pkl', 'rb') as file:
number=pickle.load(file)

so i stupidly deleted the file

do you know how to fix this?
i reinstalled it but it didn't work
this is on widnows and on version 3.11.3 on python

thank you
-- 
https://mail.python.org/mailman/listinfo/python-list


Importing modules with arguments

2021-07-30 Thread Charles Smith
I have found myself wanting to import module and provide arguments to them. 
There's two main reason I could think of for this. First is to prevent a 
circular import, though most of circular imports can be prevented by changing 
the design. The second reason is to invert dependencies between two modules. It 
occurred to me when using libraries like FastAPI or Flask that it would be 
nicer to use and leaner if instead of:
1. Import FastAPI Router or FastAPI object directly
2. Create a Router
3. Use the route decorators

We could simply import a module with importlib and provide the router itself. 
You can then keep all the FastAPI related code inside its module and only have 
clean list of endpoints. Now this is actually doable right now, here's the 
snippet: https://gist.github.com/BinarSkugga/c281cbbe36e7f11bc0fd143ea1bb4dd4

Disclaimer: I have no idea what are the implication of this but I'd like to 
have it as a feature instead of this hack.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Importing modules with arguments

2021-07-30 Thread Charles Smith
First off, thanks for the answer. I don't see the cached module as a problem 
here. If you provide arguments to a module, the goal is "most likely" to 
alter/parameterize the behavior of the first import. Now, I agree that behavior 
becomes unpredictable because passing different parameters on subsequent 
imports won't change the behavior of the imported module . One thing that could 
be done is to memoize those imports based on the parameters (this is a huge 
change to how imports works so its a bit yikes). Another solution would be to 
simply not cache parameterized imports. You sacrifice performance for added 
flexibility which I think is fair. I do however agree about partial imports. It 
would be rather complex to properly pass the context but its certainly doable.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: on writing a while loop for rolling two dice

2021-09-08 Thread charles hottel

On 9/7/2021 9:20 PM, Avi Gross wrote:

Greg,

Yes, a smart person may come up with such tricks but a really smart person,
in my view, adjusts. With some exceptions, such as when trying to port
existing code to a new language quickly, someone who is not too obsessive
will try to pick up the goals and spirit of a new language and use them when
it seems reasonable. And, a smart person, if they see nothing new, might
just go back to their old language or ...

Pick a language that easily supports regular expressions and object creation
and functional programming and so on, like python, and ask why you might
want to use it to simulate a really old version of BASIC when you can just
use BASIC.

Admittedly, most people are not flexible. I find that with human languages
too that some learn another language just enough to recognize words but not
to use the changed grammar or the different idioms and never become fluent.

I am amused though at the fact that python, by using indentation rather than
things like curly braces, would make some of the games like shown below
quite a bit more difficult.

-Original Message-
From: Python-list  On
Behalf Of Greg Ewing
Sent: Tuesday, September 7, 2021 9:08 PM
To: python-list@python.org
Subject: Re: on writing a while loop for rolling two dice

On 8/09/21 2:53 am, Grant Edwards wrote:

#define IF if (
#define THEN ) {
#define ELSE } else {
#define ENDIF }
...


I gather that early versions of some of the Unix utilities were written by
someone who liked using macros to make C resemble Algol.

I guess you can get away with that sort of thing if you're a Really Smart
Person.

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



So what do yoy think or feel about a language like RATFOR (Rational 
FORTRAN) which was implemented as macros?  Should they instead have 
simply adapted themselves to FORTRAN?

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


Re: Call for Assistance

2016-08-09 Thread Charles Ross
> CC-BY-NC-SA is not a license for free (as in speech) content. Is that
> what you want?

I really appreciate all the conversation about the license. Perhaps I made a 
mistake with requiring noncommercial in the license, I don’t know, but I’ll 
look at the links provided about free documentation and free software and see 
if I can understand the issues more and perhaps make a better decision.

Honestly, I have no expectation that this book will ever be anything more than 
a (hopefully) useful resource for others like myself, as described in the 
current introduction. I might have a remote hope that it would be something 
that would receive attention from a traditional publisher, but that remote hope 
is in the same category as a remote hope that a distant rich uncle will someday 
name me in his well. So, given the minuscule odds of that happening, I’ll 
probably remove the NC portion. I’ll just do a bit of research first with those 
links.

Thanks,
Chuck
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Call for Assistance

2016-08-09 Thread Charles Ross
Well, I’ve been convinced. The license for the book is now Creative Commons 
Attribution-ShareAlike.

https://github.com/chivalry/meta-python/blob/master/LICENSE.md

Thanks,
Chuck

> On Aug 9, 2016, at 3:00 PM, Charles Ross  wrote:
> 
>> CC-BY-NC-SA is not a license for free (as in speech) content. Is that
>> what you want?
> 
> I really appreciate all the conversation about the license. Perhaps I made a 
> mistake with requiring noncommercial in the license, I don’t know, but I’ll 
> look at the links provided about free documentation and free software and see 
> if I can understand the issues more and perhaps make a better decision.
> 
> Honestly, I have no expectation that this book will ever be anything more 
> than a (hopefully) useful resource for others like myself, as described in 
> the current introduction. I might have a remote hope that it would be 
> something that would receive attention from a traditional publisher, but that 
> remote hope is in the same category as a remote hope that a distant rich 
> uncle will someday name me in his well. So, given the minuscule odds of that 
> happening, I’ll probably remove the NC portion. I’ll just do a bit of 
> research first with those links.
> 
> Thanks,
> Chuck
> -- 
> https://mail.python.org/mailman/listinfo/python-list

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


Meta Python Chapter 3 Available

2016-08-12 Thread Charles Ross
I’ve completed a first draft of Chapter 3: Modules (and Packages) of the Meta 
Python book. Feedback from novices and experts alike would be welcome.

https://github.com/chivalry/meta-python 


Thanks,
Chuck
-- 
https://mail.python.org/mailman/listinfo/python-list


How to get Read the Docs to generate py-modindex.html?

2016-08-29 Thread Charles Ross
Since I appear to be experiencing one of the few times that Stack Overflow 
hasn’t provided any quick answers to a problem 
(http://stackoverflow.com/questions/39197037/how-to-get-read-the-docs-to-generate-py-modindex-html
 
),
 I’ll try posting my question here and see if anyone has a suggestion.

I'm trying to get Read the Docs to generate the `py-modindex.html` file. 
Research into a related question lead me to the following setup:

- `setup.py` in the project directory has the following contents, which were 
the minimum needed to get `pytest` to work and haven't been changed since I got 
that part of my project working:

import setuptools

setuptools.setup(
name='polygons',
packages=setuptools.find_packages(),
)

- `docs/requirements.txt` contains a single line:

sphinx-autodoc-annotation

- The Read the Docs repository URL points to my repository 
(https://github.com/chivalry/polygons).
- The RtD setting for "Install your project inside a virtualenv using setup.py 
install" is checked.
- The RtD setting for "Requirements file" points to `docs/requirements.txt`.

The "Module Index" link gets included in `index.html` 
(http://polygons.readthedocs.io/en/latest/), but the `py-modindex.html` file is 
missing.

My understanding is that with the virtualenv setting above, RtD will use the 
`setup.py` file to install the project so that Sphinx can read the 
documentation found in the Python docstrings. I'm using function annotations 
and would like `sphyinx-autodoc-annotation` to make use of those when creating 
the built docs files. All of this works splendidly on my local machine when I 
run `make html` while in the `docs` folder. Now I'm trying to get it to work on 
Read the Docs.

Thanks,
Chuck

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


Multiprocessing interactive processes with connections

2016-09-06 Thread Charles Hixson
I want to process a bunch of processes that all talk to each other.  
I've figured out how to do this using queues with the main process as 
the mail handler, but I'd rather have them talk directly.  If I use 
connections, then I can pass the pipes to the processes, but there 
doesn't seem to be anything analogous to queue, so it looks like I need 
to divide each process into two threads, one of which does nothing but 
mail handling.


Is this correct?


FWIW, a small, unoptimized, test of the working "mailhandler" approach is:

## Multiprocessing:  main thread as post office.
#  This is a bit clumsy, but it works.

from  multiprocessing import Process, Queue
from  queue import   Empty

def f(i, lim, q_rcv, q_snd):
   for j in range(lim):
  if i != j:
 q_snd.put([i, "message from process {0} to proess 
{1}".format(i, j), j])

  if not q_rcv.empty():
 val   =  q_rcv.get()
 print (val)
   q_snd.put([i, "done"])
   while (not q_recv.empty()):
  val   =  q_rcv.get()
  print (val, " :: ", i)
  if val == "done": return


if __name__ == '__main__':
   ps =  []
   qs =  []
   q_recv   =  Queue()
   for i in range(3):
  q  =  Queue()
  qs.append (q)
  ps.append (Process(target=f, args=(i, 3, q, q_recv)) )
   for p in ps:
  p.start()
   dones =  0
   try:
  v = q_recv.get(True, 1)
  while (v):
 print ("v = ", v)
 if v[1] == "done":
dones =  dones + 1
 else:
if len(v) == 3:
   assert v[2] < len(qs), "unexpected value"
   qs[v[2]].put(v[1])
else:
   print ("error:  ", v, " was an unexpected value.")
 v = q_recv.get(True, 1)
   except   Empty:
  print ("1: Timeout of maine receive queue")
   for q in qs:
  q.put("done")
   try:
  v = q_recv.get(True, 1)
  while (v):
 print ("2: v = ", v)
 if v[1] == "done":
dones =  dones + 1
 else:
if len(v) == 3:
   assert v[3] < len(qs), "2: unexpected value"
   qs[v[3]].put(v[2])
else:
   print ("2: error:  ", v, " was an unexpected value.")
 v = q_recv.get(True, 1)
   except   Empty:
  print ("2: Timeout of maine receive queue")
   for i in range(len(qs)):
  qs[i].close();
  qs[i] =  None

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


Multiprocessing queues receiving from wrong process

2016-12-23 Thread Charles Hixson
I was looking to avoid using a upd connection to transfer messages 
between processes, so I thought I'd use multiprocessing (which I expect 
would be faster), but...I sure would appreciate an explanation of this 
problem.


When I run the code (below) instead of messages receiving messages from 
the correct process I get:
(where the first number of a line identifies the index assigned to the 
process.)


waiting for completion
1=Process-2 received: at time 0.001243: Process-1 says Hi to 0
0=Process-1 received: at time 0.001211: Process-2 says Hi to 1
0=Process-1 received: at time 0.001144: Process-3 says Hi to 2
4=Process-5 received: at time 0.002324: Process-1 says Hi to 0
0=Process-1 received: at time 0.000953: Process-4 says Hi to 3
0=Process-1 received: at time 0.000674: Process-5 says Hi to 4
3=Process-4 received: at time 0.002114: Process-1 says Hi to 0
3=Process-4 received: at time 0.001864: Process-2 says Hi to 1
4=Process-5 received: at time 0.002094: Process-2 says Hi to 1
2=Process-3 received: at time 0.001711: Process-1 says Hi to 0
4=Process-5 received: at time 0.001885: Process-3 says Hi to 2
4=Process-5 received: at time 0.001586: Process-4 says Hi to 3
1=Process-2 received: at time 0.001456: Process-3 says Hi to 2
3=Process-4 received: at time 0.001734: Process-3 says Hi to 2
2=Process-3 received: at time 0.00158: Process-2 says Hi to 1
2=Process-3 received: at time 0.001444: Process-4 says Hi to 3
2=Process-3 received: at time 0.001088: Process-5 says Hi to 4
3=Process-4 received: at time 0.001221: Process-5 says Hi to 4
1=Process-2 received: at time 0.001212: Process-4 says Hi to 3
1=Process-2 received: at time 0.000885: Process-5 says Hi to 4

##Test multiprocessing queues
importmultiprocessingasmp
importtime

frommultiprocessingimportProcess
frommultiprocessingimportQueue
fromqueueimportEmpty
fromqueueimportFull
fromrandomimportrandom


class TestMPQ:
""" Class doc """

def __init__ (self, ndx):
""" Class initialiser """
self.name=mp.current_process().name
self.ndx=ndx

defsendHi (self):
for i in range(5):
if i != self.ndx:
qs[i].put ("{} says Hi to {}".format(self.name, self.ndx))

defprocessHi (self):
while (True):
time.sleep(random() + 0.001)
try:
msg=qs[self.ndx].get_nowait()
print ("{}={} received: {}".format(self.ndx, self.name, 
msg) )

exceptEmpty:
break
except Exception as ex:
print ("Exception: ", repr(ex))
break

defprocHandler (ndx, qs):
p=TestMPQ(ndx)
p.sendHi()
p.processHi()

if "__main__" == __name__:
qs=[]
for i in range(5):
qs.append(Queue())
ps=[]
for i in range(5):
ps.append(Process(target = procHandler, args = (i, qs) ) )
ps[i].start()
print ("waiting for completion")
for i in range(5):
ps[i].join()


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


Re: Multiprocessing queues receiving from wrong process

2016-12-23 Thread Charles Hixson



On 12/23/2016 01:56 PM, Charles Hixson wrote:
I was looking to avoid using a upd connection to transfer messages 
between processes, so I thought I'd use multiprocessing (which I 
expect would be faster), but...I sure would appreciate an explanation 
of this problem.


When I run the code (below) instead of messages receiving messages 
from the correct process I get:
(where the first number of a line identifies the index assigned to the 
process.)


waiting for completion

The receiving process should be the one sent to.

 receiving sending   sent to
  ndx process nameprocess 
name  ndx

1=Process-2 received: at time 0.001243: Process-1 says Hi to 0
0=Process-1 received: at time 0.001211: Process-2 says Hi to 1
0=Process-1 received: at time 0.001144: Process-3 says Hi to 2
4=Process-5 received: at time 0.002324: Process-1 says Hi to 0
0=Process-1 received: at time 0.000953: Process-4 says Hi to 3
0=Process-1 received: at time 0.000674: Process-5 says Hi to 4
3=Process-4 received: at time 0.002114: Process-1 says Hi to 0
3=Process-4 received: at time 0.001864: Process-2 says Hi to 1
4=Process-5 received: at time 0.002094: Process-2 says Hi to 1
2=Process-3 received: at time 0.001711: Process-1 says Hi to 0
4=Process-5 received: at time 0.001885: Process-3 says Hi to 2
4=Process-5 received: at time 0.001586: Process-4 says Hi to 3
1=Process-2 received: at time 0.001456: Process-3 says Hi to 2
3=Process-4 received: at time 0.001734: Process-3 says Hi to 2
2=Process-3 received: at time 0.00158: Process-2 says Hi to 1
2=Process-3 received: at time 0.001444: Process-4 says Hi to 3
2=Process-3 received: at time 0.001088: Process-5 says Hi to 4
3=Process-4 received: at time 0.001221: Process-5 says Hi to 4
1=Process-2 received: at time 0.001212: Process-4 says Hi to 3
1=Process-2 received: at time 0.000885: Process-5 says Hi to 4

##Test multiprocessing queues
importmultiprocessingasmp
importtime

frommultiprocessingimportProcess
frommultiprocessingimportQueue
fromqueueimportEmpty
fromqueueimportFull
fromrandomimportrandom


class TestMPQ:
""" Class doc """

def __init__ (self, ndx):
""" Class initialiser """
self.name=mp.current_process().name
self.ndx=ndx

defsendHi (self):
for i in range(5):
if i != self.ndx:
qs[i].put ("{} says Hi to {}".format(self.name, 
self.ndx))


defprocessHi (self):
while (True):
time.sleep(random() + 0.001)
try:
msg=qs[self.ndx].get_nowait()
print ("{}={} received: {}".format(self.ndx, 
self.name, msg) )

exceptEmpty:
break
except Exception as ex:
print ("Exception: ", repr(ex))
break

defprocHandler (ndx, qs):
p=TestMPQ(ndx)
p.sendHi()
p.processHi()

if "__main__" == __name__:
qs=[]
for i in range(5):
qs.append(Queue())
ps=[]
for i in range(5):
ps.append(Process(target = procHandler, args = (i, qs) ) )
ps[i].start()
print ("waiting for completion")
for i in range(5):
ps[i].join()




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


MySQL schema sync or diff

2017-01-04 Thread Charles Heizer
Hello,
I have a MySQL database that is not managed (yet) and I would like to get an 
output or diff against my new model file. I'm using flask-sqlalchemy. 

Are there any modules that would help me discover the differences so that I can 
script a migration to begin using flask-migrate?

Thanks!
-- 
https://mail.python.org/mailman/listinfo/python-list


MySQL schema sync or diff

2017-01-06 Thread Charles Heizer
Hello,
I have a MySQL database that is not managed (yet) and I would like to get an 
output or diff against my new model file. I'm using flask-sqlalchemy.

Are there any modules that would help me discover the differences so that I can 
script a migration to begin using flask-migrate?

Thanks!

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


Embedding python, run a function and get it's result

2017-01-31 Thread Charles Heizer
Hello,
I'm messing around with the embedded python and I can get parts to work. What 
I'm having a hard time is getting my head around calling a function in the 
python string and getting it's result.

Question, how do I load the python script and call runMe() and get it's value?

Thanks!

Example Works

Obj-C Code:

Py_Initialize();
PyObject *py_main, *py_dict;
py_main = PyImport_AddModule("__main__");
py_dict = PyModule_GetDict(py_main);

// Run the python source code
PyRun_String([auditScript UTF8String], Py_file_input, py_dict, py_dict);

PyObject *pythonString = PyDict_GetItemString(py_dict, "x") ;
if (!pythonString) {
NSLog(@"pythonString returned NULL");
return "NO";
}

// Convert the unpickled Python string to a C string
char *cString = PyString_AsString(pythonString);
Py_DECREF(pythonString);
f (!cString) {
NSLog(@"Failed converting pythonString string to C string");
return 1;
}
NSLog(@"answer: %@",[NSString cString]);

Python Code:

x = "NA"
def runMe():
return "YES"

x = runMe()
-- 
https://mail.python.org/mailman/listinfo/python-list


PyDictObject to NSDictionary

2017-02-02 Thread Charles Heizer
Hello,
I'm embedding python in to my Objective-C app and I need to know how do I 
convert a PyDictObject (PyObject) to a NSDictionary?

Thanks!
-- 
https://mail.python.org/mailman/listinfo/python-list


Fwd: Fwd: ftplib sending data out of order

2018-03-26 Thread Charles Wilt
Just to close out this thread in case anybody finds it...

We're reasonably sure the issue was cause by version 14.6 MP1 of Symantec
Vontu; which is a Data Loss Prevention (DLP) product that "inspects"
packets before they leave the PC.

I believe the issue was reported to Symantec.

In the meantime, we worked around the issue by extending the base ftplib.FTP
 class and adding a new function:

#stortext combines block read from STORBINARY with ASCII transfer mode
from STORLINEdef stortext(self, cmd, fp, blocksize=8192,
callback=None, rest=None):
self.voidcmd('TYPE A')
conn = self.transfercmd(cmd, rest)
while 1:
buf = fp.read(blocksize)
if not buf: break
conn.sendall(buf)
if callback: callback(buf)
conn.close()
return self.voidresp()

We stopped having issues with scrambled code. As a bonus, the transfer run
considerably faster than they did with storline.

So we've continued to use our new function.


On Mon, Jul 10, 2017 at 7:23 AM, Charles Wilt 
wrote:

> I downloaded the 3.6.1 source and added some debug logging to
> sock_sendall() and sock_send_impl() in socketmodule.c.
>
> As I understand it, sock_send_impl() is where the data is passed to the
> OS.
>
> I can see that sock_send_impl() is getting the data in the correct order.
>
>
>
>
> On Wed, Jul 5, 2017 at 2:03 PM, Dieter Maurer  wrote:
>
>> Charles Wilt wrote at 2017-7-5 11:08 -0600:
>> >On Mon, Jul 3, 2017 at 4:24 PM, Dieter Maurer 
>> wrote:
>> >
>> >>
>> >> It is not the "readline" that changes depending on the callback.
>> >> Keep in mind that "conn.sendall" can return before the bytes are
>> actually
>> >> sent.
>> >>
>> >
>> >?Not according to this answer
>> >https://stackoverflow.com/questions/34252273/what-is-the-di
>> fference-between-socket-send-and-socket-sendall
>>
>> "sendall" internally calls "send" until all the bytes passed as argument
>> are accepted by "send". Below "send", the things are packeted, transmitted
>> and reassembled.
>>
>> If send returns, this does *not* mean that the data has been successfully
>> transfered. It only means that a lower level has taken over responsibilty
>> for the transfer.
>>
>> As a consequence, "sendall" may return before the data has been
>> successfully transfered; it only means that the complete data was
>> accepted by the lower (network) level.
>>
>>
>> >And if sendall can return before the data is sentwouldn't that make
>> it
>> >the wrong choice for an FTP client?
>>
>> Why?
>>
>> The data is transfered to the lower level and this has taken
>> over responsibility for the transfer. "ftplib" is using a TCP socket.
>> TCP promises to ensure a reliable transfer (by using retransmissions, if
>> necessary and possible). Under normal conditions, the data will be
>> transfered;
>> thus, why wait until the transfer is complete.
>>
>>
>>
>> --
>> Dieter
>>
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why exception from os.path.exists()?

2018-06-10 Thread Charles Hixson

On 06/07/2018 12:45 AM, Chris Angelico wrote:

On Thu, Jun 7, 2018 at 1:55 PM, Steven D'Aprano
 wrote:

On Tue, 05 Jun 2018 23:27:16 +1000, Chris Angelico wrote:


And an ASCIIZ string cannot contain a byte value of zero. The parallel
is exact.

Why should we, as Python programmers, care one whit about ASCIIZ strings?
They're not relevant. You might as well say that file names cannot
contain the character "π" because ASCIIZ strings don't support it.

No they don't, and yet nevertheless file names can and do contain
characters outside of the ASCIIZ range.

Under Linux, a file name contains bytes, most commonly representing
UTF-8 sequences. So... an ASCIIZ string *can* contain that character,
or at least a representation of it. Yet it cannot contain "\0".

ChrisA
This seems like an argument for allowing byte strings to be used as file 
names, not for altering text strings.  If file names are allowed to 
contain values that are illegal for text strings, then they shouldn't be 
necessarily considered as text strings.


The unicode group sets one set of rules, and their rules should apply in 
their area.  The Linux group sets another set of rules, and their rules 
should apply in their area.  Just because there is a large area of 
overlap doesn't mean that the two areas are congruent.  Byte strings are 
designed to handle any byte pattern, but text strings are designed to 
handle a subset of those patterns. Most byte strings are readable as 
text, but not all of them.

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


Call for Assistance

2016-08-09 Thread Charles Ross
I’ve begun a new book called Meta Python that I’m looking for assistance with. 
The book is one I wish was out there, and so am writing. The book is targeted 
at experienced programmers who are novice Python users and want to move from 
that point to one where they have published to PyPI.

I’m specifically looking for three types of users to assist me:

- Expert Python developers who are willing to confirm and correct the technical 
details, since I’m getting to the material that I want to learn and therefore 
need to teach. So far that only really includes virtual environments, covered 
in chapter 2, but will soon include many other topics.
- Developers like me, who aren’t new to programming but are perhaps new to 
Python and certainly new to publishing to PyPI, and who can provide feedback on 
the clarity and usefulness of the content.
- Linux and Windows Python users who would be willing to assist in making the 
book a bit less Mac-centric.

The book is being hosted at https://github.com/chivalry/meta-python 
. The introduction and first two 
chapters have their initial drafts complete, but you’ll see a few “TODOs” in 
there. Any and all feedback is appreciated, and preferred through the GitHub 
Issues system, but feel free to email me if you prefer.

Thanks,
Chuck

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


Re: Call for Assistance

2016-08-09 Thread Charles Ross
You’re right. I should have mentioned that this is a volunteer effort on my 
part and anyone else who becomes involved. It’s being released under the 
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License 
(http://creativecommons.org/licenses/by-nc-sa/4.0/ 
<http://creativecommons.org/licenses/by-nc-sa/4.0/>) as demonstrated by the 
LICENSE.md file at the GitHub repository 
(https://github.com/chivalry/meta-python/blob/master/LICENSE.md 
<https://github.com/chivalry/meta-python/blob/master/LICENSE.md>).

I don’t yet know precisely how the “book” will be published. I might just leave 
it as a set of GitHub files or export the Markdown to other format to be hosted 
outside GitHub. I’m not worrying yet about publishing, only clarity and 
correctness of content.

Thanks,
Chuck

> On Aug 9, 2016, at 1:17 AM, Steven D'Aprano 
>  wrote:
> 
> On Tuesday 09 August 2016 11:52, Charles Ross wrote:
> 
>> I’ve begun a new book called Meta Python that I’m looking for assistance
>> with.
> 
> Are you looking for people to be co-authors? Are you offering payment, or 
> credit? A free copy of the book? A kick to the head? Or just looking for 
> volunteers to provide content for the book while you lie back on a beach in 
> the 
> Bahamas collecting the millions[1] in royalties?
> 
> 
> 
> 
> 
> [1] Zimbabwean dollars.
> 
> -- 
> Steve
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list

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


Installation Error

2020-05-21 Thread Charles Seagraves
Hi,
I have been learning and using Python to create a program to play Mah Jongg
and it was going well until my windows 10 computer started receiving an
update. My computer restarted and Python was gone. I have attempted to
reinstall with a message that the install was successful. When I started to
use it I got the following message.

pythonw.exe - System Error
The code execution cannot proceed because python38.dll was not found.
Reinstalling the program may fix this problem.

I have reinstalled python several times. Repaired it several times but
continue to get the same error.
I uninstalled the bad Windows update but still had the same problem trying
to get python running.

Please help,
Charlie Seagraves
-- 
https://mail.python.org/mailman/listinfo/python-list


Unable to set up Python correctly

2020-11-13 Thread Charles Okorobo
I have a problem going to one(1) week now. Our instructor told us that we
can check if our Python is well installed or well set up correctly by
typing Control-Shift- P on Windows OS while in VS Code Editor. We cut out
the path enclosed within the Quotation Marks, then we type "Select
Interpreter" and this will auto detect the installation path of our Python
installation. And when we click on that path, it will auto populate the
Path for us.

I did that, and it never happened. I mean that--when I followed all the
instructions, my path never auto populated.

So while the Path of our instructor is 3.8 and 32-bit, mine is 3.9 and
64-bit. But I am not able to auto populate the path to reflect my own path
and Python version. And when I try to print out Hello World, I get an error.

See screenshot of the path error-- https://prnt.sc/vidqif
[image: Mine vs default Path.png]

See screenshot of my Hello World error-- https://prnt.sc/vh6130
[image: Python VS Code error.png]

How can I fix this?

And is anyone willing to use Team Member software to help me remotely fix
this and still show me what you did to fix it?

I've not been able to move forward.
Needing help desperately.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python's Performance

2005-10-11 Thread Charles Krug
On Mon, 10 Oct 2005 11:21:18 -0700, Donn Cave <[EMAIL PROTECTED]>
wrote:
>> Iron-
>> Python).  is it still an interpreter if it generates machine code?
> 
> Is what an interpreter?
> 
> I am not very well acquainted with these technologies, but it sounds
> like variations on the implementation of an interpreter, with no
> really compelling distinction between them.  

An important point made by Tannenbaum is this:

Once you have a machine that executes instructions (what he called
hardware or "Level Zero Machine", then you can create higher level
machines that execute code written in the language of that machine.

For the purposes of writing C, for example, we pretend that we have this
magical machine that "runs C code," or more typically, "the machine that
runs (insert OS name) C code."

When the Level n machine isn't fast enough, we go to the level n-1
machine . . . C or Java for us, or assembly, but the model remains valid
until the point where you bump up against the underlying logic gates.

While we don't talk about the "Virtual Machine" the way Java folks do,
Tannenbaum's model is still useful for thinking about such things.

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


Re: When someone from Britain speaks, Americans hear a "British accent"...

2005-10-11 Thread Charles Krug
On Mon, 10 Oct 2005 15:46:34 -0500, Terry Hancock
<[EMAIL PROTECTED]> wrote:
> On Saturday 08 October 2005 04:35 am, Steve Holden wrote:
>> I must have been working at NASA at the time; they are well known for 
>> embiggening prices.
> 
> Not nearly as much as the DoD, from what I hear.
> 
> Truthfully, I think those stories are bit exaggerated -- I think the
> real problem is somebody making a bad make/buy decision. They decide
> to make something that they could easily have bought at the hardware
> store.
> 

Typically, it was a $30 hammer with $270 worth of paperwork attached.

The famous "$10k Toilet Seat" is actually a bit of an interesting tale.

The part in question is the toilet from a C5A transport . . not
something you can purchase at the local Home Depot.

Being an aircraft toilet, it's crammed into a tiny space and has to be
as light as possible and all the things you associate with aircraft
toilets.

When they were speccing the project, the airframe manufacturer included
some number of spare toilet seats in the bid, given the expected life of
the airframe.  Some faceless bureaucrat decided that they didn't NEED
any spare toilet seats and cancelled that line item.

Lo and Behold, they eventually needed spare toilet seats.  But because
of Another Good Regulation (tm) the tooling had been recycled.

Recreating the tooling to make the spares was, amortized over the number
ordered, around $10k/seat.  Compared to the tooling costs, subsequent
orders of the same seat are pretty much "free" . . . at least until some
bozo in Ring A decides to toss the tooling again.

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


[wxPython-users] Web based applications are possible with wxPython?

2005-10-18 Thread Ruben Charles
Hi,


I am reading some essays --http://www.paulgraham.com/avg.html "Beating
the averages"-- and i am very interested in the web-based
applications.

I want to take the advantages having the application on a server. Is
easy to update, maintain, etc...

My questions is

Can i have a wxPython GUI app available on a web browser?

I founded some doc on the www  but the most refers to GUI wrote in
java script and tool kits relates with java. Some java script samples
are interesting but is not what i am looking for.


There is a way for  having wxpython frames, dialogs etc on a web browser?

If not, can you suggest me any kind oh method for have something similar?


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


Re: Need Python Pro for Help!! Plzz

2005-10-31 Thread Ruben Charles
A stranger from the land of Woot came to Master Foo as he was eating
the morning meal with his students.

"I hear y00 are very l33t," he said. "Pl33z teach m3 all y00 know."

Master Foo's students looked at each other, confused by the stranger's
barbarous language. Master Foo just smiled and replied: "You wish to
learn the Way of Unix?"

"I want to b3 a wizard hax0r," the stranger replied, "and 0wn ever3one's b0xen."

"I do not teach that Way," replied Master Foo.



http://www.catb.org/~esr//writings/unix-koans/script-kiddie.html


On 10/30/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Need python Pro at [EMAIL PROTECTED] , if u wanna help, plz
> reply to that address. We are python beginners. need a real good
> Python Programmer for Help. TIA!!
> --
>  * Posted with NewsLeecher v3.0 Beta 7
>  * http://www.newsleecher.com/?usenet
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need Python Pro for Help!! Plzz

2005-11-01 Thread Ruben Charles
> On the other hand, a group for learning that has no experts in it may
> tend to produce "what works" style of programming as oppsoed to "what is
> a good idea or practise".

What is better?

Good practise doesn't work better?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: testing C code with python

2005-11-11 Thread Ruben Charles
On 11/10/05, Peter Hansen <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > A simple question - Is it common/good practice to test C code using
> > Python? For example one could wrap individual C functions, and test
> > each of them using python, maybe not for low-level things but at least
> > for algorithmic correctness. Anyone effectively doing this as common
> > practice?

Take a look at swig.org

There are some examples for testing C code y python and/or extend
python with C functions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tutorial example

2005-11-12 Thread Ruben Charles
That is the diference between a method and a function.
A method do something and a function return something.

Example:

def psum(n, m):
print (n + m)

def rsum(n, m):
return (n +m)

Then try this...


>>>  psum(2, 3)

>>> a = psum(2, 3)

>>> a

>>> a = rsum(2, 3)

>>> a

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


Re: tutorial example

2005-11-12 Thread Ruben Charles
On 11/12/05, Max Erickson <[EMAIL PROTECTED]> wrote:
>
> Not in python.
>
> For example, what would you call the following?
>
> def rsum(n, m):
> print n+m
> return n+m
>
>
> In python a method is callable attached to an object. A function is a
> callable object constructed with a def statement.

You are right, i was trying to explain the concept outside the objects.

PD: I would call your example: a function. Without the return
declaration, a routine or a method.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-20 Thread Charles Krug
On Mon, 20 Jun 2005 06:36:42 GMT, Ron Adam <[EMAIL PROTECTED]> wrote:
> Ron Adam wrote:
> 
>> You might be able to use a dictionary of tuples.
>> 
>> call_obj = {(type_obj1,0):obj1a,
>> (type_obj1,0):obj1b,
>> (type_boj2,1):obj2a,
>> (type_obj2,1):obj2b,
>> etc... }
>> call_obj[(type_of_obj,order)]()
>> 
>> 
>> Regards, Ron
> 
> This won't work like I was thinking it would.
> 
> But to get back to your is there a ? operator question...
> 
> Try this.
> 
> def foo():
> return "foo"
> 
> def boo():
> return "boo"
> 
> print (foo, boo)[1>0]()# prints "boo"
> print (foo, boo)[1<0]()# prints "foo"
> 
> Regards,
> Ron

Another thought:

Often complicated conditional logic is a flag that we need to refactor.
An accounting package I built has an official list of approved vendors,
but allows users to provisionally add a new vendor, which is corrected
later.

The bulk of this system only understands, "This document has-a vendor"
with a "vendor factory" that returns the appropriate type of vendor.

All of the logic specific to the specific subclass is internal to the
subclasses themselves.

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


Couple functions I need, assuming they exist?

2005-06-20 Thread Charles Krug
List:

First, I'm reading that aString.split() is depreciated.  What's the
current best practice for this?

Or am I mistaking that:

myWords = split(aString, aChar) 

is depreciated but

myWords = aString.split(aChgar)

is not?

Second question, I've written a script that generates a LaTeX source
containing randomly generated arithmetic problems of various types.

The target of the problems (my daughter) would prefer that the thousands
be delimited.  Is there a string function that does this?

Thanks


Charles

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


Re: Couple functions I need, assuming they exist?

2005-06-20 Thread Charles Krug
On 20 Jun 2005 15:51:07 GMT, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Peter Hansen wrote:
> 
>>> The target of the problems (my daughter) would prefer that the thousands
>>> be delimited.  Is there a string function that does this?
>> 
>> You refer to something like putting a comma between groups of three 
>> digits, as in 1,000?  This is locale-specific, and there's a "locale" 
>> module that should have what you need.
> 
>>>> import locale
>>>> locale.setlocale(locale.LC_ALL, '')
> 'English_United Kingdom.1252'
>>>> print locale.format("%d", 100, True)
> 1,000,000

Perfect!

Thanks.

Sometimes "hard part" is figuring out which package already does the
thing I need done.


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


Re: Python choice of database

2005-06-21 Thread Charles Krug
On Mon, 20 Jun 2005 23:42:21 -0800, EP <[EMAIL PROTECTED]> wrote:
> Oren suggested:
> 
>> How about using the filesystem as a database? For the number of records
>> you describe it may work surprisingly well. A bonus is that the
>> database is easy to manage manually.
> 
> I tried this for one application under the Windows OS and it worked fine...
> 
> until my records (text - maybe 50KB average) unexpectedly blossomed
> into the 10,000-1,000,000 ranges.  If I or someone else (who
> innocently doesn't know better) opens up one of the directories with
> ~150,000 files in it, the machine's personality gets a little ugly (it
> seems buggy but is just very busy; no crashing).  Under 10,000 files
> per directory seems to work just fine, though.
> 
> For less expansive (and more structured) data, cPickle is a favorite.
> 

Related question:

What if I need to create/modify MS-Access or SQL Server dbs?

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


Re: Loop until condition is true

2005-06-21 Thread Charles Krug
On Tue, 21 Jun 2005 12:05:25 +0200, Magnus Lycka <[EMAIL PROTECTED]> wrote:
> Remi Villatel wrote:
>> while True:
>> some(code)
>> if final_condition is True:
>> break
>> #
>> #
>> 
>> What I don't find so "nice" is to have to build an infinite loop only to 
>> break it.
> 
> This is a common Python idiom. I think you will get used to it.
> 
> 
>> Is there a better recipe?
> 
> final_condition = False
> while not final_condition:
>  some(code)

To the OP, don't get hung up on the syntax we use to implement a loop.

I took my first programming class long enough ago that we had to do
things like this (roughly translating the FORTRAN IV I remember into
p-code)

To do:

while TrueCondition
(loop body)

we'd have to write:

TopOfLoop:
if not TrueConditional goto loopEnd
   (loop body)
   goto TopOfLoop

loopEnd:

We were even required to write our source twice:

The first pass was "structured" and had to be proven correct.

The second pass was translated into something our compiler supported.

We still called it a "while loop" even though the syntax was icky.

When C came out with its built in looping, it was an unbelievable
luxury.

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


Re: Excellent Site for Developers

2005-06-25 Thread Charles Krug
On Sat, 25 Jun 2005 14:50:48 GMT, Brian <[EMAIL PROTECTED]> wrote:
> Do Re Mi chel La Si Do wrote:
>> rather... super troll
> 
> 100% Agreed.
> 
> Can anyone say, "This looks like spam... Feels like spam... and is about 
> as useful here in the Python forums as spam -- therfore my conclusion is 
> that his VB message probably IS SPAM."  :-D
> 
> Brian
> ---

H . . .tough call.

After all, Spam is nearly ALWAYS ON topic for a Python group.

*enjoys his spam bacon eggs spam spam and spam*

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


Having trouble importing against PP2E files

2005-07-08 Thread Charles Krug
List:

I'm trying to use the example files from Programming Python, 2nd Ed.

I've copied them into c:\Python24\Examples\PP2E.

Launching any of the examples programs by themselves seems to work
spiffily.

Using regedit, I appended "c:\Python24\Examples\PP2E" to Pythonpath

from the immediate window, executing the line:

from PP2E.launchmodes import PortableLauncher

Raises the exception:

Import Error: no module named PP2E.launchmodes

However if I copy launchmodes.py into my work directory, it imports
successfully.

Both "Examples" above and "Examples\PP2E" contain the __init__.py file.

Obviously, I'm missing a setup step here.

What magic do I need to perform to get Python to find modules in the
Examples heirarchy?

Is there any way to check from the immediate window where Python will
search for modules?  Pythonpath appears to be correct, but the file
isn't importing unless I copy it to the current directory.

Thanx


Charles

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


Re: Having trouble importing against PP2E files

2005-07-09 Thread Charles Krug
On Fri, 08 Jul 2005 22:43:55 +0300, Elmo Mäntynen <[EMAIL PROTECTED]>
wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
> 
>> Import Error: no module named PP2E.launchmodes
>> 
>> However if I copy launchmodes.py into my work directory, it imports
>> successfully.
>> 
>> Both "Examples" above and "Examples\PP2E" contain the __init__.py file.
> Are both Examples and PP2E packages? 

They appear to be, yes.

> In python if a folder is meant to represent a package it should iclude
> the above mentioned file __init__.py and by saying the above your
> suggesting that PP2E is a package inside the package Examples.

That appears to be the case, yes.

> If the above is correct, you should append the pythonpath with
> c:\Python24\ and refer to the wanted .py with Examples.PP2E.launchmodes.
> As such the import statement obviously should be "from
> Examples.PP2E.launchmodes import PortableLauncher". If the above isn't
> the case and there is still something unclear about this, reply with a
> more detailed post about the situation.
> 

The registry value is this:

C:\Python24\Lib;C:\Python24\DLLs;C:\Python24\Lib\lib-tk;
C:\Python24\Examples\PP2E

I'm not realy sure what other details are relavant.  I've installed from
the Windows .msi package, and appended the directory I want to
PythonPath in the registry, and that doesn't do what I need.

This is WinXP Pro

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


Re: Launching Python programs from Linux shell script

2005-09-09 Thread Ruben Charles
Yes...
-
Or... 
Add this line in de source:
#!/usr/bin/env python 
then
chmod +x myscript.py
./myscript.py


On 9 Sep 2005 08:31:27 -0700, Ernesto <[EMAIL PROTECTED]> wrote:
> Does anyone know how to start Python program(s) from a Linux shell
> script?  Is it just
> 
> $python myscript.py
> 
> ??
> 
> Thanks,
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a list of Mondays for a year

2005-09-19 Thread Charles Krug
On Mon, 19 Sep 2005 12:10:04 GMT, Chris <[EMAIL PROTECTED]> wrote:
> Thanks to everyone for your help!
> 
> That fit the need perfectly.
> 
> In article <[EMAIL PROTECTED]>, 
> [EMAIL PROTECTED] says...
>> Is there a way to make python create a list of Mondays for a given year?
>> 
>> For example,
>> 
>> mondays = ['1/3/2005','1/10/2005','1/17/2005','1/24/2005',
>> '1/31/2005','2/7/2005',   ... ]
>> 

You can also calculate it using the Julian Day Number.  Google on
astronomical calculations, or read the introduction to one of the
Numerical Recipies. . . books for a discussion and algorithm.

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


Re: How to program efficient pattern searches in a list of float numbers?

2005-09-19 Thread Charles Krug
On 19 Sep 2005 00:02:34 -0700, malv <[EMAIL PROTECTED]> wrote:
> Simple case:
> In this list, how to find all occurences of intervals of n adjacent
> indexes having at least one list-member with a value between given
> limits.
> Visualizing the list as a two-dimensional curve, this is like
> horizontally dragging a given rectangle over the curve and finding the
> x coordinates where the curve passes through the rectangle.(Define such
> a x-index coordinate as the left corner of the rectangle.)
> 
> More complicated case:
> Given a pair of rectangles spaced relatively to each other in a fixed
> manner. Drag this rectangle pair horizontally over the above
> two-dimensional curve and list the indexes of the occurences where the
> curve passes simultaneously through both rectangles.
> (Define such a x-index coordinate as the leftmost corner of the
> rectangle pair).
> 
> These problems can be solved by programming a naive search advancing
> index by index. It seems obvious that due to the localized properties
> searched for, much more efficient searches should be possible.
> After having found the occurence-indexes for one particular rectangle
> set, how to find the pattern occurences after changing one or more
> rectangle parameters?
> 

Make a picture of the problem.  From your description, I'm not certain
anything more complicated than a linear search is called for.

Is this the phrasing of the original problem presentation?  Seems to me
the word "superimpose" ought to occur here.

Another thought:  What is the end result you're after?  Often we start
thinking of a solution but lose sight of the end result.  Then another
solution will pop into our mind that makes it Oh So Simple.

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


[OT]Scipy plotting problems

2005-09-19 Thread Ruben Charles
Hi,

I'm using Scipy on Debian Gnu/Linux. (python2.3-scipy) in a program
that have to show plots but while i'm testing capabilities of the
three possible options (gplt, plt an xplt) a couple of questions comes
up.

--
plt:

If a follow the steps of the plotting tutorial everything seems ok in
the first try.

>>> import gui_thread
>>> gui_thread.start() # or gui_thread.wxPython_thread()
>>> from scipy import plt
>>> plt.plot((1,2,3))


But if i close the Plot frame (manually with the cursor) and try to plot again

>>> plt.plot((1,2,3))


The interpreter shows a message: "The C++ part of the code has been
deleted" and i can´t plot again without exit the interpreter and back
again.


How i can solve that?



gplt (gnuplot):

If i create a plot with the Gnuplot program the resulting plot has
responses to mouse events and shows coordinates in the window but if i
create a plot in python

gplt.plot((1,2,3))

The window have not the same response to mouse events (no response at all).

How i can give the same responses?
___




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


How can I tell if my host supports Python?

2005-02-14 Thread Charles Stricklin
I'd like to use Planet (http://planetplanet.org/) to aggregate my members
blogs into one big blog, and my host (http://www.bodhost.com) says they
support Python, but I see nothing anywhere on their web site including my
control panel that leads me to believe they do.

Is there any way to determine if they do?
-- 
Charles Stricklin


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


hotshot load error

2005-03-09 Thread Charles Hartman
I've used profile before, but wanted to get more information so I  
thought I'd try hotshot instead. It works fine when used like profile.  
But when I run it using this line,
	prof = hotshot.Profile('ScanHot.prof', lineevents=1)
though it runs all right, when I try to load the resulting file I get  
this:

>>> hs = hotshot.stats.load("ScanHot.prof")
Traceback (most recent call last):
  File "", line 1, in ?
  File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/hotshot/stats.py", line 12, in load
return StatsLoader(filename).load()
  File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/hotshot/stats.py", line 51, in load
assert not self._stack
AssertionError

--which I don't understand. (The program is a GUI one using wxPython  
2.5, running from within the WingIDE on a Mac under OS 10.3.8, if any  
of that makes a difference. Nothing there prevents hotshot from loading  
a file that's been made without the lineevents=1 argument.)

Charles Hartman
Professor of English, Poet in Residence
http://cherry.conncoll.edu/cohar
http://villex.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   >