Use of compile flags in regular expressions.

2012-07-19 Thread Steven W. Orr
I have a problem that I'm solving using a regex. (Yeah, I know, now I have two 
problems...) ;-)>


Anyways, the regex is about a couple of pages long and it works just peachy. 
There's just one thing I'd like to do to make it more elegant.


I need to compile the regex with MULTILINE and DOTALL. But there are a few 
sections where I wish it was *not* compiled with DOTALL. For those cases, I 
use (something like)


[^\n]*

instead of

.*

I see that I can use the (?MS) construct but I also see that it applies 
globally and not to the subgroup that I'm using it in.


* Is there a way to make it apply locally to a subgroup?
* If not, is there another way?
* Also, is this an incredible stroke of genius that I came up with this idea 
of applying flags to a subgroup, or have others thought of this too and found 
out that it's not really a good idea?


TIA

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Deciding inheritance at instantiation?

2012-08-03 Thread Steven W. Orr

On 8/3/2012 4:48 PM, Tobiah wrote:

I have a bunch of classes from another library (the html helpers
from web2py). There are certain methods that I'd like to add to
every one of them. So I'd like to put those methods in a class,
and pass the parent at the time of instantiation. Web2py has
a FORM class for instance. I'd like to go:

my_element = html_factory(FORM)

Then my_element would be an instance of my class, and also
a child of FORM.

I started messing with decorators, but it became difficult
for me to visualise how to do this.

Thanks!

Toby


Your class inherits from whatever is in the class statement.

class Foo(object):
pass

Here, Foo inherits from object, but you can replace object with any tuple of 
classes which can be redefined before instantiation.


class Base1(object):
pass

class Base2(object):
pass

Now we can define Foo2 to inherit from something that better be a tuple of 
classes at instantiation time.


class Foo2(bases):
pass

bases = (Base1,)

foo2 = Foo2() # foo2 is a Foo2 which inherits from Base1.

bases = (Base1, Bace2)

foob1b2 = Foo2() # foob1b2 is a Foo2 which inherits from Base1 and Base2.

Who was it who said: "Give a man a shovel and he'll dig himself one helluva 
hole"?

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: conditional running of code portion

2012-08-05 Thread Steven W. Orr

On 8/5/2012 12:43 AM, Ramchandra Apte wrote:

Try pypreprocessor  .
Better idea:
You should be using the logging 
module if you want to print debug information quickly.It uses threads and is
optimized to run fast.


I never saw pypreprocessor. Looks interesting. I have experience with Ned's cog 
preprocessor.


http://nedbatchelder.com/code/cog/

I used this in something that was operating at the packet socket level. I had no 
time to test if debug was true.




--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Computing win/loss records in Python

2012-08-25 Thread Steven W. Orr

On 8/25/2012 10:20 PM, Christopher McComas wrote:

Greetings,

I have code that I run via Django that grabs the results from various sports 
from formatted text files. The script iterates over every line in the formatted 
text files, finds the team in the Postgres database updates their w/l record 
depending on the outcome on that line, saves the team's row in the db, and then 
moves on to the next line in the file.

I'm trying to get away from Django for this project, I want to run the files, 
get the W/L results and output a formatted text file with the teams and their 
W/L records. What's confusing me I guess how to store the data/results as the 
wins and losses tally up. We're talking hundreds of teams, thousands of games, 
but a quick example would be:

Marshall
Ohio State
Kentucky
Indiana

Marshall,24,Ohio State,48,
Kentucky,14,Indiana,10,
Marshall,10,Indiana,7,
Ohio State,28,Kentucky,10

That's just a quick example, I can handle seperating the data in the lines, figuring it 
all out, I just am unsure of how to keep a running total of a team's record. I would do 
"for line in file:" then on the first line I see that Marshall lost so they 
would have 1, Ohio State won so they'd have 1 win. It'd go to the next line Kentucky 1 
win, Indiana 1 loss, then on the 3rd line, Marshall got a win so they'd have 1 win, but 
it would have to remember that loss from line 1...

Does this make sense?

Thanks,


win_count = defaultdict(int)
loss_count = defaultdict(int)

items = line.split(',')
if items[1] > items[3]:
windex = 0
lossdex = 2
else:
windex = 2
lossdex = 0
win_count[windex] += 1
loss_count[lossdex] += 1

Zat help?


--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: 3.2 can't extract tarfile produced by 2.7

2012-12-27 Thread Steven W. Orr

On 12/26/2012 11:11 AM, Benjamin Kaplan wrote:


On Dec 26, 2012 11:00 AM, "Antoon Pardon" mailto:antoon.par...@rece.vub.ac.be>> wrote:
 >
 > I am converting some programs to python 3. These programs manipulate
tarfiles. In order for the python3 programs to be really useful
 > they need to be able to process the tarfiles produced by python2 that
however seems to be a problem.
 >
 > This is testcode that produces a tarfile.
 >
 > #! /usr/bin/python
 >
 > compression = "bz2"
 > tarmode = "w|%s" % compression
 > rt = '.'
 >
 > import os
 > import os.path
 > import errno
 >
 > import tarfile as tar
 >
 > def process():
 > pj = os.path.join
 > entries = os.listdir(rt)
 > of = open("DUMP.tbz", "w")
 > tf = tar.open(mode = tarmode, fileobj = of,
 >   encoding = 'ascii', format = tar.PAX_FORMAT)
 > for entry in entries:
 > fqpn = pj(rt, entry)
 > try:
 > tf.add(fqpn, entry, recursive = False)
 > except OSError as ErrInfo:
 > print("%s: disappeared" % fqpn)
 > if ErrInfo.errno != errno.ENOENT:
 > raise
 > tf.close()
 > of.close()
 >
 > if __name__ == "__main__":
 > process()
 >
 >
==
 > This is testcode that checks a tarfile
 >
 > #!/usr/bin/python
 >
 > compression = "bz2"
 > tarmode = "r|%s" % compression
 >
 > import os
 > import os.path
 > import stat
 >
 > import tarfile as tar
 >
 > def equalfile(fl1, fl2):
 > bf1 = fl1.read(8192)
 > bf2 = fl2.read(8192)
 > while bf1 == bf2:
 > if bf1 == "":
 > return True
 > bf1 = fl1.read(8192)
 > bf2 = fl2.read(8192)
 > return False
 >
 > def process():
 > gf = open("DUMP.tbz", "r")
 > tf = tar.open(mode = tarmode, fileobj = gf,
 >   encoding = 'ascii', format = tar.PAX_FORMAT)
 > for tarinfo in tf:
 > entry = tarinfo.name 
 > fileinfo = os.stat(entry)
 > if stat.S_ISREG(fileinfo.st_mode) and tarinfo.isreg():
 > bfl = tf.extractfile(tarinfo)
 > ofl = open(entry)
 > if not equalfile(bfl, ofl):
 > print("%s: does not match backup" % entry)
 > sync = False
 > tf.close()
 > gf.close()
 >
 > if __name__ == "__main__":
 > process()
 >
 >
=
 >
 > When I use python2.7 to produce and later check the tarfile
everything works as expected. However when I use python3.2 to check the
tarfile I
 > get the following traceback.
 >
 > Traceback (most recent call last):
 >   File "tarchck", line 39, in 
 > process()
 >   File "tarchck", line 25, in process
 > encoding = 'ascii', format = tar.PAX_FORMAT)
 >   File "/usr/lib/python3.2/tarfile.py", line 1771, in open
 > t = cls(name, filemode, stream, **kwargs)
 >   File "/usr/lib/python3.2/tarfile.py", line 1667, in __init__
 > self.firstmember = self.next()
 >   File "/usr/lib/python3.2/tarfile.py", line 2418, in next
 > tarinfo = self.tarinfo.fromtarfile(self)
 >   File "/usr/lib/python3.2/tarfile.py", line 1281, in fromtarfile
 > buf = tarfile.fileobj.read(BLOCKSIZE)
 >   File "/usr/lib/python3.2/tarfile.py", line 573, in read
 > buf = self._read(size)
 >   File "/usr/lib/python3.2/tarfile.py", line 585, in _read
 > buf = self.__read(self.bufsize)
 >   File "/usr/lib/python3.2/tarfile.py", line 604, in __read
 > buf = self.fileobj.read(self.bufsize)
 >   File "/usr/lib/python3.2/codecs.py", line 300, in decode
 > (result, consumed) = self._buffer_decode(data, self.errors, final)
 > UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9e in position
10: invalid start byte
 >
 > I have been looking around but have no idea how I have to adapt this
code in order to have it process the tarfile under python3.2. The
original code didn't have the coding and format keywords on the tar.open
statement and after reading the documentation I thought that
 > would make things work, but no such luck. Further reading didn't
 > provide anything usefull
 >
 > --
 > Antoon Pardon
 > --

You're opening the file in text mode, so it's trying to decode it as
text using your default encoding (utf-8). You want the file read as a
series of bytes, so open it in binary mode.

gf =open("DUMP.tbz", "rb")





Really? I thought that the whole idea of using "rb" or "wb" was 
something that was necessitated by WinBlo$e. We're not doing IO on a 
text file here. It's a tar file which by definition is binary and it's 
not clear to me why unicode has anything to do with it. The files you 
extract should be unaffected and the archive you produce shouldn't care. 
Am I missing something?


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


Need help with shutils.copytree

2012-02-12 Thread Steven W. Orr
I have a 'master' directory and a collection of 'slave' dirs. I want the 
master to collect all of the stuff in the slave dirs.


The slaves all look like this,

.
|-- slaveX
|   `-- archI
|   |   `-- distJ
|   |   |   ` -- FILE

Where the different slaveX dirs may contain multiple occurrences of archI and 
distJ, but across all slaveX dirs, there will only be one *unique* instance of 
FILE in archI and distJ.


Here's an example: Given slave[1234], arch1 and arch2, and dist1 and dist2, I 
want master to end up looking like this:


.
|-- master
|   `-- arch1
|   |   ` -- dist1
|   |   |` -- FILE
|   `-- arch1
|   |   ` -- dist2
|   |   |` -- FILE
|   `-- arch2
|   |   ` -- dist1
|   |   |` -- FILE
|   `-- arch2
|   |   ` -- dist2
|   |   |` -- FILE

etc...


In bash, I might use cpio passthrough mode and say something like:

master=$path_to_master
for slave in ${slaves}
do
pushd $slave
find . -print | cpio -pdum $master
popd
done

but I'm having a hard time trying to get this functionality in python. (I'm 
trying to avoid writing a subprocess.)


I tried using shutil.copytree with a try / except that does a pass on OSError 
(which is what gets raised when trying to create a dir that already exists). 
No joy there. I also tried an ignore function that always returns ().


Someone must have done this before. Any suggestions / pointers are much 
appreciated.


(I hope this was clear to read.)

TIA

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a ConfigParser which keeps comments

2012-03-15 Thread Steven W. Orr

On 3/14/2012 6:07 AM, Gelonida N wrote:

Hi,


At the moment I use ConfigParser
http://docs.python.org/library/configparser.html
for one of my applications.


Now I'm looking for a library, which behaves like config parser, but
with one minor difference.

The write() mehtod should keep existing comments.

Does anybody know or implement something like this or is there as
switrch, that I overlooked in hte documentaiton.




I use ConfigObj.

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Questions about the use of descriptors.

2012-03-15 Thread Steven W. Orr

Question 1:

I have a class A with one attribute and I define __get__ and __set__ for that 
class. Then I create another class B that uses it.


Why does B require that the instance of A be a class variable in B and not 
created as an instance variable in __init__?


E.g.,
# This works fine.
class Truth(object):
def __init__(self):
self.is_slave = False

def __get__(self, obj, objtype):
return self.is_slave

def __set__(self, obj, val):
if not self.is_slave and val:
self.is_slave = val


class TruthHolder(object):
IsSlave = Truth()

def set_truth(self):
self.IsSlave = True

tt = TruthHolder()
print tt.IsSlave
tt.IsSlave = True
print tt.IsSlave
tt.IsSlave = False
print tt.IsSlave


But if I change TruthHolder to not start as a class variable

class TruthHolder(object):
def __init__(self):
self.IsSlave = Truth()

def set_truth(self):
self.IsSlave = True

it doesn't seem to use descriptor methods of Truth. It's just using the 
default setter and getter of TruthHolder.


Question2:

Is it the case that people only use descriptors for classes with single 
attributes? Or is it more frequent that descriptors are used with classes that 
have multiple attributes?


I feel like this is powerful juju, but I'm not getting when I should be using 
property and when I should be using descriptors.


General note: I see really simple examples in my searches, but I'd like to see 
a good practical example that has just a bit more meat on it.


--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Question about collections.defaultdict

2012-03-26 Thread Steven W. Orr
I created a new class called CaseInsensitiveDict (by stealing from code I 
found on the web, thank you very much). The new class inherits from dict. It 
makes it so that if the key has a 'lower' method, it will always access the 
key using lower


I'd like to change the place where I previously declared a dict

self.lookup = defaultdict(list)

so that the new code will allow this new dict to be used instead. But then I 
realized I may have painted myself into a small corner:


Is there a way to use defaultdict so that I can override what *kind* of dict 
it will use?


I would like the value to still be a list be default, but it seems like I 
can't tell defaultdict to use *my* new dict.


Do I give up on defaultdict?

BTW, 2.6 if it matters.

TIA :-)

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question about collections.defaultdict

2012-03-26 Thread Steven W. Orr

On 3/26/2012 9:44 AM, Robert Kern wrote:

On 3/26/12 2:33 PM, Steven W. Orr wrote:

I created a new class called CaseInsensitiveDict (by stealing from code I found
on the web, thank you very much). The new class inherits from dict. It makes it
so that if the key has a 'lower' method, it will always access the key using
lower

I'd like to change the place where I previously declared a dict

self.lookup = defaultdict(list)

so that the new code will allow this new dict to be used instead. But then I
realized I may have painted myself into a small corner:

Is there a way to use defaultdict so that I can override what *kind* of dict it
will use?


No.


I would like the value to still be a list be default, but it seems like I can't
tell defaultdict to use *my* new dict.

Do I give up on defaultdict?


Assuming that your CaseInsensitiveDict subclasses from dict or UserDict, it's
relatively easy to make a subclass of your CaseInsensitiveDict act like a
defaultdict. Just implement the __missing__(key) method appropriately (and
modify the constructor to take the callable, of course).

http://docs.python.org/library/stdtypes.html#dict
http://docs.python.org/library/collections.html#collections.defaultdict.__missing__




I'm not quite getting what you're telling me, but I'm sure you have the right 
idea. Here's the beginning of my class:


class CaseInsensitiveDict(dict):
def __init__(self, init=None):
if isinstance(init, (dict, list, tuple)):
for kk, vv in init.items():
self[self.key_has_lower(kk)] = vv


It sounds like you want me to subclass defaultdict to create something like 
this?

class CaseInsensitiveDictDef(defaultdict):
def __init__(self, init=None):
super(CaseInsensitiveDictDef, self).__init__(list)
self.__missing__ = list

I think I'm way off base. I'm not clear on what the calling sequence is for 
defaultdict or how to get it to  use my CaseInsensitiveDict instead of regular 
dict.


Can you help?

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question about collections.defaultdict

2012-03-28 Thread Steven W. Orr

On 3/26/2012 11:52 AM, Robert Kern wrote:

On 3/26/12 4:33 PM, Steven W. Orr wrote:

On 3/26/2012 9:44 AM, Robert Kern wrote:

On 3/26/12 2:33 PM, Steven W. Orr wrote:

I created a new class called CaseInsensitiveDict (by stealing from code I
found
on the web, thank you very much). The new class inherits from dict. It
makes it
so that if the key has a 'lower' method, it will always access the key using
lower

I'd like to change the place where I previously declared a dict

self.lookup = defaultdict(list)

so that the new code will allow this new dict to be used instead. But then I
realized I may have painted myself into a small corner:

Is there a way to use defaultdict so that I can override what *kind* of
dict it
will use?


No.


I would like the value to still be a list be default, but it seems like I
can't
tell defaultdict to use *my* new dict.

Do I give up on defaultdict?


Assuming that your CaseInsensitiveDict subclasses from dict or UserDict, it's
relatively easy to make a subclass of your CaseInsensitiveDict act like a
defaultdict. Just implement the __missing__(key) method appropriately (and
modify the constructor to take the callable, of course).

http://docs.python.org/library/stdtypes.html#dict
http://docs.python.org/library/collections.html#collections.defaultdict.__missing__






I'm not quite getting what you're telling me, but I'm sure you have the right
idea. Here's the beginning of my class:

class CaseInsensitiveDict(dict):
def __init__(self, init=None):
if isinstance(init, (dict, list, tuple)):
for kk, vv in init.items():
self[self.key_has_lower(kk)] = vv


It sounds like you want me to subclass defaultdict to create something like
this?

class CaseInsensitiveDictDef(defaultdict):
def __init__(self, init=None):
super(CaseInsensitiveDictDef, self).__init__(list)
self.__missing__ = list

I think I'm way off base. I'm not clear on what the calling sequence is for
defaultdict or how to get it to use my CaseInsensitiveDict instead of
regular dict.

Can you help?


You need to make a subclass of CaseInsensitiveDict, implement the
__missing__(key) method, and override the __init__() method to take the
factory function as an argument instead of data. defaultdict is just a
subclass of dict that does this.


class CaseInsensitiveDictDef(CaseInsensitiveDict):
def __init__(self, default_factory):
super(CaseInsensitiveDictDef, self).__init__()
self.default_factory = default_factory

def __missing__(self, key):
return self.default_factory()



Many thanks. This was a great learning experience as well as ending up with 
exactly what I wanted.


Python is rich with "Ah ha!" moments. This was definitely one of them.

In my feeble attempt to give back, here's the answer:

class CaseInsensitiveDefaultDict(CaseInsensitiveDict):
def __init__(self, default_factory=None, init=None):
if not callable(default_factory):
raise TypeError('First argument must be callable')
super(CaseInsensitiveDefaultDict, self).__init__(init)
self.default_factory = default_factory

def __missing__(self, key):
self[key] = val = self.default_factory()
return val

def __getitem__(self, key):
try:
return super(CaseInsensitiveDefaultDict, self).__getitem__(key)
except KeyError:
return self.__missing__(key)


--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: can I overload operators like "=>", "->" or something like that?

2012-04-20 Thread Steven W. Orr

On 4/19/2012 3:28 PM, dmitrey wrote:

hi all,
can I somehow overload operators like "=>", "->" or something like
that? (I'm searching for appropriate overload for logical implication
"if a then b")
Thank you in advance, D.


This tickled a memory from decades back when I worked in PL/I. They have a 
bool builtin function that performed bitwise boolean operations. The first two 
args were bit strings. The third arg is 4 bits whose value denoted the logical 
operation to be performed on the first two args on a bit by bit basis.


The meaning of the four bits are

1st bit of arg3 defines the result of bool if A = '0'B and B = '0'B
2nd bit of arg3 defines the result of bool if A = '0'B and B = '1'B
3rd bit of arg3 defines the result of bool if A = '1'B and B = '0'B
4th bit of arg3 defines the result of bool if A = '1'B and B = '1'B

bool ( A , B , '0001'B )   A AND  Blogical AND
bool ( A , B , '0111'B )   A OR   Blogical OR
bool ( A , B , '0110'B )   A XOR  Bexclusive-OR
bool ( A , B , '1110'B )   A NAND BNOT AND
bool ( A , B , '1000'B )   A NOR  BNOT OR
bool ( A , B , '1001'B )   A IFF  Bequivalence
bool ( A , B , '1101'B )   A  ->  Bimplication: if A then B
bool ( A , B , '1011'B )   A  <-  Bimplication: if B then A

If A and B are just one bit (like True or False) then the operation basically 
becomes logical instead of bitwise. The full explanation is over at


http://tinyurl.com/855dzjm

Also more detail is here

http://tinyurl.com/cdhwgdj

So, if you *really* wanted to, you could define a bunch of constants like 
BOP_AND, BOP_OR, BOP_XOR, BOP_NAND, BOP_NOR, BOP_IFF, BOP_IMP and BOP_NIMP.


Then define a class called Bool that redefines things like __rlshift__ and 
__rrshift__. That would get >>= and <<= for Implications and nodus tolens. 
It's not a total solution. I can't see how you're going to get IFF, NAND and NOR.


But, maybe writing a bool function might be enough. If you implement bool in 
python then you can say things like


def condition(A, B, bop):
return bool(A, B, bop)

A = something_boolish_thats_long_and_complex
B = something_boolish_thats_long_and_more_complex

bop = give_me_a_boolean_condition(*xx)

boolVal = do_on_condition() if bool(A, B, bop) else None

I think this might be useful to the right person where you have to calculate 
the logical operation at run-time. Passing in a constant operator is probably 
less useful.


Is this horrible?

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to suppress exception printing to console?

2012-05-31 Thread Steven W. Orr

On 5/31/2012 3:57 AM, Qi wrote:


I have an application that embedding Python into C++.
When any exception occurred in C++ code, PyErr_SetString will
be called to propagate the exception to Python.

The problem is, some unit tests trigger exception on intention.
So it's OK to have the exceptions. But Python will still print
the exception to console, polluting the unit test output.

My question is, is there any way to disable exception reporting
to console from either C++ or Python code?



How about a big hammer?

try:
main()
except Exception:
sys.exit(1)
else:
sys.exit(0)


--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Question about how to get line buffering from paramiko

2011-07-05 Thread Steven W. Orr
I'm writing a program that uses paramiko to run a lot of commands over ssh. 
Some of the commands take time to run and they write to stdout and stderr as a 
normal part of their operation so that we can see progress happening.


I can't seem to get the output from the remote commands (which is input to me) 
to be line buffered. If I run the commands using ssh, they line buffer nicely. 
If I run them through paramiko, they end up fully buffered.


I stole this code I found as a base. The code that I got looked like the 
execute_capture method (below). I added the execute method so that I could 
poll for the result from both stderr and stdout. Note that I am calling 
channel.get_pty, but that doesn't change the fact that the results are not 
line buffered.


Can anyone suggest a way to solve this?

The code I'm using follows:

#! /usr/bin/python

"""
Friendly Python SSH2 interface using paramiko
"""

import os
import sys
import tempfile
import paramiko
import select
from collections import namedtuple

ExecStatus = namedtuple('ExecStatus', 'status stdout stderr')

class Connection(object):
"""
Connects and logs into the specified hostname.
Arguments that are not given are guessed from the environment.
"""
def __init__(self,
 host,
 username = None,
 private_key = None,
 password = None,
 port = 22,
 blocking_cmds = True,
 verbose = False,
 ):
self._sftp_live = False
self._sftp = None
if not username:
username = os.environ['LOGNAME']

# Log to a temporary file if requested.
if verbose:
self.templog = tempfile.mkstemp('.txt', 'ssh-')[1]
paramiko.util.log_to_file(self.templog)
else:
self.templog = False

# Begin the SSH transport.
self._transport = paramiko.Transport((host, port))
self._tranport_live = True
# Authenticate the transport.
if password:
# Using Password.
self._transport.connect(username = username, password = password)
else:
# Use Private Key.
if not private_key:
# Try to use default key.
if os.path.exists(os.path.expanduser('~/.ssh/id_rsa')):
private_key = '~/.ssh/id_rsa'
elif os.path.exists(os.path.expanduser('~/.ssh/id_dsa')):
private_key = '~/.ssh/id_dsa'
else:
raise TypeError, "You have not specified a password or key."

private_key_file = os.path.expanduser(private_key)
rsa_key = paramiko.RSAKey.from_private_key_file(private_key_file)
self._transport.connect(username = username, pkey = rsa_key)

def _sftp_connect(self):
"""Establish the SFTP connection."""
if not self._sftp_live:
self._sftp = paramiko.SFTPClient.from_transport(self._transport)
self._sftp_live = True

def get(self, remotepath, localpath = None):
"""Copies a file between the remote host and the local host."""
if not localpath:
localpath = os.path.split(remotepath)[1]
self._sftp_connect()
self._sftp.get(remotepath, localpath)

def put(self, localpath, remotepath = None):
"""Copies a file between the local host and the remote host."""
if not remotepath:
remotepath = os.path.split(localpath)[1]
self._sftp_connect()
self._sftp.put(localpath, remotepath)

def execute(self, command):
"""
Execute the given commands on a remote machine.
Return value is exit status of the remote command.
"""
# This execute method is similar to execute_capture below. The
# difference is that this method gets the stdout and stderr of
# the runnning command and forwards it on to the correct
# channel within this process.
# To do this, we use the poll(2) system call which comes from
# the select package.

def _write(fd, chan, syschan):
"""
_write internal method to check an fd from the list of fds
for a POLLIN event, read the data that's there, and if there's
anything there, then write it to the correct channel.
Return True if there was something to read.
"""
ret = False
if fd[1] & select.POLLIN:
if fd[0] == chan.channel.fileno():
ss = chan.readline()
ret = len(ss) != 0
if ret:
# No need to strip and then print with a newline.
# because every line is newline terminated.
print >> syschan, ss[:-1]
return ret
# Open a channel of type session. Same as open_channel('session')
ch

Trying to learn about metaclasses

2011-07-25 Thread Steven W. Orr
I have been doing a lot of reading. I'm starting to get it. I think it's 
really cool as well as dangerous, but I plan on being respectful of the 
construct. I found a web page that I found quite readable.


http://cleverdevil.org/computing/78/

So, I tried to run the example code (below), and I get AttributeError. If 
someone can get me over this hump, I'd be grateful. It complains that Person 
has no _fields attribute, but the print hello I have in EnforcerMeta doesn't 
happen either. Am I doing something wrong?


I'm running python 2.6.2

Here's the error:

585 > ./meta1.py
Traceback (most recent call last):
  File "./meta1.py", line 38, in 
swo.name = 'swo'
  File "./meta1.py", line 27, in __setattr__
if key in self._fields:
AttributeError: 'Person' object has no attribute '_fields'


And here's the code:

#! /usr/bin/python
# http://cleverdevil.org/computing/78/
class Field(object):
def __init__(self, ftype):
self.ftype = ftype

def is_valid(self, value):
return isinstance(value, self.ftype)

class EnforcerMeta(type):
def __init(cls, name, bases, ns):
# Store the field definitions on the class as a dictionary
# mapping the field name to the Field instance.
print 'Hello'
cls._fields = {}

# loop through the namespace looking for Field instances.
for key, value in ns.items():
if isinstance(value, Field):
cls._fields[key] = value

class Enforcer(object):
# attach the metaclass
__metaclass__ = EnforcerMeta

def __setattr__(self, key, value):
if key in self._fields:
if not self._fields[key].is_valid(value):
raise TypeError('Invalid type for field.')
super(Enforcer, self).__setattr__(key, value)

class Person(Enforcer):
name = Field(str)
age = Field(int)

if __name__ == '__main__':
swo = Person()
swo.name = 'swo'
print 'swo:', swo


--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Need an example program that implements rpm -pql via import rpm

2011-03-03 Thread Steven W. Orr
I look everywhere but I couldn't find anything. Could someone please point me to 
a small example program that does an import rpm, takes an rpm file as an 
argument and gets the list of files contained in the file, the same as if I had 
used the commandline


rpm -pql foo-1.23-4.i586.rpm

Much appreciated.

TIA

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need an example program that implements rpm -pql via import rpm

2011-03-04 Thread Steven W. Orr

On 3/3/2011 11:11 PM, geremy condra wrote:

On Thu, Mar 3, 2011 at 7:24 PM, Steven W. Orr  wrote:

I look everywhere but I couldn't find anything. Could someone please point
me to a small example program that does an import rpm, takes an rpm file as
an argument and gets the list of files contained in the file, the same as if
I had used the commandline

rpm -pql foo-1.23-4.i586.rpm

Much appreciated.


Thank you, but this is not what I was looking for. What I want is the same 
thing but uses the rpm module. After I get this piece of it working I'll be 
able to do the rest of what I want, but the important thing is that it happens 
in the context of import rpm.


Anyone?



#! /usr/bin/env python

import sys
import commands

if __name__ == "__main__":
 rpm = sys.argv[1]
 print commands.getoutput("rpm -pql %s" % rpm)


Input validation and help text left as an exercise for the reader.

Geremy Condra



--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need an example program that implements rpm -pql via import rpm

2011-03-04 Thread Steven W. Orr

On 3/4/2011 10:24 AM, Daniel Mahoney wrote:

On Thu, 03 Mar 2011 22:24:24 -0500, Steven W. Orr wrote:


I look everywhere but I couldn't find anything. Could someone please
point me to a small example program that does an import rpm, takes an
rpm file as an argument and gets the list of files contained in the
file, the same as if I had used the commandline

rpm -pql foo-1.23-4.i586.rpm

Much appreciated.

TIA


This is just a quick and dirty script, but how about:

import os
import rpm
import sys


I am at peace with the universe.

Thanks :-)



ts = rpm.TransactionSet()
fd = os.open(sys.argv[1], os.O_RDONLY)
h = ts.hdrFromFdno(fd)
os.close(fd)

flist = h.fiFromHeader()
for file in flist:
 print file[0]



Dan



--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: English Idiom in Unix: Directory Recursively

2011-05-17 Thread Steven W. Orr

On 5/17/2011 6:26 PM, Xah Lee wrote:

might be of interest.

〈English Idiom in Unix: Directory Recursively〉
http://xahlee.org/comp/idiom_directory_recursively.html


The answer is from compute science 101. From any standard data structures 
course, you learn the algorithm for how to walk a tree. To make it simple, the 
example is to use a binary tree which means that any non-leaf node of a tree may 
only have two child nodes, which are designated as Left and Right. There are 
only three things that are possible: Visit, Go Left, or Go Right. This means 
that a tree traversal program can only be written three ways:

A PreOrder Traversal will Visit, Go Left, Go Right.
An InOrder Traversal will Go Left, Visit, Go Right.
A PostOrder Traversal will Go Left, Go Right, Visit.

So, the Visit function is the function that does whatever you want to have 
happen at that node. Selection of whether you want to do things like copy, print 
or delete are designated by what kind of traversal you perform. And, since the 
Traversal function calls itself, it is, by definition, recursive.


QED.

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Advise on using logging.getLogger needed.

2011-10-02 Thread Steven W. Orr
I hope I don't sound like I'm ranting :-(

I have created a module (called xlogging) which sets up logging the way I want
it. I found out that if I set up my logger without a name, then it gets
applied to every logger that is referenced by every module that ever gets
imported.

The problem is that I must call xlogging.getLogger or logging.getLogger in all
other modules using the name of the root logger, and I don't know what that
name is.

I want the name of the root logger to be the name of the running program, so
in my setup, I say

pname = sys.argv[0]
try:
rslash = pname.rindex('/')
except ValueError:
pass
else:
pname = pname[rslash + 1:]

try:
dot_py = pname.rindex('.py')
except ValueError:
pass
else:
pname = pname[0:dot_py]

and then I say

logger = logging.getLogger(pname)

My problem is that I just want the modules that I write, to be able to get the
 named root logger and still be able to refer to possible sub-loggers.

So, let's say I run program foo. At some point in my mail setup, I set the
configuration for the foo logger. I'd like my xlogging module to supply a
getLogger function such that if I don't supply any arguments, it will return
the logger that would normally be returned by logging.getLogger(pname).

Also, part of the reason I'm confused is because foo calls m1 and m2 and they
want to say

logger = xlogging.getLogger(MaybeWithAnArg?)

at the top of their code. This means that the import statement for m1 and m2
are getting the calls to getLogger executed before I get the chance to set
things up.

I am running 2.6, so I don't have access to logging.getChild, but I'm not
clear that I even want that.

My modules are used by multiple programs. Does this mean that I should simply
use __name__ all the time? (That seems inelegant, no?)

If I'm making sense, is there a way to do this?


-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about using "with"

2007-01-09 Thread Steven W. Orr
>From the tutorial, they said that the following construct will 
automatically close a previously open file descriptor:

---
#! /usr/bin/python
import sys

for nn in range ( 1, len(sys.argv ) ):
 print "arg ", nn, "value = ", sys.argv[nn]
 with open(sys.argv[nn]) as f:
 for line in f:
 print line,
--

but when I run it (with args) I get:

591 > ./cat.py cat.py
   File "./cat.py", line 6
 with open(sys.argv[nn]) as f:
 ^
SyntaxError: invalid syntax
592 >

This example came from http://docs.python.org/tut/node10.html down in 
section 8.7

Am I missing something?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Looking to embed python into html like mason

2007-06-21 Thread Steven W. Orr
Does something like that exist?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Indenting in Emacs

2007-06-21 Thread Steven W. Orr
On Thursday, Jun 21st 2007 at 10:11 +0100, quoth Michael Hoffman:

=>[EMAIL PROTECTED] wrote:
=>> Hello,
=>> Does anyone know how to make python-mode correctly indent nested lists
=>> and dictionaries. I hate indenting Django url patterns and Zope
=>> Archetypes schemas by hand, because python-mode indents them in
=>> incorrect and ugly way.
=>> 
=>> Here's how it should be:
=>> StringField('reference',
=>> widget=StringWidget(
=>>description='Position reference'
=>> )),
=>> 
=>> Here's how python-mode indents this code:
=>> schema = BaseSchema.copy() +  Schema((
=>> StringField('reference',
=>> widget=StringWidget(
=>> description='Position reference'
=>> )),
=>
=>I get:
=>
=>schema = BaseSchema.copy() +  Schema((
=> StringField('reference',
=> widget=StringWidget(
=> description='Position reference'
=> )),
=>
=>I'm using py-version "$Revision$." Oops! Anyway, try to install the 
=>latest python-mode, whatever that is, if it isn't 4.78.

Ok. I'm not stupid but I do not see a 4.78 anywhere even though I see refs
from google. I have 4.75 The SVN tree doesn't seem to even have that. 

I checked the latest copy out from sourceforge and that was 4.75 too.

Can someone please tell me where to find the latest?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about how to use cog as a preprocessor :-(

2007-07-18 Thread Steven W. Orr
I have the following module:

#! /usr/bin/python
COG_DEBUG=1
def wrapper( dd ):
 if dd == 1:
 def dfunc( *args ):
 print "print ",
 for ii in args:
 print repr(ii)
 print "compd dfunc"
 return dfunc
 else:
 def nfunc( *args ):
 pass
 print "compd nfunc"
 return nfunc
dbgprint = wrapper(COG_DEBUG)
print "dbgprint = ", repr(dbgprint)
dbgprint("called from def hunk")
print "hello1"

This does what I want, but when I use this code inside cog then the call 
to dbgprint doesn't do anything.

Here's the input to cog:

#! /usr/bin/python
[[[cog
import cog
def wrapper( dd ):
 if dd == 1:
 def dfunc( *args ):
 cog.out( "print " )
 for ii in args:
 cog.out( repr(ii) )
 print
 print "compd dfunc"
 return dfunc
 else:
 def nfunc( *args ):
 pass
 print "compd nfunc"
 return nfunc
dbgprint = wrapper(COG_DEBUG)
print "dbgprint = ", repr(dbgprint)
dbgprint("called from def hunk")
]]]
[[[end]]]

print "hello1"
[[[cog dbgprint( "Hello from dbg" )]]]
[[[end]]]
print "Doo dis"

and this is the cmdline: cog.py -D COG_DEBUG=1 -d -o d1out.py d1.py

And the output is just

#! /usr/bin/python
import sys


print "hello1"
print "Doo dis"

DOes anyone have any ideas? :-(

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


I need a string/list/generator/comprehension incantation.

2007-04-20 Thread Steven W. Orr
I really tried. I give up.

I got this one last time (for which I'm very grateful).

import calendar
months = dict([(month,ii) for ii,month in enumerate(calendar.month_abbr)][1:])

Now I want something that's going to give me a string whose value is the 
set of all of the first letters of months. Order is not important.

And for extra credit, I need the string whose value is the set of all of 
the letters of months minus the first letter.

E.g., 'ADFJMONS', 'acbeglonprutvy'

  Thanks in advance to all the wizards out there. :-)

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Can __init__ not return an object?

2007-04-21 Thread Steven W. Orr
When I go to create an object I want to be able to decide whether the 
object is valid or not in __init__, and if not, I want the constructor to 
return something other than an object, (like maybe None). I seem to be 
having problems. At the end of __init__ I say (something like)

if self.something < minvalue:
del self
return None

and it doesn't work. I first tried just the return None, then I got crafty 
and tried the del self. Is what I'm trying to do possible in the 
constructor or do I have to check after I return? Or would raising an 
exception in the constructor be appropriate?

Am I even being clear?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shebang or Hashbang for modules or not?

2007-04-23 Thread Steven W. Orr
On Saturday, Apr 21st 2007 at 19:18 +0100, quoth Michael Hoffman:

=>Chris Lasher wrote:
=>> Should a Python module not intended to be executed have shebang/
=>> hashbang (e.g., "#!/usr/bin/env python") or not? I'm used to having a
=>> shebang in every .py file but I recently heard someone argue that
=>> shebangs were only appropriate for Python code intended to be
=>> executable (i.e., run from the command line).
=>
=>Personally I include it in all of them, as part of boilerplate in a 
=>template.

I'd recommend againt it. The shebang doesn't do you any good unless it's 
also in the presence  of a file that has its executable bit set. 

For example, let's leave python out for a second: I have a shell script. 
And I also have lots of files which are not intended to be executed which 
are also shell scripts, but which are sucked in by the shell "." or 
"source" command (which is *somewhat* analogous to python's import). Lots 
of these shell "library" scripts can't execute as standalone. The same 
thing is possible with pything scripts.

Of course, anything that has 
if __name__ == "__main__":
in it should always have a shebang and be executable.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shebang or Hashbang for modules or not?

2007-04-23 Thread Steven W. Orr
On Monday, Apr 23rd 2007 at 17:31 +0100, quoth Michael Hoffman:

=>Steven W. Orr wrote:
=>> On Saturday, Apr 21st 2007 at 19:18 +0100, quoth Michael Hoffman:
=>> 
=>> =>Chris Lasher wrote:
=>> =>> Should a Python module not intended to be executed have shebang/
=>> =>> hashbang (e.g., "#!/usr/bin/env python") or not? I'm used to having a
=>> =>> shebang in every .py file but I recently heard someone argue that
=>> =>> shebangs were only appropriate for Python code intended to be
=>> =>> executable (i.e., run from the command line).
=>> =>
=>> =>Personally I include it in all of them, as part of boilerplate in a 
=>> =>template.
=>> 
=>> I'd recommend againt it. The shebang doesn't do you any good unless it's 
=>> also in the presence  of a file that has its executable bit set. 
=>
=>It doesn't do any bad either, so I don't understand why you would 
=>recommend against it.
=>
=>And the bash function I use to create new files from the template also 
=>does chmod a+x.
=>
=>Not to mention that I have emacs set such that things with shebangs at 
=>the top are automatically chmod a+x, so in my programming environment, 
=>having a shebang on files I create and being executable are one and the 
=>same.
=>
=>> For example, let's leave python out for a second: I have a shell script. 
=>> And I also have lots of files which are not intended to be executed which 
=>> are also shell scripts, but which are sucked in by the shell "." or 
=>> "source" command (which is *somewhat* analogous to python's import). Lots 
=>> of these shell "library" scripts can't execute as standalone. The same 
=>> thing is possible with pything scripts.
=>> 
=>> Of course, anything that has 
=>> if __name__ == "__main__":
=>> in it should always have a shebang and be executable.
=>
=>That's in my template as well. :)
=>
=>I try to write all my modules so that they can easily be adapted to run 
=>as scripts, and all my scripts so that they can easily be adapted to use 
=>as modules. This has served me well many, many times. I see no reasons 
=>to create an artificial barrier to doing this by leaving the shebang out 
=>of files where it has no ill effect.

We're going too far here. Anything that ever gets executed should 
obviously always be executable and have a shebang. I'm trying to point out 
to people who create scripts in any language, shell, python, farsi, 
whatever, that if it's intended to be read in as some sort of library then 
don't make it executable and don't add a shebang. To do so is to confuse 
future generations.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


how to create/ref globals in an alternate namespace?

2007-04-27 Thread Steven W. Orr
I have two seperate modules doing factory stuff which each have the 
similar function2:

In the ds101 module, 
def DS101CLASS(mname,data):
 cname = mname+'DS101'
 msg_class = globals()[cname]
 msg = msg_class(data)
 return msg

and in the fdu module,

def FDUCLASS(mname,data):
 cname = mname+'FDU'
 msg_class = globals()[cname]
 msg = msg_class(data)
 return msg

I was thinking I'd be clever and create a common function:
def procCLASS(mname, objname, data):
 cname = mname+objname
 msg_class = globals()[cname]
 msg = msg_class(data)
 return msg

but the call to globals fouls it all up. Is there a way to write it so 
that the call to globals can be parameterized to be in the context of a 
specific module?

Also, I need to go the other way, a la,
 globals()[name] = nclass

Is this doable?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to create/ref globals in an alternate namespace?

2007-04-27 Thread Steven W. Orr
On Friday, Apr 27th 2007 at 14:07 -0700, quoth James Stroud:

=>Steven W. Orr wrote:
=>> I have two seperate modules doing factory stuff which each have the 
=>> similar function2:
=>> 
=>> In the ds101 module, def DS101CLASS(mname,data):
=>> cname = mname+'DS101'
=>> msg_class = globals()[cname]
=>> msg = msg_class(data)
=>> return msg
=>> 
=>> and in the fdu module,
=>> 
=>> def FDUCLASS(mname,data):
=>> cname = mname+'FDU'
=>> msg_class = globals()[cname]
=>> msg = msg_class(data)
=>> return msg
=>> 
=>> I was thinking I'd be clever and create a common function:
=>> def procCLASS(mname, objname, data):
=>> cname = mname+objname
=>> msg_class = globals()[cname]
=>> msg = msg_class(data)
=>> return msg
=>> 
=>> but the call to globals fouls it all up. Is there a way to write it so 
=>> that the call to globals can be parameterized to be in the context of a 
=>> specific module?
=>> 
=>> Also, I need to go the other way, a la,
=>> globals()[name] = nclass
=>> 
=>> Is this doable?
=>> 
=>> TIA
=>> 
=>
=>Why do you need all of the msg_class(es) global? Why not put them into a 
=>module and import the module where you need them? This would be the 
=>conventional way to avoid such problems.

The idea is that DS101 is being called in a loop in the ds101 module to 
create a lot of msg_classes. The same is true for the FDUCLASS function; 
it creates a lot of classes in a loop.

In addition, I have two other functions, almost alike, in two seperate 
modules (mdefs is a structure with all of the stuff needed to drive the 
loops)

def __InitDS101Classes():
for m in mdefs:
mdef = mdefs[m]
name = mdefs[m]['name']+'DS101'
nclass = new.classobj(name,(DS101,),{})
nclass.mdef = mdef
nclass.mid = m
globals()[name] = nclass


def __InitFDUClasses():
for m in mdefs:
mdef = mdefs[m]
name = mdefs[m]['name']+'FDU'
nclass = new.classobj(name,(FDU,),{})
nclass.mdef = mdef
nclass.mid = m
globals()[name] = nclass

I'm trying to see if by being clever, I can factor out the common code of 
the four different functions and still end up with what they create ending 
up in the namespaces where they are intended to reside in. Does this make 
sense or am I way off base?


-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


What do people use for code analysis.

2007-05-02 Thread Steven W. Orr
Lots of code, calls to, calls by, inheritance, multiple tasks, etc.

What do people use to figure out what's happening?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What do people use for code analysis.

2007-05-02 Thread Steven W. Orr
On Wednesday, May 2nd 2007 at 12:48 +0200, quoth Daniel Nogradi:

=>> Lots of code, calls to, calls by, inheritance, multiple tasks, etc.
=>>
=>> What do people use to figure out what's happening?
=>
=>This is a pretty cool project just for that:
=>
=>http://codeinvestigator.googlepages.com/codeinvestigator

I looked at codeinvestigator  but it looks like it doesn't do what I want.

I saw something about source navigator having python support. Have people 
used it? Does that work well?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Further adventures in array slicing.

2007-05-04 Thread Steven W. Orr
This is more for my education and not so much for practicality.

I have a structure that sort of looks like this:

mdict = {33:{'name': 'Hello0',
 'fields':'fields0',
 'valid': 'valid0'
  55:{'name': 'Hello1',
 'fields':'fields1',
 'valid': 'valid1'},
  14:{'name': 'Hello2',
 'fields':'fields2',
 'valid': 'valid2'}}

i.e, each element of the dictionary is itself a dictionary with three 
common keys.

I need to unpack this into three seperate arrays called name, fields, 
valid. The old code looked like this:

names = []; fields = []; valid = []
for ii in mdict:
 names.append(mdict[ii]['name'])
 fields.append(mdict[ii]['fields'])
 valid.append(mdict[ii]['valid'])

I tried this (to see if it would work) and it seems to work just fine:

def u2(m):
 aa = [ms[ii][jj] for jj in 'name','fields','valid' for ii in m]
 return tuple(zip(aa[0::3], aa[1::3], aa[2::3]))
names,fields,valid = u2(mdict)

I was very pleased with myself, except that the real world example of 
'fields' and 'valid' is that they can be (but not always) a sequence. 
e.g.,

mdefs = {0:{'name': 'Hello0',
 'fields':(('Address', 8),
 ('Control', 8)),
 'valid': {'Address': (1,255),
'Control': (33,44)}},
  1:{'name': 'Hello1',
 'fields':'fields1',
 'valid': 'valid1'},
  2:{'name': 'Hello2',
 'fields':'fields2',
 'valid': 'valid2'}}

Is there a way to do this with possibly a more concise technique than the 
first for loop above?

A second question is: When can you use += vs .append(). Are the two always 
the same?

Thanks. :-)

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Decorator question

2007-05-23 Thread Steven W. Orr
I just discovered decorators. Very cool. My question is that I can't 
figure out how to make a decorator not be restricted to a function so it 
would also work on a method.

Here's my code:

def g(expr):
 def rpt(func):
 def wrapper(t):
 for ii in range(expr):
 print ii,
 func(t)
 wrapper.__name__ = func.__name__
 wrapper.__dict__ = func.__dict__
 wrapper.__doc__ = func.__doc__
 return func
 return wrapper
 return rpt

@g(20)
def f(s):
 print 's="%s"'%s
f('Hello')

It works fine, but now I want to apply the same decorator to a class 
method.

class KK:
 # @g(20) This obviously doesn't work.
 def f(self, s):
 print 's= %s'%s

k = KK()
k.f('Hello')

Is there a trick I need?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Another question about variable args.

2007-08-07 Thread Steven W. Orr
I have a structure I need to pack. I call struct.pack about a dozen times 
and each call takes about 53 arguments.

I create a sequence of the arguments:
a1 = 1
a2 = 2
a3 = 3
etc...
a54 = 88
myseq = (a1, a2, a3, a4 etc... a53)
Also I made

def mpack ( fmt, *ss ):
 print type(ss)
 for ii in ss:
 print 'ii = ', ii, 'type(ii) = ', type(ii)
 for ii in list(ss):
 print 'ii = ', ii, 'type(ii) = ', type(ii)
 return struct.pack(fmt, *ss )

In my main, this first print statement works.
print 'main:', mpack(ff, a, b, c, d, e, f, g, h, i)

1. For the life of me, I can't figure out what to do to get the next print 
to work. The idea is that I want to make my code clearer by not passing 
50+ args each time and to instead pass a sequence which when evaluated 
will be the desired list of args.

print 'main:', mpack(ff, subseq)

2. And then, if possible, I'd like to do it in such a way that one myseq 
is defined, its value can automagically be re-eval'd so I don't have to 
re-assign to myseq each time one of the 50+ variables changes prior to 
calling pack.

Does this make sense?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about FutureWarning

2007-08-14 Thread Steven W. Orr
I have module M1 which has the following line in it:

   StartTime   = safe_dict_get ( dic, 'starttime', 0x )

It gets imported by modules M2 and M3. And finally, M4 imports both M2 and 
M3.

M4
  |\M3
  | |\M1
  |\M2
  | |\M1

I'm building a .deb file which means I have to compile the modules into 
.pyc and .pyo files.

The compile command I use is

python=/usr/bin/python2.3
i_python ()
{
 $python -c "import $1"
 $python -O -c "import $1"
}
i_python M1
i_python M2
i_python M3
i_python M4

When M1 is compiled, there's no problem. The same for when I compile M2 
and M3. But when M4 is compiled, I get the following message:

M1.py:268: FutureWarning: hex/oct constants > sys.maxint will 
return positive values in Python 2.4 and up
   StartTime   = safe_dict_get ( dic, 'starttime', 0x )

I get the message twice, ostensibly because of M3 and M2.

I was able to shut off the warning by adding the following lines *before* 
the import in M4.

import warnings
warnings.filterwarnings('ignore', category=FutureWarning)

My question is this: Why can the warning not be shut off by putting the 
two lines in M1?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Retry: Question about FutureWarning

2007-08-14 Thread Steven W. Orr
I'm trying again, since no response indicates that I'm not providing 
enough info.

I have module M1 which has the following line in it:

StartTime   = safe_dict_get ( dic, 'starttime', 0x )

It gets imported by modules M2 and M3. And finally, M4 imports both M2 and
M3. So the idea is that in total we have 4 files called M1.py M2.py M3.py 
and M4.py

M4
   |\M3
   | |\M1
   |\M2
   | |\M1

I need to compile the python modules as part of the package building 
process.

The shell compile command I use to generate both the .pyc and the .pyo 
files is:

python=/usr/bin/python2.3
i_python ()
{
  $python -c "import $1"
  $python -O -c "import $1"
}
i_python M1
i_python M2
i_python M3
i_python M4

When M1 is compiled, there's no problem. The same for when I compile M2
and M3. But when M4 is compiled, I get the following message:

M1.py:268: FutureWarning: hex/oct constants > sys.maxint will
return positive values in Python 2.4 and up
StartTime   = safe_dict_get ( dic, 'starttime', 0x )

I get the message twice, ostensibly because of M3 and M2 both being 
imported into M1

I was able to shut off the warning by adding the following lines *before*
the import of M2 and M3 in M4:

import warnings
warnings.filterwarnings('ignore', category=FutureWarning)

My question is this: Why can the warning not be shut off by putting the
two lines in M1 where the reference exists to 0x ?

I'm just leary of fixing warnings by looking for ways to shut them off.

Also, do I need to supply any more information?

Thanks for your patience.

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Retry: Question about FutureWarning

2007-08-15 Thread Steven W. Orr
Thanks guys, but that's not my question. The question is this: Why does 
the call to filterwarnings not work if it's placed inside the M1 module? 
Why do I have to place the call in M4 to make it work? This is more a 
question about how import works than it is about what the value of -1 is. 
;-)

On Tuesday, Aug 14th 2007 at 18:49 -0700, quoth Erik Max Francis:

=>Steven W. Orr wrote:
=>
=>> M1.py:268: FutureWarning: hex/oct constants > sys.maxint will
=>> return positive values in Python 2.4 and up
=>>StartTime   = safe_dict_get ( dic, 'starttime', 0x )
=>  ...
=>> import warnings
=>> warnings.filterwarnings('ignore', category=FutureWarning)
=>> 
=>> My question is this: Why can the warning not be shut off by putting the
=>> two lines in M1 where the reference exists to 0x ?
=>
=>You really don't want to shut off the warning; it means just what it says:
=>
=>Python 2.3.5 (#1, Feb  8 2005, 23:36:23)
=>[GCC 3.2.3] on linux2
=>Type "help", "copyright", "credits" or "license" for more information.
=> >>> 0x
=>:1: FutureWarning: hex/oct constants > sys.maxint will return 
=>positive values in Python 2.4 and up
=>-1
=>
=>Python 2.4.3 (#1, Mar 29 2006, 17:16:11)
=>[GCC 3.2.3] on linux2
=>Type "help", "copyright", "credits" or "license" for more information.
=> >>> 0x
=>4294967295L
=>

On Wednesday, Aug 15th 2007 at 06:10 -0700, quoth Paul McGuire:

=>On Aug 14, 8:49 pm, Erik Max Francis <[EMAIL PROTECTED]> wrote:
=>
=>So if by '0x' you meant -1, then change this line to use -1.
=>Otherwise, if you really meant 4294967295L, leave it at 0x and
=>move on.
=>
=>-- Paul
=>
=>-- 
=>http://mail.python.org/mailman/listinfo/python-list
=>

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Need to generate some functions.

2007-08-17 Thread Steven W. Orr
Given a list of names

ll = ("n1", "n2", "n3", "n4")

I want to create a pair of functions based off of each name. An example of 
what I want to happen would look like this:

def mkn1dict(address):
 return {'Address': address, 'Control': SOME_CONST}

def mkn1Classobj(address):
 return Classobj( mkn1classobj(address) )

I know how to do this in a preprocessor, but I'd like to do it directly in 
python. Can this be done?

TIA


-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Problems with dynamic function creation.

2007-08-22 Thread Steven W. Orr
I have some functions I need to create at runtime. The way I'm creating 
them is by calling a function which returns the string representation. 
Then I exec the string.

Here's the code I use to gen the strings:
mkfactfns.py
---
import new
def mkfactfns( cname ):
 def auxgen( name, params, dd ):
 v1 = ( """def mk%s%sdict(%s):\n"""%(name, cname, params)
+
"""print 'In mk%s%sdict'\n"""%(name, cname)
+
"""return %s\n"""%dd)
 v2 = ( """def mk%s%s(%s):\n"""%(name,cname,params)
+
"""print 'Calling mk%s%s'\n"""%(name,cname)
+
"""return %s%s( mk%s%sdict(%s) )\n"""%(name,cname, 
name, cname, params))
 return v1, v2
 return auxgen

This is  the caller of mkfactfns

import mkfactfns
fbase = "ABC"   # Factory BASEname
auxfactgen = mkfactfns.mkfactfns(fbase)

Then in the same module, I call auxfactgen
via
 mkfactfns.AuxFnDefs( auxfndata, auxfactgen, globals(), "ABC" )

def AuxFnDefs(auxfndata, fnmaker, globs, cname ):
 dictsuff = ('dict','')
 for ii in auxfndata:
 rr = fnmaker( *ii )
 for jj in range( 2 ):
 co = compile (rr[jj], '', 'exec')
 exec co
 name = 'mk%s%s%s'%(ii[0],cname,dictsuff[jj])
 print 'co = ', co, 'name = ', name
 nfunc = new.function( co, globs, name )
 print 'Just added mk%s%s%s'%(ii[0],cname,dictsuff[jj])
 globs['mk%s%s%s'%(ii[0],cname,dictsuff[jj])] = nfunc
 print 'g = ', globs['mk%s%s%s'%(ii[0],cname,dictsuff[jj])]

Everything works just fine (that I know of) except that when I run a 
function that takes 1 arg, I get the following message:

TypeError: ?() takes no arguments (1 given)

even though I know that I am passing one arg. I must be doing something 
wrong, I just don't know what. :-(

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Redo: How to create a function dynamically.

2007-08-22 Thread Steven W. Orr
I have this which works:

#! /usr/bin/python
strfunc = """
def foo( a ):
 print 'a = ', a
"""
exec strfunc
globals()['foo'] = foo
foo( 'Hello' )

and this which does not:

#! /usr/bin/python
import new
strfunc = """
def foo( a ):
 print 'a = ', a
"""
co = compile ( strfunc, '', 'exec' )
exec co
nfunc = new.function( co, globals(), 'foo' )
globals()['foo'] = nfunc
foo( 'Hello' )

When I try to run this one I get:
Traceback (most recent call last):
   File "./m2.py", line 13, in ?
 foo( 'Hello' )
TypeError: ?() takes no arguments (1 given)


I need the second case to work because I want to be able to end up with a 
function in a seperate module to do the work of function creation. The 
caller will pass in globals() so that the resulting function will end up 
in the directory?/dictionary? of that caller.

[And my apologies for overcomplicating the question on my first try.]

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem with dynamic creation of classes.

2007-08-23 Thread Steven W. Orr
I have a base class B and a derived class D which inherits from B. I also 
have a D2 class which inherits from D. D is used as a base class for most 
of my generated classes. I have a "special" class which inherits from D2 
because I need to override a couple of its methods. Anything based on D2 
will inherit Encode and Decode from B.

class D(b.B):
 def __init__(self, data, timestamp = None):
 b.B.__init__(self, data)
 self.timestamp = timestamp

class D2( D ):
 def __init__(self, data, timestamp = None):
 DS.__init__(self, data, timestamp)
 def Decode(self):
 pass
 def Encode(self):
pass

The generated classes come from this loop:

 for m in mdefs:
 mdef = mdefs[m]
 name = mdef['name'] + fbase
 if mdef.has_key('baseclass'):
 base_class_seq = mdef['baseclass']
 else:
 base_class_seq = DEFAULT_BASE_CLASS
 nclass = new.classobj( name, base_class_seq, globals() )

base_class_seq is either going to be (D,) or (D2,)

After I get through the class generation, I want to say
 globals()['IFRAMED2'].Decode = dynDecode
 globals()['IFRAMED2'].Encode = dynEncode
for the one class that inherited from D2. If I do that, I find that *all* 
classes that call Encode or Decode are all calling dyn{En,De}code (which 
is exactly what I *don't* want).

So I looked at the id values after class generation.

 print 'IFRAMED2.Encode = ', IFRAMED2.Encode, id(IFRAMED2.Encode)
 print 'SNRMD.Encode = ', SNRMD.Encode, id(SNRMD.Encode)
 print 'IFRAMED2 = ', IFRAMED2, id(IFRAMED2)
 print 'SNRMD = ', SNRMD, id(SNRMD)
 IFRAMED2.Decode = dynDecode
 IFRAMED2.Encode = dynEncode
 print 'IFRAMED2.Encode = ', IFRAMED2.Encode, id(IFRAMED2.Encode)
 print 'SNRMD.Encode = ', SNRMD.Encode, id(SNRMD.Encode)

Here's the output:

IFRAMED2.Encode =   1100623660
SNRMD.Encode =   1100623660
IFRAMED2 =  d.IFRAMED2 1076299644
SNRMD =  d.SNRMD 1103202364
IFRAMED2.Encode =   1100623660
SNRMD.Encode =   1100623660

So it looks like the IFRAMED2 class which inherits from D2 is starting out 
with the same id value for Encode as SNRMD which inherits from D, even 
though D2 defines its own Encode method.

Is it me of is it the interpreter doing something wrong?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Redo: Problem with dynamic creation of classes.

2007-08-23 Thread Steven W. Orr
Sorry, I had a small description problem. It's corrected below.

I have a base class B and a derived class D which inherits from B. I also
have a D2 class which inherits from D. D is used as a base class for most
of my generated classes. I have a "special" class which inherits from D2
because I need to override a couple of its methods. Anything based on D 
will inherit Encode and Decode from B.

class D(b.B):
  def __init__(self, data, timestamp = None):
  b.B.__init__(self, data)
  self.timestamp = timestamp

class D2( D ):
  def __init__(self, data, timestamp = None):
  DS.__init__(self, data, timestamp)
  def Decode(self):
  pass
  def Encode(self):
pass

The generated classes come from this loop:

  for m in mdefs:
  mdef = mdefs[m]
  name = mdef['name'] + fbase
  if mdef.has_key('baseclass'):
  base_class_seq = mdef['baseclass']
  else:
  base_class_seq = DEFAULT_BASE_CLASS
  nclass = new.classobj( name, base_class_seq, globals() )

base_class_seq is either going to be (D,) or (D2,)

After I get through the class generation, I want to say
  globals()['IFRAMED2'].Decode = dynDecode
  globals()['IFRAMED2'].Encode = dynEncode
for the one class that inherited from D2. If I do that, I find that *all*
classes that call Encode or Decode are all calling dyn{En,De}code (which
is exactly what I *don't* want).

So I looked at the id values after class generation.

  print 'IFRAMED2.Encode = ', IFRAMED2.Encode, id(IFRAMED2.Encode)
  print 'SNRMD.Encode = ', SNRMD.Encode, id(SNRMD.Encode)
  print 'IFRAMED2 = ', IFRAMED2, id(IFRAMED2)
  print 'SNRMD = ', SNRMD, id(SNRMD)
  IFRAMED2.Decode = dynDecode
  IFRAMED2.Encode = dynEncode
  print 'IFRAMED2.Encode = ', IFRAMED2.Encode, id(IFRAMED2.Encode)
  print 'SNRMD.Encode = ', SNRMD.Encode, id(SNRMD.Encode)

Here's the output:

IFRAMED2.Encode =   1100623660
SNRMD.Encode =   1100623660
IFRAMED2 =  d.IFRAMED2 1076299644
SNRMD =  d.SNRMD 1103202364
IFRAMED2.Encode =   1100623660
SNRMD.Encode =   1100623660

So it looks like the IFRAMED2 class which inherits from D2 is starting out
with the same id value for Encode as SNRMD which inherits from D, even
though D2 defines its own Encode method.

Is it me of is it the interpreter doing something wrong?

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


How to replace a method in an instance.

2007-08-24 Thread Steven W. Orr
In the program below, I want this instance to end up calling repmeth 
whenever inst.m1 is called. As it is now, I get this error:

Hello from init
inst =  <__main__.CC instance at 0x402105ec>
Traceback (most recent call last):
   File "./foo9.py", line 17, in ?
 inst.m1()
TypeError: repmeth() takes exactly 1 argument (0 given)


#! /usr/bin/python
def repmeth( self ):
 print "repmeth"

class CC:
 def __init__( self ):
 self.m1 = repmeth
 print 'Hello from init'

 def m1 ( self ):
 print "m1"

inst = CC()
inst.m1()

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to replace a method in an instance.

2007-08-24 Thread Steven W. Orr
On Friday, Aug 24th 2007 at 09:12 -0700, quoth [EMAIL PROTECTED]:

=>On Aug 24, 11:02 am, "Steven W. Orr" <[EMAIL PROTECTED]> wrote:
=>> In the program below, I want this instance to end up calling repmeth
=>> whenever inst.m1 is called. As it is now, I get this error:
=>>
=>> Hello from init
=>> inst =  <__main__.CC instance at 0x402105ec>
=>> Traceback (most recent call last):
=>>File "./foo9.py", line 17, in ?
=>>  inst.m1()
=>> TypeError: repmeth() takes exactly 1 argument (0 given)
=>>
=>> #! /usr/bin/python
=>> def repmeth( self ):
=>>  print "repmeth"
=>>
=>> class CC:
=>>  def __init__( self ):
=>>  self.m1 = repmeth
=>>  print 'Hello from init'
=>>
=>>  def m1 ( self ):
=>>  print "m1"
=>>
=>> inst = CC()
=>> inst.m1()

=>Remove "self" from repmeth as it's not required in a function, only in
=>functions that are defined within a class. Of course, a function in a
=>class is also know as a method.

Sorry. I need repmeth to have self passed to it automatically if it's 
called. I didn't mean to obfuscate the problem by not making a reference 
to self in repmeth. 

Am I being clear?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to replace a method in an instance.

2007-08-24 Thread Steven W. Orr
On Friday, Aug 24th 2007 at 12:26 -0400, quoth Steven W. Orr:

=>On Friday, Aug 24th 2007 at 09:12 -0700, quoth [EMAIL PROTECTED]:
=>
=>=>On Aug 24, 11:02 am, "Steven W. Orr" <[EMAIL PROTECTED]> wrote:
=>=>> In the program below, I want this instance to end up calling repmeth
=>=>> whenever inst.m1 is called. As it is now, I get this error:
=>=>>
=>=>> Hello from init
=>=>> inst =  <__main__.CC instance at 0x402105ec>
=>=>> Traceback (most recent call last):
=>=>>File "./foo9.py", line 17, in ?
=>=>>  inst.m1()
=>=>> TypeError: repmeth() takes exactly 1 argument (0 given)
=>=>>
=>=>> #! /usr/bin/python
=>=>> def repmeth( self ):
=>=>>  print "repmeth"
=>=>>
=>=>> class CC:
=>=>>  def __init__( self ):
=>=>>  self.m1 = repmeth
=>=>>  print 'Hello from init'
=>=>>
=>=>>  def m1 ( self ):
=>=>>  print "m1"
=>=>>
=>=>> inst = CC()
=>=>> inst.m1()
=>
=>=>Remove "self" from repmeth as it's not required in a function, only in
=>=>functions that are defined within a class. Of course, a function in a
=>=>class is also know as a method.
=>
=>Sorry. I need repmeth to have self passed to it automatically if it's 
=>called. I didn't mean to obfuscate the problem by not making a reference 
=>to self in repmeth. 
=>
=>Am I being clear?

On Friday, Aug 24th 2007 at 18:44 +0200, quoth Wildemar Wildenburger:

=>Steven W. Orr wrote:
=>> Sorry. I need repmeth to have self passed to it automatically if it's
=>> called. I didn't mean to obfuscate the problem by not making a 
reference
=>> to self in repmeth.
=>>
=>> Am I being clear?
=>>
=>>
=>Sort of. Maybe you fare better if you state what you want to achieve,
=>instead of how you think you should do it. Chances are you don't need to
=>replace a method in __init__, but there's another, less tricky way.
  
Ok. I have a collection of classes that are produced by a factory. They   
all inherit from a baseclass. One (maybe more) of the classes inherits a  
method that he shouldn't. All I want is to be able to change that
particular class so that he will have the special method that he needs
instead of the default one that he inherits. I was thinking that instead 
of making a special class for CC to inherit from which would give him his 
special replacement method(s), I could simply assign them in a manner 
which would more easily lend itself to later being table driven.

If I had a choice, I'd rather not do it in init. Instead, I'd rather be 
able to say something like 
CC.m1 = repmeth
but since in the real world, CC inherits from his baseclass, the above 
assignment causes the baseclass to be altered. :-(

Please tell me if I need to provide more.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Need a better understanding on how MRO works?

2007-08-25 Thread Steven W. Orr
Given the following code: (I hope it's as simple as possible) :-)
#! /usr/bin/python
import new
class BASE:
 def __init__( self ):
 print 'Hello from BASE init'
 def m1( self ):
 print 'M1 Base: Self = ', self

def m1replace( self ):
 print 'm1replace:Self = ', self

class D1(BASE):
 def __init__(self):
 BASE.__init__(self)

def __InitDS101Classes():
 name = 'C1'
 nclass = new.classobj(name,(D1,),globals())
 globals()[name] = nclass
 name = 'C2'
 nclass = new.classobj(name,(D1,),globals())
 globals()[name] = nclass
 globals()[name].m1 = m1replace

__InitDS101Classes()

s = C1()
s.m1()
t = C2()
t.m1()

I get the following output:

1100 > ./foo1.py
Hello from BASE init
m1replace:Self =  <__main__.C1 instance at 0xb7e637cc>
Hello from BASE init
m1replace:Self =  <__main__.C2 instance at 0xb7e6388c>

But if I make BASE inherit from object
class BASE(object):
then I get this:

1100 > ./foo1.py
Hello from BASE init
m1replace:Self =  <__main__.NewClass instance at 0xb7f5070c>
Hello from BASE init
M1 Base: Self =  <__main__.D1 instance at 0xb7f5088c>

Can someone please explain why the assignment to C2.m1 would overwrite
BASE.m1?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a better understanding on how MRO works?

2007-08-25 Thread Steven W. Orr
On Saturday, Aug 25th 2007 at 17:19 -0700, quoth Alex Martelli:

=>Steven W. Orr <[EMAIL PROTECTED]> wrote:
=>   ...
=>>  name = 'C1'
=>>  nclass = new.classobj(name,(D1,),globals())
=>>  globals()[name] = nclass
=>
=>Here, you're creating a VERY anomalous class C1 whose __dict__ is
=>globals(), i.e. the dict of this module object;
=>
=>>  name = 'C2'
=>>  nclass = new.classobj(name,(D1,),globals())
=>>  globals()[name] = nclass
=>
=>and here you're creating another class with the SAME __dict__;
=>
=>>  globals()[name].m1 = m1replace
=>
=>So of course this assignment affects the 'm1' entries in the dict of
=>both classes, since they have the SAME dict object (a la Borg) -- that
=>is, IF they're old-style classes (i.e. if D1 is old-style), since in
=>that case a class's __dict__ is in fact a dict object, plain and simple.
=>
=>However, if D1 is new-style, then C1.__dict__ and C2.__dict__ are in
=>fact instances of  -- each with a copy of the entries that
=>were in globals() when you called new.classobj, but DISTINCT from each
=>other and from globals(), so that further changes in one (or globals)
=>don't affect globals (nor the other).
=>
=>I guess this might be a decent interview question if somebody claims to
=>be a "Python guru": if they can make head or tails out of this mess, boy
=>the *ARE* a Python guru indeed (in fact I'd accord minor guruhood even
=>to somebody who can get a glimmer of understanding of this with ten
=>minutes at a Python interactive prompt or the like, as opposed to
=>needing to understand it "on paper" without the ability to explore:-).
=>
=>Among the several "don't"s to learn from this: don't use old-style
=>classes, don't try to make two classes share the same dictionary, and
=>don't ask about MRO in a question that has nothing to do with MRO
=>(though I admit that was a decent attempt at misdirection, it wouldn't
=>slow down even the minor-guru in any appreciable way:-).
=>
=>
=>Alex
=>-- 
=>http://mail.python.org/mailman/listinfo/python-list
=>

Thanks Alex. I am humbled, though I was before I started.
I really don't have a lot of understanding of what you're saying so I'll 
probably have to study this for about a year or so.

* (I need to look up what dictproxy is.) I don't have any idea what the 
ramifications are of your use of the word DISTINCT. Are you somehow 
suggesting that new.classobj does a deep copy of the globals copy that's 
passed to it?

* Also, I'd like to understand what the difference is between 
nclass = new.classobj(name,(D1,),globals())
vs. 
def classfactory():
class somename(object):
def somestuff():
pass
return somename
G1 = classfactory()
globals()[name] = G1

Does new.classobj do anything special?

I appreciate your time. 

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a better understanding on how MRO works?

2007-08-26 Thread Steven W. Orr
On Saturday, Aug 25th 2007 at 22:14 -0700, quoth Alex Martelli:

=>Steven W. Orr <[EMAIL PROTECTED]> wrote:

=>> * Also, I'd like to understand what the difference is between 
=>> nclass = new.classobj(name,(D1,),globals())
=>> vs. 
=>> def classfactory():
=>>   class somename(object):
=>>   def somestuff():
=>>   pass
=>> return somename
=>> G1 = classfactory()
=>> globals()[name] = G1
=>> 
=>> Does new.classobj do anything special?
=>
=>No, new.classobj does essentially the same thing that Python does after
=>evaluating a class statement to prepare the class's name, bases and
=>dictionary: finds the metaclass and calls it with these arguments.
=>
=>A key difference of course is that a class statement prepares the class
=>dictionary as a new, ordinary, distinct dictionary, while new.classobj
=>accepts whatever dictionary you give it (so you can, though shouldn't,
=>do strange things such as pass globals()...:-).

In fact, I wanted to make a common routine that could be called from 
multiple modules. I have classes that need to be created from those 
multiple modules. I did run into trouble when I created a common routine 
even though I passed globals() as one of the args. The """though 
shouldn't""" is prompting me to ask why, and where I might be able to read 
more.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python syntax wart

2007-09-10 Thread Steven W. Orr
On Monday, Sep 10th 2007 at 08:34 -, quoth Marc 'BlackJack' Rintsch:

=>On Mon, 10 Sep 2007 20:19:08 +1200, Lawrence D'Oliveiro wrote:
=>
=>> In message <[EMAIL PROTECTED]>, Marc 'BlackJack' Rintsch
=>> wrote:
=>> 
=>>> I see a tree structure here ...
=>> 
=>> Good, you're improving.
=>
=>Thanks.
=>
=>>> ... but still no table. 
=>> 
=>> Who said anything about a table?
=>
=>Me. If that statement is 2D I expected to see a table structure.  And I
=>don't mean that the source code itself is arranged in lines and columns
=>but that the so called *2D statement* can be seen as table.
=>
=>>> And this is also easily written that way in Python if you don't insist on
=>>> the line break after the ``if`` or can live with backslashes.
=>> 
=>> Which is precisely the point.
=>
=>Then is the lack of curly braces also a syntax wart.  Maybe you should
=>switch to a different language or write a preprocessor.

C'mon   givethe
poorguy
a   break.

Whatdid
I   just
say ?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Is every number in a list in a range?

2007-03-05 Thread Steven W. Orr
I have a list ll of intergers. I want to see if each number in ll is 
within the range of 0..maxnum

I can write it but I was wondering if there's a better way to do it?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exit to interpreter?

2007-03-27 Thread Steven W. Orr
On Friday, Mar 23rd 2007 at 10:52 -0700, quoth belinda thom:

=>I'm writing a function that polls the user for keyboard input,  
=>looping until it has determined that the user has entered a valid  
=>string of characters, in which case it returns that string so it can  
=>be processed up the call stack. My problem is this. I'd also like it  
=>to handle a special string (e.g. 'quit'), in which case control  
=>should return to the Python command line as opposed to returning the  
=>string up the call stack.
=>
=>sys.exit seemed like a good choice, but it exits the python interpreter.
=>
=>I could use an exception for this purpose, but was wondering if  
=>there's a better way?

I was reading other people's responses. Why not simply use the python 
debugger?

http://docs.python.org/lib/module-pdb.html

Yes? No?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


elementary tuple question. (sorry)

2007-04-05 Thread Steven W. Orr
I have a tuple that I got from struct.unpack. Now I want to pass the data 
from the returned tuple to struct.pack

>>> fmt
'l 10l 11i h 4h c 47c 0l'
>>>struct.pack(fmt, tup)
Traceback (most recent call last):
   File "", line 1, in ?
struct.error: required argument is not an integer

What's the idiom to pass the data in tup?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Prevent Modification of Script?

2007-04-06 Thread Steven W. Orr
On Wednesday, Apr 4th 2007 at 18:04 -0700, quoth ts-dev:

=>Is it possible to prevent modification of a python file once its been
=>deployed?  File permissions of the OS could be used..but that doesn't
=>seem very secure.
=>
=>The root of my question is verifying the integrity of the application
=>and the scripts being run. Is this possible, if so, how?

I'm going to take a stab at this one even though I'm a really junior 
pythonian.

I know others have already responded, but I'd like to offer a couple of 
suggestions that have nothing to do with python. (BTW, I do applaud the 
previous answers that suggest that this is really a non-problem in the 
first place.)

1. *IF* you are on a linux target platform then it's likely that you have
   a package management system in use, either rpm or deb. In either case,
   you have the ability to verify by checksum, every file of any package.

   In the case of rpm, just use the -V option.

2. You also have the ability to set the immutable flag on ext2/ext3
   filesystems. See lsattr/chattr commands. Of course, if you can get root
   access then you can shut off immutability, but you can also replace
   your package management tools as well. AAAUUUGGGHHH!!!

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


How to initialize a table of months.

2007-04-15 Thread Steven W. Orr
I'm reading a logfile with a timestamp at the begging of each line, e.g.,

Mar 29 08:29:00

I want to call datetime.datetim() whose arg2 is a number between 1-12 so I 
have to convert the month to an integer.
I wrote this, but I have a sneaky suspicion there's a better way to do it.

mons = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6,
 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12 }

def mon2int( mon ):
 global mons
 return mons[mon]

Is there a generator expression or a list comprehension thingy that would 
be *betterer*? (I realize it's probably not that important but I find lots 
of value in learning all the idioms.)

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested dictionaries trouble

2007-04-18 Thread Steven W. Orr
On Wednesday, Apr 18th 2007 at 12:16 -0700, quoth IamIan:

=>I am using the suggested approach to make a years list:
=>
=>years = ["199%s" % x for x in range(0,10)]
=>years += ["200%s" % x for x in range(0,10)]
=>
=>I haven't had any luck doing this in one line though. Is it possible?

I'm so green that I almost get a chubby at being able to answer something. 
;-)

years = [str(1990+x) for x in range(0,20)]

Yes?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2 daemons write to a single file /w python file IO

2007-09-14 Thread Steven W. Orr
On Tuesday, Sep 11th 2007 at 21:17 -0700, quoth Andrey:


=>i have a newbie question about the file() function.
=>I have 2 daemons running on my linux box.
=>
=>1 will record the IDs to a file - logs.txt
=>other 1 will open this file, read the IDs, and then "Clean up the 
=>file" -logs.txt
=>
=>Since these 2 daemons will run every 2-5mins, I think this will crash, isn't 
=>it? When both daemons try to write to the file at the same time.
=>
=>I am wondering if this won't crash, OR if there is some simple high-level 
=>functions can lock the file while writing...
=>I also wonder if one side locked the file, what happens if the other side 
=>try to open this locked file? raise error? so i also need to write a loop to 
=>wait for the file to release locking?
=>
=>seems a basic easy thing but i just cannot find an simple answer.
=>I always advoid this issue by putting them in mysql (well, fast and hassle 
=>free for locking)

This is more of a unix question as opposed to a python question, but I'll 
'splain it anyways :-)

If two processes each have a channel opened to the same file then it is 
very possible for the writes to collide. One way to mitigate the damage 
would be to make sure that the two processes open the file for append 
access instead of simple write access. This will ensure that the if 
ProcessA writes data that ProcessB's next write won't overwrite the data 
that A just wrote. But! It still won't work! You will still get 
interleaving of data in your output file. They will all get out there, but 
the data will on occasion look garbled because the interleaving won't look 
like it was partitioned as the different processes intended.

So what's the solution? It turns out that data that is written to a pipe 
(as opposed to data that is written to a file) is guaranteed to maintain 
its partitioned integrity.

P1 >> fn
P2 >> fn

If you are the guy who starts P1 and P2 from a parent process(PP) then you 
could structure your pipes so you end up with 

  PP > fn
 / \
/   \
   P1   P2

and just make PP be a multiplexor.  :-)

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An Editor that Skips to the End of a Def

2007-09-21 Thread Steven W. Orr
On Thursday, Sep 20th 2007 at 18:14 +0100, quoth Paul Rudin:

=>"W. Watson" <[EMAIL PROTECTED]> writes:
=>
=>> Thanks, but no thanks. The learning curve is way too steep.
=>
=>Up to you but, these days emacs comes with all sorts of
=>pointing-clicky-menu-y type things - you don't really have to learn
=>anything to get started.
=>
=>(It even gives useful advice on top-posting if you use it as a news
=>client :/)

Vuts det? Iz no longer Editor Mit Aggravating Control Sequencez? ;-)

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about quoting style.

2007-10-01 Thread Steven W. Orr
Python has a number of "quoting" 'options' to help """with
times when""" one way may be more convenient than another.

In the world of shell scripting, I use a technique that I call minimal 
quoting. It works like this:

foo=bar # No quotes needed
echo $foo   # Also none needed
baz='Hello there'   # Don't use double quotes. No iterpolation.
qaz="$baz $foo and grill" # Interpolation needs double quotes.

Is there some sort of best practices approach for when different types of 
quoting should be employed?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Version specific or not?

2007-10-10 Thread Steven W. Orr
We have an app and I'm trying to decide where the app should be 
installed. The question is whether it should be site-specific or not, as 
in

/usr/lib/python2.3/site-packages
or
/usr/lib/site-python

The latter would solve a lot of problems for me.

In the case of emacs, most stuff seems to go into $EMACS/site-lisp and far 
less into $EMACS/$current_version/site-lisp. The python site dirs seem to 
be the opposite. We have lots of stuff in the 2.3/site-packages and very 
little in the site-python directory.

If there are multiple versions of python installed on the same machine, 
having a shebang that just looked for /usr/bin/python would make my life a 
lot easier.

* Since we distribute .pyo files, is there an issue if the .pyo was built 
with 2.3.5 and then executed by 2.4 or 2.5?

* Are there any caveats?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about compiling.

2007-01-10 Thread Steven W. Orr
I *just* read the tutorial so please be gentle. I created a file called 
fib.py which works very nicely thank you. When I run it it does what it's 
supposed to do but I do not get a resulting .pyc file. The tutorial says I 
shouldn't do anything special to create it. I have machines that have both 
2.4.1 and 2.3.5. Does anyone have an idea what to do?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dot operations

2007-01-11 Thread Steven W. Orr
On Thursday, Jan 11th 2007 at 11:41 +0100, quoth robert:

=>[EMAIL PROTECTED] wrote:
=>> Hi,
=>>  Frequently I get to do like this:
=>> a = (1, 2, 3, 4) # some dummy values
=>> b = (4, 3, 2, 1)
=>> import operator
=>> c = map(operator.add, a, b)
=>> 
=>> I am finding the last line not very readable especially when I combine
=>> couple of such operations into one line. Is it possible to overload
=>> operators, so that, I can use .+ for element wise addition, as,
=>> c = a .+ b
=>> which is much more readable.
=>> 
=>> Similarly, I want to use .- , .*, ./   . Is it possible to do?
=>
=>import numpy
=>
=>You'll not even need dots

I'm very new so my plea to be gentle is still on.

I just looked at the numpy package. Seems very cool, but for the life of 
me I didn't understand the method by which python allows for creation of 
infix operators. Can someone please explain or point me to a reference?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to get whole commandline include redirection.., etc

2007-01-12 Thread Steven W. Orr
On Friday, Jan 12th 2007 at 15:11 -0800, quoth [EMAIL PROTECTED]:

=>Can I get whole commandline not only argument list.
=>
=>1. When I command like this
=>$ a.py > filename
=>2. sys.argv is returns only argument list
=>['a.py']
=>
=>Is there a way to find out 'redirection' information.

As a new person to python, I'm going to go out on a limb and declare this 
to not be a python question and to be a Unix question. If you're running 
under Windoze then my answer may not be valid since, as you can see, I 
only recently learned how to spell it.

When any Unix commandline is handed to a shell, all pipes and redirections 
are processed by that shell so that the various IO channels for the 
command are defined to point to the desired files before the command is 
even started. Only after that setup has occured is the desired command 
even started. There are books on the subject and this is not the correct 
forum to explain it all, but the docs to read that will leave you with no 
hint of idiomatic usage are all in section 2: fork, exec, open, close, dup 
and pipe (plus a few others not germain here also).

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about a single underscore.

2007-02-01 Thread Steven W. Orr
I saw this and tried to use it:

--><8--- const.py-
class _const:
 class ConstError(TypeError): pass
 def __setattr__(self,name,value):
 if self.__dict__.has_key(name):
 raise self.ConstError, "Can't rebind const(%s)"%name
 self.__dict__[name]=value

import sys
sys.modules[__name__]=_const()
--><8--- const.py-

Then when I go to try to use it I'm supposed to say:

const.pi= 3.14159
const.e = 2.7178


Two questions:

1. Why do I not have to say

_const.pi= 3.14159
_const.e = 2.7178

and is this in the tutorial?

2. Can I make this behave in such a way that I can create my constants 
with a classname that is different for different uses? e.g.,

irrational_const.pi= 3.14159
irrational_const.e = 2.7178

even_const.first= 2
even_const.firstPlus= 4

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about a single underscore.

2007-02-01 Thread Steven W. Orr
On Thursday, Feb 1st 2007 at 09:25 -0800, quoth Bart Ogryczak:

=>On Feb 1, 5:52 pm, "Steven W. Orr" <[EMAIL PROTECTED]> wrote:
=>> I saw this and tried to use it:
=>>
=>> --><8--- const.py-
=>[...]
=>> sys.modules[__name__]=_const()
=>
=>__name__ == 'const', so you?re actually doing
=>const = _const()

So how can I say this in const.py?

class _const:
class ConstError(TypeError): pass
def __setattr__(self,name,value):
if self.__dict__.has_key(name):
raise self.ConstError, "Can't rebind const(%s)"%name
self.__dict__[name]=value

def __init__(self):
sys.modules[self]=_const()

import sys

to cause a different instantiation a la

foo = _const()

The goal would be to create different instances of consts.

I did try the previous suggestion

irrational_consts = _const()

but I got

>>> import const
>>> iii=_const()
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name '_const' is not defined
*>>> iii=const()
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: _const instance has no __call__ method


For ref:

class _const:
class ConstError(TypeError): pass
def __setattr__(self,name,value):
if self.__dict__.has_key(name):
raise self.ConstError, "Can't rebind const(%s)"%name
self.__dict__[name]=value

import sys
sys.modules[__name__]=_const()



-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Question about a single underscore.

2007-02-01 Thread Steven W. Orr
On Thursday, Feb 1st 2007 at 10:36 -0800, quoth Paul Rubin:

=>"Steven W. Orr" <[EMAIL PROTECTED]> writes:
=>> to cause a different instantiation a la
=>> foo = _const()
=>> The goal would be to create different instances of consts.
=>
=>The idea of putting it in sys.modules is so it's visible in all modules.
=>
=>> >>> import const
=>> >>> iii=_const()
=>
=>You need 
=>   iii = const._const
=>-- 
=>http://mail.python.org/mailman/listinfo/python-list
=>


547 > python
Python 2.3.5 (#2, May  4 2005, 08:51:39) 
[GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import const
>>> iii = const._const
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: _const instance has no attribute '_const'
*>>> iii = const._const()
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: _const instance has no attribute '_const'
>>> 


What am I missing here? (Sorry if it should be obvious)

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about a single underscore.

2007-02-01 Thread Steven W. Orr
On Thursday, Feb 1st 2007 at 21:45 +0100, quoth Bruno Desthuilliers:

=>Steven W. Orr a écrit :
=>> I saw this and tried to use it:
=>> 
=>> --><8--- const.py-
=>> class _const:
=>> class ConstError(TypeError): pass
=>> def __setattr__(self,name,value):
=>> if self.__dict__.has_key(name):
=>> raise self.ConstError, "Can't rebind const(%s)"%name
=>> self.__dict__[name]=value
=>> 
=>> import sys
=>> sys.modules[__name__]=_const()
=>> --><8--- const.py-
=>> 
=>> Then when I go to try to use it I'm supposed to say:
=>> 
=>> const.pi= 3.14159
=>> const.e = 2.7178
=>> 
=>> 
=>> Two questions:
=>> 
=>> 1. Why do I not have to say
=>> 
=>> _const.pi= 3.14159
=>> _const.e = 2.7178
=>
=>Because of the last two lines of module const. sys.modules is a dict of 
=>already imported modules (yes, Python's modules are objects too), which 
=>avoids modules being imported twice or more. __name__ is a magic 
=>variable that is set either to the name of the module - when it's 
=>imported - or to '__main__' - when it's being directly executed as the 
=>main program. Here, when you first do 'import const', the module's code 
=>itself sets sys.modules['const'] to an instance of _const, so what you 
=>import in your namespace as 'const' is not the const module instance but 
=>a _const instance.
=>
=>> and is this in the tutorial?
=>
=>Hmmm... Not sure. FWIW, it's mostly a hack !-)
=>
=>> 2. Can I make this behave in such a way that I can create my constants 
=>> with a classname
=>
=>s/classname/name/
=>
=>> that is different for different uses? e.g.,
=>> 
=>> irrational_const.pi= 3.14159
=>> irrational_const.e = 2.7178
=>> 
=>> even_const.first= 2
=>> even_const.firstPlus= 4
=>
=>irrational_const = const.__class__()
=>even_const = const.__class__()
=>
=>Now while I find this hack interesting, it's also totally unpythonic 
=>IMHO. The usual convention is to use ALL_UPPER names for (pseudo) 
=>symbolic constants, and I don't see any reason to forcefit B&D languages 
=>concepts into Python.

Ok. Now *maybe* we're getting to where I want to be. My const.py now looks 
like this:

class _const:
class ConstError(TypeError): pass
def __setattr__(self,name,value):
if self.__dict__.has_key(name):
raise self.ConstError, "Can't rebind const(%s)"%name
self.__dict__[name]=value

import sys
sys.modules[__name__]=_const()

and in a seperate module call key_func_consts I say:

import const
# Define constants for Key Function Field.
KeyFuncConst   = const.__class__()
KeyFuncConst.NotDefined= 0x00

And in my main module I have
#! /usr/bin/python
import const
import key_func_consts
print KeyFuncConst.MSK


but the last print fails with 

The goal is to be able to create classes of global constants.

561 > t_const.py 
Traceback (most recent call last):
  File "./t_const.py", line 6, in ?
print KeyFuncConst.MSK
NameError: name 'KeyFuncConst' is not defined

Do I need to get the KeyFuncConst object into sys.modules somehow? I know 
I'm close.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net-- 
http://mail.python.org/mailman/listinfo/python-list

Question about optparse/OptionParser callback.

2007-02-09 Thread Steven W. Orr
I'm new to python and I have a need to do this.

The Cookbook almost takes me there with:

def check_order(option, opt_str, value, parser):
 if parser.values.b:
 raise OptionValueError("can't use %s after -b" % opt_str)
 setattr(parser.values, option.dest, 1)

but warns that the "it needs a bit of work: the error message and the flag 
that it sets must be generalized". I do need to do my option processing in 
an option processor with many options. Is it possible to have a callback 
that knows how to access all of the options?

Many thanks. All I need is to be taught how to fish...

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Retry:Question about optparse/OptionParser callback.

2007-02-09 Thread Steven W. Orr
I decided I could be more articulate. I hope this helps.

I'm writing a program that needs to process options. Due to the nature of 
the program with its large number of commandline options, I would like to 
write a callback to be set inside add_option.

Something like this:

parser.add_option("-b", action="callback", callback=optionhandlr, dest='b')

The Cookbook almost takes me there with a callback function that only 
works for an option called b that takes no argument:

def optionhndlr(option, opt_str, value, parser):
  if parser.values.b:
  raise OptionValueError("can't use %s after -b" % opt_str)
  setattr(parser.values, option.dest, 1)

but warns that "it needs a bit of work: the error message and the flag 
that it sets must be generalized". I do need to do my option processing in 
an option processor with many options and I'd both like to do it in one 
method (if possible) and learn a trick or two while I'm at it. Is it 
possible to have a single callback that could be used in the general case?

All I need is to be taught how to fish...

TIA

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


How do I create an array of functions?

2007-02-18 Thread Steven W. Orr
I have a table of integers and each time I look up a value from the table 
I want to call a function using the table entry as an index into an array 
whose values are the different functions.  I haven't seen anything on how 
to do this in python.

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Can I reverse eng a .pyc back to .py?

2007-02-20 Thread Steven W. Orr
The short story is that someone left, but before he left he checked in a 
.pyc and then both the directory was destroyed and the backups all got 
shredded (don't ask*). Is there anything that can be extracted? I looked 
on the web and the subject seems to get different answers, all old.

Any joy?

TIA


* Murphy's Ultimate Corollary: If it could have gone wrong earlier and it 
didn't, it ultimately would have better for it to have.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about classes and possible closure.

2007-02-21 Thread Steven W. Orr
This is all an intro learning experience for me, so please feel free to 
explain why what I'm trying to do is not a good idea.

In the Cookbook, they have a recipe for how to create global constants.

-
class _const:
 class ConstError(TypeError): pass
 def __setattr__(self,name,value):
 if self.__dict__.has_key(name):
 raise self.ConstError, "Can't rebind const(%s)"%name
 self.__dict__[name]=value

import sys
sys.modules[__name__]=_const()


I'd like to be able to create constants within a class. (Yes I understand 
that uppercase names is a far better and easier convention but this is a 
learning experience for me.)

I can't get this to work, but my idea is that MyClass is defined thusly:

class ConstError(TypeError): pass
class Myclass:
 def mprint(self):
 print "C1 = ", self._C1

 # Define a subclass to create constants. It refs upself to access
 # the uplevel copy of self.
 class _const:
 class ConstError(TypeError): pass
 def __setattr__(_upself,name,value):
 if upself.__dict__.has_key(name):
 raise self.ConstError, "Can't rebind const(%s)"%name
 else:
 print "Just set something"
 upself.__dict__[name]=value

 # I want the const instance to be contained in this class so I
 # instantiate here in the constructor.
 def __init__(self):
 upself = self
 upself.consts = const()
 upself.consts._C1 = 0
 setattr(upself.consts, "_C1", 44)
 self = upself

Then the call in another file is this:
#! /usr/bin/python
from c2 import Myclass
foo = Myclass()
foo.mprint()
# end

Is it possible to nest a class in another class and is it possible to make 
this work?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about idiomatic use of _ and private stuff.

2007-02-23 Thread Steven W. Orr
I understand that two leading underscores in a class attribute make the 
attribute private. But I often see things that are coded up with one 
underscore. Unless I'm missing something, there's a idiom going on here.

Why do people sometimes use one leading underscore?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Solved: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread Steven W. Orr
On Friday, Feb 23rd 2007 at 11:12 -0500, quoth Steven W. Orr:

=>I understand that two leading underscores in a class attribute make the 
=>attribute private. But I often see things that are coded up with one 
=>underscore. Unless I'm missing something, there's a idiom going on here.
=>
=>Why do people sometimes use one leading underscore?

I found the answer. It turns out that if you say:

import foo 

then you get access to all of the attributes that are not mangled. A 
single leading underscore does not cause mangling.

If you say 

from foo import _fooa, _foob, 

then the import will fail because the _ is used only by the import to 
decide that you shouldn't see _fooa or _foob.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about raise and exceptions.

2007-02-28 Thread Steven W. Orr
In my class I have

 class Error(Exception):
 """Base class for exceptions in this module."""
 pass

 class TransitionError(Error):
 """Raised when an operation attempts a state transition that's not
 allowed.

 Attributes:
 previous -- state at beginning of transition
 next -- attempted new state
 message -- explanation of why the specific transition is not 
allowed
 """

 def __init__(self, previous, next, message):
 self.previous = previous
 self.next = next
 self.message = message

Also in my class I check to see if a transition is legal or not:

 newstate = self.fsm[self.curr_state][self._ev]
 if newstate == self.error_state:
 raise TransitionError, self.curr_state, newstate, \
"Going to error state %d from state %d" % (self.curr_state, newstate)
 self.curr_state= self.fsm[newstate][self._ev]

When I run it I get this:

884 > ./t_fsm.py
Traceback (most recent call last):
   File "./t_fsm.py", line 3, in ?
 from fsm import *
   File "/home/boston/VIASAT/sorr/py/fsm/fsm.py", line 76
 raise TransitionError, self.curr_state, newstate, "Going to error 
state %d from state %d" % (self.curr_state, newstate)
 ^
SyntaxError: invalid syntax

(The carat is really under the comma before "Going.)

I hate to bother people with syntax problems, but I have no idea what to 
do. Sorry.

TIA :-(

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about raise and exceptions.

2007-02-28 Thread Steven W. Orr
On Wednesday, Feb 28th 2007 at 22:03 +0100, quoth Bruno Desthuilliers:

=>Daniel Klein a ?crit :
=>> On Wed, 28 Feb 2007 13:48:54 -0500 (EST), "Steven W. Orr"
=>> <[EMAIL PROTECTED]> wrote:
=>> 
=>> 
=>>>When I run it I get this:
=>>>
=>>>884 > ./t_fsm.py
=>>>Traceback (most recent call last):
=>>>  File "./t_fsm.py", line 3, in ?
=>>>from fsm import *
=>>>  File "/home/boston/VIASAT/sorr/py/fsm/fsm.py", line 76
=>>>raise TransitionError, self.curr_state, newstate, "Going to error 
=>>>state %d from state %d" % (self.curr_state, newstate)
=>>>^
=>>>SyntaxError: invalid syntax
=>> 
=>> 
=>> The arguments for TransitionError must be a tuple, 
=>
=>Err...
=>
=>> eg:
=>> 
=>> msg = "Going to error state %d from state %d" % (self.curr_state,
=>> newstate)
=>> raise TransitionError(self, curr_state, newstate, msg)
=>
=>Where did you see a tuple here ? You're code is *calling* 
=>TransitionError, passing it the needed arguments.
=>
=>Note that it's the correct syntax - but not the correct explanation !-)

Ok. Now I'm potentially confused:
1. TransitionError takes 4 args
2. raise takes a tuple with four elements after the exception argument as 
its 2nd arg

I take it you mean #2?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Assertion for python scripts

2007-11-23 Thread Steven W. Orr
On Friday, Nov 2nd 2007 at 14:14 -, quoth matthias:

=>Howdy !
=>
=>I started using the assert() stmt and found it quite useful :-)  I
=>have only one problem:  I don't
=>know how to turn them off again.
=>
=>I know that "-O" turns off assertions in general.  However, how do I
=>pass thus parameter to
=>python to an executable script ?

I had similar questions and I decided that what I really needed for my 
app was a preprocessor. I looked around and found what I thought to be 
really cool:

http://nedbatchelder.com/code/cog

It's a preprocessor written in python which allows you to embed python 
code (called cogs) in your python such that the cogs execute and are 
replaced by what they output.

I have print statements (effectively) which produce either output or 
nothing, depending on what I pass from the Makefile. The files that I 
write are called .cog.py and when I execute make, it produces .py files as 
output. It's a hugely useful thing to have available. The only slight 
disadvantage is that you have to (remember to) run make if you change your 
.cog.py files before retrying something.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Questions about subclassing an int

2008-01-04 Thread Steven W. Orr
class S(int):
 def __init__(self, value):
self.value = value
 def addStr(self, str):
self.doc = str

s = S(44)
s.addStr('Hello')

print 's = ', s
print 's.doc = ', s.doc

class T(int):
 def __init__(self, value, str):
self.value = value
self.doc = str

t = T(44, 'Goodbye')

print 't = ', t
print 't.doc = ', t.doc

It works ok with S but it fails when I try to instantiate T with a syntax 
error. Why?

Also, I don't understand why S works. If I change the name of value and 
use something else, the print of s still works by printing the integer 
value out. How does it know what value to use? Also, in S.__init__, should 
I be calling super(S, self).__init__(value) or is there a difference?

And just for fun:

class R(int):
 def __init__(self, value, doc):
 super(R, self).__init__(value)
 self.doc = doc

r = R(66,'GGG')
Traceback (most recent call last):
   File "", line 1, in ?
TypeError: an integer is required

Now it's no longer a syntax error but I don't see why it's different?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Another dumb scope question for a closure.

2008-01-09 Thread Steven W. Orr
So sorry because I know I'm doing something wrong.

574 > cat c2.py
#! /usr/local/bin/python2.4

def inc(jj):
 def dummy():
 jj = jj + 1
 return jj
 return dummy

h = inc(33)
print 'h() = ', h()
575 > c2.py
h() =
Traceback (most recent call last):
   File "./c2.py", line 10, in ?
 print 'h() = ', h()
   File "./c2.py", line 5, in dummy
 jj = jj + 1
UnboundLocalError: local variable 'jj' referenced before assignment

I could have sworn I was allowed to do this. How do I fix it?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another dumb scope question for a closure.

2008-01-10 Thread Steven W. Orr
On Wednesday, Jan 9th 2008 at 14:01 -, quoth Fredrik Lundh:

=>Steven W. Orr wrote:
=>
=>> So sorry because I know I'm doing something wrong.
=>> 
=>> 574 > cat c2.py
=>> #! /usr/local/bin/python2.4
=>> 
=>> def inc(jj):
=>>  def dummy():
=>>  jj = jj + 1
=>>  return jj
=>>  return dummy
=>> 
=>> h = inc(33)
=>> print 'h() = ', h()
=>> 575 > c2.py
=>> h() =
=>> Traceback (most recent call last):
=>>File "./c2.py", line 10, in ?
=>>  print 'h() = ', h()
=>>File "./c2.py", line 5, in dummy
=>>  jj = jj + 1
=>> UnboundLocalError: local variable 'jj' referenced before assignment
=>
=>http://docs.python.org/ref/naming.html has the answer:
=>
=> "If a name binding operation occurs anywhere within a code block,
=> all uses of the name within the block are treated as references
=> to the current block."

Thanks. This helps a little. But I still don't understand something. If 
it's a question of a legal reference or not, I could buy it. But what's 
really happening is that it works if it's a read-only ref but fails if 
it's a write:

>>> def inc(jj):
... def dummy():
... print jj
... return dummy
... 
>>> f = inc(44)
>>> f()
44
>>> f()
44
>>> f()
44
>>> 

The problem only happens if I try to modify jj.

What am I not understanding?

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


class closure question

2008-01-17 Thread Steven W. Orr
I want to indirectly change the value of a variable.

#! /usr/bin/python
foo = [44]
bar = foo
bar[0] = 55
print 'bar = ', bar
print 'foo = ', foo

This works fine.

bar =  [55]
foo =  [55]

But I want to do the same with a class value.

#! /usr/bin/python
S = None
dd = { 'class': [S] }
class C1(object):
 def __init__(self):
 print 'Hello from C1'

def mkclass(base):
 class zzz(base):
 pass
 return zzz

dd['class'][0] = mkclass( C1 )
print "dd['class'][0].__bases__ = ", dd['class'][0].__bases__
print 'S = ', S

The answer is not what I want:

dd['class'][0].__bases__ =  (,)
S =  None

The goal is for S to be set to the returned class from mkclass.

Can someone help?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Question on importing wxPython

2008-01-28 Thread Steven W. Orr
python-2.3.5
wx-2.6

I just bought the wxPython In Action book and I see that all the examples 
say to
import wx
All of our pre-existing code was horribly doing a
from wxPython import *

I changed all the code so that it was doing an import wx and found that 
everything was broken. In particular, references to wxNewId would fail.

634 > python
Python 2.3.5 (#2, May  4 2005, 08:51:39)
[GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
>>> wx.wxNewId
Traceback (most recent call last):
   File "", line 1, in ?
AttributeError: 'module' object has no attribute 'wxNewId'
>>>

In fact, the *only* way to get it was to go back to
import wxPython
and then refer to it as wxPython.wx.wxNewId

Is my system broken or am I missing something? i.e., should I be able to 
say import wx?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Looking for indent advice howto in emacs python-mode

2008-03-31 Thread Steven W. Orr
Here's what I want to do:

if ( ( v == 1 )
   or ( v == 2 )
   or ( v == 3 ) ):
 pass

but emacs (left to its own devices, does this.

if ( ( v == 1 )
  or ( v == 2 )
  or ( v == 3 ) ):
 pass

It works great for me in C-mode. Does anyone know how to jimmie up 
python-mode so it would know how to do this?

TIA


-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __init__.py file

2008-04-08 Thread Steven W. Orr
On Tuesday, Apr 8th 2008 at 16:51 -, quoth cesco:

=>Hi,
=>
=>I need to instantiate an object (my_object) whose methods I have to
=>use in two files (file1.py and file2.py) which are in the same
=>directory. Is it possible to instantiate such object in the
=>__init__.py file and then directly use it in file1.py and file2.py?
=>If not, as I seem to experience, what is the best practice to follow
=>in this case? (I thought __init__.py was somehow useful for that).

Sounds more like a job for a singleton. I recently found one that I like a 
lot better than the standard recipe:

class Singleton(object):
__single = None # the one, true Singleton
  
def __new__(classtype, *args, **kwargs):
if classtype != type(classtype.__single): 
classtype.__single = object.__new__(classtype, *args, **kwargs)
return classtype.__single
  
def __init__(self,name=None):
"""Arg doesn't have to be str."""
self.name = name

def display(self):
print self.name,id(self),type(self)

The advantage of this one is that it can be nicely subclassed.

if __name__ == "__main__":
  
class SubSingleton(Singleton):
def __init__(self, name=None):
Singleton.__init__(self, name)
self.aa = 123
self.bb = 456
self.cc = 789

o1 = Singleton('foo')
o1.display()
o2 = Singleton('bar')
o2.display()
o3 = SubSingleton('foobar')
o3.display()
o4 = SubSingleton('barfoo')
o4.display()
print 'o1 = o2:',o1 == o2
print 'o1 = o3:',o1 == o3
print 'o3 = o4:',o3 == o4

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


wxPython scrolling question.

2008-04-09 Thread Steven W. Orr
I just discovered Accelerator entries so my wx app is now able to exit 
by typing Ctrl-Q.

Can someone please tell me what to use to cause a pane to scroll up and 
down using the middle mouse scroll roller thingy? I looked and found 
wxCURSOR_MIDDLE_BUTTON but I suspect that's only good for clicking with 
the middle mouse button. I also found something called WXK_SCROLL, but how 
do I tell which direction the scroll is going?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: remove elements incrementally from a list

2010-05-19 Thread Steven W. Orr

On 5/19/2010 6:53 AM, Javier Montoya wrote:


I've a list of float numbers and I would like to delete incrementally
a set of elements in a given range of indexes, sth. like:

for j in range(beginIndex, endIndex+1):
print ("remove [%d] =>  val: %g" % (j, myList[j]))
del myList[j]

However, since I'm iterating over the same list, the indexes (range)
are not valid any more for the new list.
Does anybody has some suggestions on how to delete the elements
properly?


How about using numpy?

to_be_deleted is an array of indexes to be deleted from myList. You seem to 
already have that list created but your list is contiguous. Just in case it 
isn't, you can say stuff like:


to_be_deleted = numpy.where( myList > allowed_or_something )
myList = numpy.delete( myList, to_be_deleted )


--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Looking for matlab to python converter.

2010-05-26 Thread Steven W. Orr
I found something on sourceforge called mat2py, but there's nothing there. (It 
seems to be just a placeholder.) I figure that if anyone would know of something 
useful, this would be the place to try.


TIA

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


problem with Descriptors

2010-05-31 Thread Steven W. Orr

I just discovered descriptors but what I want to do isn't working right.

I hope this isn't too long. :-(

Here's what I have that works:

class C(object):
  def g(self):
print "dir(g):",dir(self.g)

def f(self, ss):
  print "ss = ", ss

cc = C()

cc.ff = f.__get__(C,cc)
cc.ff('Round 3')

And when I run it, it prints out:

ss =  Round 3


That's the part that works. I'm trying to use the above construct to implement a 
new kind of dict().


The idea is that I want to create a dict that knows about certain values that 
can have dependencies on other values. If you change a value that is a 
dependency of another value within the dict, then the target value will 
automatically recompute itself. In the example below, the value of the key 
"range" is dependent on the value of the key "stop".


When I run the code, the function recalc_range seems to be successfully saved as 
a bound method. (The save happens in AddDep) But then when I try to invoke the 
saved bound method, it yells at me that the arg to __getitem__ is of the wrong type.


Does anyone see what I did wrong?

class BalancedDict(dict):
  def __init__( self, initval={}, depDesc=None ):
dict.__init__(self)
self.target = []
self.deplist = []
self.recalc_f = []
self.addDep( depDesc )
if isinstance(initval, dict):
  dict.update(self, initval)

  def __setitem__(self, key, value): # setting a keyword
dict.__setitem__(self, key, value)
for ii, deps in enumerate(self.deplist):
  if key in deps:
print '__setitem__:recalc_f[%d]'%ii,self.recalc_f[ii]
print '__setitem__:targ:',self.target[ii]
print '__setitem__:deplist:',self.deplist[ii]
self.recalc_f[ii](self.target[ii],self.deplist[ii])

  def addDep(self, depDesc=None):
if not depDesc:
  return
for jj in depDesc:
  self.target.append(jj[0])
  self.deplist.append(jj[1])
  self.recalc_f.append(None)
  idx = len(self.recalc_f) - 1
  self.recalc_f[idx] = jj[2].__get__(BalancedDict, self)
  print 'addDep:self.recalc_f[%d]:'%idx, self.recalc_f[idx]


if __name__ == "__main__":
  import pprint

  def recalc_range(self, target, deplist):
print 'recalc_range:type(self):', type(self), "self:",self
print 'recalc_range:target:', target
print 'recalc_range:deplist:', deplist
stop = None
for ii in deplist:
  if ii == 'stop':
print "ii:",ii
print "self:", self, type(self)
stop = self.__getitem__(ii)
if ( isinstance( stop, int ) ):
  self.__setitem__( self[target], range( stop ) )

  pp = pprint.PrettyPrinter()
  dd = BalancedDict()
  print 'dd: Init'
  pp.pprint(dd)
  dd.addDep([['range', ['stop'], recalc_range]])
  dd['stop'] = 40
  print 'dd: After start stop and step'
  pp.pprint(dd)

C:\Users\Steve\Documents\PythonSamples>python -i vfunc3.py
dd: Init
{}
addDep:self.recalc_f[0]: '__main__.BalancedDict'>>

__setitem__:recalc_f[0] >
__setitem__:targ: range
__setitem__:deplist: ['stop']
recalc_range:type(self):  self: 
recalc_range:target: range
recalc_range:deplist: ['stop']
ii: stop
self:  
Traceback (most recent call last):
  File "vfunc3.py", line 55, in 
dd['stop'] = 40
  File "vfunc3.py", line 20, in __setitem__
self.recalc_f[ii](self.target[ii],self.deplist[ii])
  File "vfunc3.py", line 46, in recalc_range
stop = self.__getitem__(ii)
TypeError: descriptor '__getitem__' requires a 'dict' object but received a 
'str'
>>>




--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: What does this PyChecker warning mean?

2010-06-01 Thread Steven W. Orr

On 6/1/2010 7:53 AM, Xavier Ho wrote:

On 1 June 2010 21:48, Leo Breebaart mailto:l...@lspace.org>> wrote:


When fed the following code:

  def Foo():

class A(object):
def __init__(self):
pass

class B(object):
def __init__(self):
pass

PyChecker 0.8.18 warns:

  foo.py:9: Redefining attribute (__init__) original line (5)


Out of curiosity, why are you defining two classes inside a function?

-Xav



In terms of constructing a minimal example, Foo might be fodder for a closure 
that either returns A or B. Just s stab in the dark...



--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: using reverse in list of tuples

2010-06-10 Thread Steven W. Orr
On 06/10/10 04:41, quoth Marco Nawijn:
> On Jun 10, 2:39 am, james_027  wrote:
>> hi,
>>
>> I am trying to reverse the order of my list of tuples and its is
>> returning a None to me. Is the reverse() function not allow on list
>> containing tuples?
>>
>> Thanks,
>> James
> 
> As the others already mentioned list.reverse() is in-place, just as
> for
> example list.sort(). Alternatively, use the builtin reversed() or
> sorted()
> functions to get a return value (they will leave the original list
> unmodified.
> 
> Example:
 a = range(3)
 b = reversed(a)
 for item in b:
>   ...print item
> This will produce:
>   2
>   1
>   0
> 
> Note that reversed returns an iterator.
> 
> Marco

How about just doing it the old fashioned way via slicing.

>>> foo = (4,5,8,2,9,1,6)
>>> foo[::-1]
(6, 1, 9, 2, 8, 5, 4)
>>>

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



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


Re: How do subprocess.Popen("ls | grep foo", shell=True) with shell=False?

2010-06-11 Thread Steven W. Orr

On 6/10/2010 11:40 AM, Chris Seberino wrote:


Even if zombies are created, they will eventually get dealt with my OS
w/o any user intervention needed right?


Bad approach. Years ago I inherited a server that didn't do a proper cleanup pf 
its slaves. After a few days running, people discovered that the machine 
performance was seriously degrading. I was called in and found that there were 
around 10,000 defunct processes (not zombies).


Remember boys and girls. Neatness counts.

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: gui doubt

2010-06-17 Thread Steven W. Orr
On 06/17/10 01:40, quoth madhuri vio:
> if i want to create a button
> which performs the transcription of dna to rna
> using tkinter in a gui...
> can u give me the method...
> 
> -- 
> madhuri :)
> 

Dear Madasahatter. You need to read the description below on how to properly
implement and use the unsubscribe button. After use, please take a piece of
cardboard and hand it around your neck to announce your accomplishment. The
algorithm below may need to be translated into python, but I would expect that
this would be the easiest part of the problem. We all wish you the best of
luck in your new venture as village idiot. In the future, please let the FBI
know if you have any problems.

From: "Dr. Bryan Bledsoe" 
To: "prehospitalcare List Member"  
Subject: [prehospitalcare] How To Remove Yourself From The List
Date: Sat, 10 Aug 2002 20:55:52 -0500
X-Mailer: Microsoft Outlook Express 6.00.2600.
X-MDRemoteIP: 207.217.120.50
Sender: prehospitalc...@emsvillage.com
X-Return-Path: prehospitalc...@emsvillage.com
List-Unsubscribe: 
X-MDMailing-List: prehospitalc...@emsvillage.com
X-MDSend-Notifications-To: prehospitalc...@emsvillage.com
Reply-To: prehospitalc...@emsvillage.com

Phil:

You are WRONG.  Here is how to unsubscribe from prehospitalc...@emsvillage.com:
How to unsubscribe (as you requested)

First, ask your Internet Provider to mail you an Unsubscribing
Kit. Then follow these directions. The kit will most likely be
the standard no-fault type. Depending on requirements,
System A and/or System B can be used. When operating System A,
depress lever and a plastic dalkron unsubscriber will be dispensed
through the slot immediately underneath. When you have fastened the
adhesive lip, attach connection marked by the large "X" outlet
hose. Twist the silver- coloured ring one inch below the connection
point until you feel it lock.

The kit is now ready for use. The Cin-Eliminator is activated by the
small switch on the lip. When securing, twist the ring back to its
initial condition, so that the two orange lines meet. Disconnect.

Place the dalkron unsubscriber in the vacuum receptacle to the
rear. Activate by pressing the blue button.

The controls for System B are located on the opposite side. The red
release switch places the Cin-Eliminator into position; it can be
adjusted manually up or down by pressing the blue manual release
button. The opening is self-adjusting. To secure after use, press the
green button, which simultaneously activates the evaporator and
returns the Cin-Eliminator to its storage position.

You may log off if the green exit light is on over the evaporator. If
the red light is illuminated, one of the Cin-Eliminator requirements
has not been properly implemented.

Press the "List Guy" call button on the right of the evaporator. He
will secure all facilities from his control panel.

To use the Auto-Unsub, first undress and place all your clothes in
the clothes rack. Put on the velcro slippers located in the cabinet
immediately below. Enter the shower, taking the entire kit with
you. On the control panel to your upper right upon entering you will
see a "Shower seal" button.

Press to activate. A green light will then be illuminated immediately
below. On the intensity knob, select the desired setting. Now depress
the Auto-Unsub activation lever.

Bathe normally.

The Auto-Unsub will automatically go off after three minutes unless
you activate the "Manual off" override switch by flipping it up. When
you are ready to leave, press the blue "Shower seal" release
button. The door will open and you may leave. Please remove the
velcro slippers and place them in their container.

If you prefer the ultrasonic log-off mode, press the indicated blue
button. When the twin panels open, pull forward by rings A & B. The
knob to the left, just below the blue light, has three settings, low,
medium or high. For normal use, the medium setting is suggested.

After these settings have been made, you can activate the device by
switching to the "ON" position the clearly marked red switch. If
during the unsubscribing operation you wish to change the settings,
place the "manual off" override switch in the "OFF" position. You may
now make the change and repeat the cycle. When the green exit light
goes on, you may log off and have lunch. Please close the door behind
you.




Bryan E. Bledsoe, DO, FACEP
Midlothian, Texas

All outgoing email scanned by Norton Antivirus and guaranteed
"virus free" or your money back.

- Original Message -
From: Philip L. Hayes
To: prehospitalcare List Member
Sent: Saturday, August 10, 2002 7:50 PM
Subject: [prehospitalcare] How To Remove Yourself From The List

Hi Everybody-

To remove yourself from the list serv, simply follow
the instructions at the bottom of every e-mail. Sending
an unsubscribe or remove command to the list will not
do it.

Phil Hayes
EMS Village Support



-Original Message-
From: prehospitalc...@emsv

[ANN] AutoRecalcDict 0.1.1 released

2010-06-21 Thread Steven W. Orr
AutoRecalcDict is a subclass of dict that allows programmers to create user
defined dependencies and functions on target keys.

You can find it at

http://pypi.python.org/pypi/AutoRecalcDict/0.1.1

I recently was designing tests for radio frequency analysis (about which, I know
nothing). All of the tests had a dict of parameterizations that was peculiar to
that test, and they all had a key called 'freqs' whose value was a simple list
of just a few frequencies. But then I ran into a test that had a couple hundred
frequencies. What I really needed was to have four keys called 'freqs', 'start',
'stop', and 'step', so that freqs would be recalculated to be the return value
of the range function, if ever start, stop or step ever changed.

This is my first time contribution to the python community, so I suspect that I
might have made a few misteaks in packaging. If you see things that should be
altered, please let me know. And since I know what it does, suggestions for
better docs that speak to you (instead of me) are very welcome.

What I got out of this personally was a good learning experience in a number of
aspects that I had not previously nailed down.

Thanks for checking it out.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Need instruction on how to use isinstance

2010-06-27 Thread Steven W. Orr
I need to test an argument for a few different types.

I'm calling my function like this

arf = MyFunc(list)

What I want to do is to test for whether something is a string, tuple, list or
function. It's that last one that's causing me a problem.

if isinstance(arg, (str, tuple, list)):

No problem, but there are a lot of types that the type function returns. If I
have a simple function

def foo():
pass
type(foo)
prints out


So, my question is, what value can I use as the 2nd arg to isinstance to see if
foo is a function? And while I'm on the subject, what types does isinstance not
support?

And last, what is the correct way to do it if this is not the right way?

TIA (and hoping I'm clear)

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need instruction on how to use isinstance

2010-06-27 Thread Steven W. Orr
On 6/27/2010 10:25 PM, Stephen Hansen wrote:
> On 6/27/10 7:09 PM, Steven W. Orr wrote:
>> So, my question is, what value can I use as the 2nd arg to isinstance
>> to see if
>> foo is a function? And while I'm on the subject, what types does
>> isinstance not
>> support?
> 
> Does it have to be a function? -- There's quite a few things which are
> function-y enough that you really should accept them even if they may
> not be technically a /function/. Like a class instance with the __call__
> method defined wrapping a function as a decorator. Or a bound method,
> really.
> 
> In Python 2.x, you can use callable(fun) -- that goes away in Py3
> though. But personally, I think this is the wrong approach.

Ok, you just asked great questions, and your questions were based on what I
didn't tell you.

I'm trying to teach myself about how __metaclass__ can be used as a substitute
for LSD. ;-)

So, instead of writing a class that does typechecking on its arguments at
instantiation time, I'm writing a metaclass that allows the class to announce
what sort of values it specifically will be expecting after instantiation.

The model I'm using is something I've found that

http://cleverdevil.org/computing/78/

So, the basic idea is

>>> class Person(Enforcer):
...name = Field(str)
...age = Field(int)
...ff = Field(function)

but there's no factory function called function.

Does this help?

> 
> I'm assuming you need to do some different sort of behavior based on if
> its a str, tuple or list-- okay.
> 
> But, personally-- at that point, I would just *assume* the argument is a
> function. And call it.
> 
> If it can't be called, its not a functiony-thing. You can either let
> that traceback propagate, or just raise a TypeError "expected arg to be
> a string, tuple, list or callable".
> 
> Then again, similarly I almost never want to test for if somethings a
> tuple or list. I'd rather use it as a sequence type and see if it works:
> while there's not as many 'sequency-like-things' out there as there are
> function-like-things, there's still quite a few.
> 
> So personally, I'd check if its a string (can it be unicode or regular?
> If so isinstance(x,basestring)).
> 
> Then I'd try to use it as a sequence, doing whatever I woulda done with
> it sequence-like. If that works, great. If not, I'd try to call it.
> 
> Etc.
> 
> Then again it does depend on just what you're *doing* with the arg being
> passed in.
> 


-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: refactoring a group of import statements

2010-06-28 Thread Steven W. Orr
On 06/27/10 23:20, quoth GrayShark:
> Thanks for the help
> That was what I was looking for. All the rest, the arguments were 
> unhelpful. 
> 
> Question: If you can't answer the question, why are you talking? 
> 
> I'm American Indian. That's what I was taught. We don't talk that much. 
> But you get an answer when we do talk. Makes life simpler.
> 
> Thanks you again Thomas Jollans.
> 

Look, I'm not American Indian, though I question how many American Indians
call themselves American Indians. *But* in keeping with the true spirit of
what this python list is all about (i.e., finding new ways to aggravate
people), I refer you all to the immortal words of Tom Lehrer:

One week of every year is designated National Brotherhood Week. This is just
one of many such weeks honoring various worthy causes. One of my favorites is
National Make-fun-of-the-handicapped Week which Frank Fontaine and Jerry Lewis
are in charge of as you know. During National Brotherhood Week various special
events are arranged to drive home the message of brotherhood. This year, for
example, on the first day of the week Malcolm X was killed which gives you an
idea of how effective the whole thing is. I'm sure we all agree that we ought
to love one another and I know there are people in the world that do not love
their fellow human beings and I hate people like that. Here's a song about
National Brotherhood Week.

Oh, the white folks hate the black folks,
And the black folks hate the white folks.
To hate all but the right folks
Is an old established rule.

But during National Brotherhood Week, National Brotherhood Week,
Lena Horne and Sheriff Clarke are dancing cheek to cheek.
It's fun to eulogize
The people you despise,
As long as you don't let 'em in your school.

Oh, the poor folks hate the rich folks,
And the rich folks hate the poor folks.
All of my folks hate all of your folks,
It's American as apple pie.

But during National Brotherhood Week, National Brotherhood Week,
New Yorkers love the Puerto Ricans 'cause it's very chic.
Step up and shake the hand
Of someone you can't stand.
You can tolerate him if you try.

Oh, the Protestants hate the Catholics,
And the Catholics hate the Protestants,
And the Hindus hate the Muslims,
And everybody hates the Jews.

But during National Brotherhood Week, National Brotherhood Week,
It's National Everyone-smile-at-one-another-hood Week.
Be nice to people who
Are inferior to you.
It's only for a week, so have no fear.
Be grateful that it doesn't last all year!

http://www.youtube.com/watch?v=dUwbZ9AlSPI


-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



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


Re: Check if a command is valid

2010-07-14 Thread Steven W. Orr
On 07/12/10 21:29, quoth Kenny Meyer:
> Hello,
> 
> I have to figure out if a string is callable on a Linux system. I'm
> actually doing this:
> 
> def is_valid_command(command):
> retcode = 100 # initialize
> if command:
> retcode = subprocess.call(command, shell=True)
> if retcode is 0:
> print "Valid command."
> else:
> print "Looks not so good..."
> 
> is_valid_command("ls")
> 
> Never mind the code, because this is not the original.
> The side effect of subprocess.call() is that it *actually* executes
> it, but I just need the return code. What are better ways of doing
> this?

Luke! Use the force!

#! /usr/bin/python

import os
def is_valid_command(command):
looking_good = False
for ii in os.environ['PATH'].split(':'):
if os.access(ii + '/' + command, os.X_OK):
looking_good = True
break
print ["Looks not so good...", "Valid command."][looking_good]

is_valid_command('python')
is_valid_command('pythoon')

This way you don't start up any subprocesses and you are actually doing what
the shell would do for you.

THE ONLY DIFFERENCE is that a persistent bash would hash all of the contents
of what lives in PATH and so might have a slight shot of being faster under
somewhat obscure conditions.

I would strongly encourage you to not execute an arbitrary string to see if it
returns a pretty return code.

is_valid_command('{cd /; rm -rf /}')

Warning:
* It only checks if the command exists in PATH and is executable TO YOU:
* Do not make fun of is_valid_command. It will get angry.
* You might also want to beef it up a la
pp = ii + '/' + command
if os.access(pp, (os.X_OK) and not os.stat.isdir(p)):
so you are checking executable files and not directories etc...
* More warnings can be amplified upon over pitchers of beer.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



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


Re: How to capture all the environment variables from shell?

2010-07-26 Thread Steven W. Orr
On 07/26/10 20:02, quoth Chris Rebert:
> On Mon, Jul 26, 2010 at 4:36 PM, Peng Yu  wrote:
> 
> You need to "export R_HOME" in bash (probably in your .bashrc or
> .bash_profile). See
> http://www.ibm.com/developerworks/library/l-bash.html#N10074

Please! Never export anything from your .bashrc unless you really know what
you're doing. Almost all exports should be done in your .bash_profile

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



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


Re: How to capture all the environment variables from shell?

2010-07-27 Thread Steven W. Orr
On 07/26/10 22:42, quoth Tim Chase:
> On 07/26/10 21:26, Steven W. Orr wrote:
>> Please! Never export anything from your .bashrc unless you
>> really know what you're doing. Almost all exports should be
>> done in your .bash_profile
> 
> Could you elaborate on your reasoning why (or why-not)?  I've found that
> my .bash_profile doesn't get evaluated when I crank up another terminal
> window, while my bashrc does.  Thus I tend to put my exports in my
> ~/.bashrc so they actually take effect in my shell...
> 
> -tkc
> 
> 

I'm happy to elaborate, but people should feel free to stop me if they're not
interested. The topic is bash:

When you log in you get your .bash_profile and not the .bashrc. Subshells get
the .bashrc and not the .bash_profile. If you set your envvars in your
.bash_profile then you don't need to reset them in subshells because they all
get inherited. (Inheritance of envvars is, after all, the reason that they are
envvars and not just local variables.)

The way you get your .bashrc to happen at login time is that you have to make
it happen yourself. In your .bash_profile, just say this:

. ~/.bashrc

The one time that you should set an envvar in your .bashrc is when you are not
an interactive shell. In that case you can set your PATH var in your .bashrc
by first testing to see if you're interactive: In your .bashrc just say:

[[ -z "$PS1" ]] && set_PATH_cmds
# Of course, note that set_PATH_cmds is not a subprocess. It has to
# be either a PATH= or function that accomplishes the same thing.

This solves the problem of things like

ssh somemachine cmd
where cmd is something that you would only find on your PATH if you properly
logged in.

As far as X goes, I am starting from the premise that your X session will be
set up to cause your .bash_profile to happen at login time.

One last note: If you say something like

export PATH=$PATH:/usr/local/bin

then re-sourcing your .bash_profile will cause your PATH value to double up.
That's why I set my PATH variable explicitly.

After that, I encourage people to set up their PATH variables so that they are
broken into four distinct sections in the following order. (The idea is to
make your stuff override the system supplied stuff.) (The stuff below is just
an example.)

USERPERSONAL=~/bin:~/share/bin
MACHINESPECIALS=/usr/local/bin:/usr/local/share/bin
OPTIONALADDONS=/opt/Adobe/Reader9/bin:/opt/openoffice.org3/program
VENDORPATHS=/bin:/usr/bin:/usr/X11R6/bin
PATH=${USERPERSONAL}:${MACHINESPECIALS}:${OPTIONALADDONS}:${VENDORPATHS}

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



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


Re: let optionparse.Optionparser ignore unknown command line switches.

2010-08-01 Thread Steven W. Orr
On 08/01/10 07:27, quoth News123:
> On 08/01/2010 01:08 PM, News123 wrote:
>> I wondered, whether there's a simple/standard way to let
>> the Optionparser just ignore unknown command line switches.
>>
> 
> In order to  illustrate, what I try to achieve:
> 
> 
> import optparse
> parser = optparse.OptionParser()
> parser.add_option("-t","--test",dest="test",action="store_true")
> argv=["tst.py","-t","--ignoreme_and_dont_fail"]
> try:
> (options,args)=parser.parse_args(argv)
> except:
> # due to --ignoreme_and_dont_fail
> # I will end up here and neither options nor
> # args will be populated
> print "parser error:"
> # However I would love to be able to see here
> # that options.test is true despite the
> # error, that occurred afterwards
> print "T",options.test
> 

You need to let us know *why* you want to do this. My psychotic imagination is
contriving that you want to pass on the ignoremeanddontfail options to
something else. If so, then you should be using -- instead of this. The other
possible scheme to solve your unknown problem is to subclass OptionParser so
it does what you want.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



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


  1   2   >