[Tutor] automatically extending PYTHONPATH?

2005-03-21 Thread Marcus Goldfish
I am using Python 2.4/IDLE on WinXP.  I organize my sourcefiles in a
directory tree, similar to the convention used in Java.  When I create
a new subdirectory, though, I have to either (i) manually edit my
PYTHONPATH environment variable, or (ii) do a sys.append() in IDLE for
the new scripts to be visible.  Is there a workaround for this?  For
example, is there a setting in IDLE of Python to specify a root source
directory and have all subdirectories added automatically?

Hope this makes sense, and that a brilliant mind has a quick solution!

Thanks,
Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] import statements in functions?

2005-03-21 Thread Marcus Goldfish
Is there a convention to be considered for deciding if import
statements should be included in a function body?  For example, which
of these two module layouts would be preferable:

 # --- MyModule1.py -
 import foo1, foo2, foo3
 import foo_special

 # several coherent functions here

 def specialFunction():
  doSomethingSpecial()

or the "embedded import" version:

 # --- MyModule2.py -
 import foo1, foo2, foo3
 import foo_rare

 # several coherent functions here

 def specialFunction():
  import foo_special
  doSomethingSpecial()

Also, does the choice have any impact on performance/space/etc.?  And
will the import function get called each time (and possibly ignored)
in the second version?

The reason I consider the second form is that the module foo_special
is only used by the code in specialFunction(), and detracts (IMHO)
from understanding the rest of the code in the module.

Thanks,
Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] python console, IDLE startup scripts

2005-03-21 Thread Marcus Goldfish
Is there a special startup script the command-line python IDE and/or
IDLE use?  As per Liam's response to my previous post, I would like to
use os.walk() to automatically set my sys.path() variable...

Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] a FIFO with fixed capacity?

2005-03-30 Thread Marcus Goldfish
I need to implement a FIFO with a fixed maximum capacity.  Is there a
name for such a beast?  Also, I read two excellent cookbook recipes on
FIFOs:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68436
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/210459

Would limiting the max capacity of the FIFO improve performance by
allowing one to preallocate the FIFO buffer?

All comments appreciated!
Thanks,

Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a FIFO with fixed capacity?

2005-03-31 Thread Marcus Goldfish
Danny,

Thanks for the informative response.  After I sent the email I
realized that a circular buffer is a FIFO with fixed capacity, and
that is what I want to implement.  I think I recall seeing a recipe in
the Python Cookbook (1st).

If you or anyone else know of other recipes/implementations please let
me know so I can save on the cut-and-paste. :)

Marcus

ps -- as for the need for a circular buffer vs. FIFO: I think my dsp
background pushed me toward the CB.  My app involves data acquisition
for extended periods of time.  I can't grow the FIFO infinitely, but
it is no big deal if a few samples get overwritten.  Does this make
sense?


On Thu, 31 Mar 2005 01:19:24 -0800 (PST), Danny Yoo
<[EMAIL PROTECTED]> wrote:
> 
> 
> On Wed, 30 Mar 2005, Marcus Goldfish wrote:
> 
> > I need to implement a FIFO with a fixed maximum capacity.
> 
> Hi Marcus,
> 
> Out of curiosity, why do you require a first-in-first-out queue with a
> maximum capacity?
> 
> 
> > Would limiting the max capacity of the FIFO improve performance by
> > allowing one to preallocate the FIFO buffer?
> 
> Possibly, but at the cost of having a FIFO that can get full.  Depending
> on the domain, this might be ok for you.  But most programs suffer from
> hardcoded limits that really shouldn't have been hardcoded in the first
> place.  You may want to see if having a queue with unlimited size is
> really a performance drag on your system: have you done any profiling yet?
> 
> The second implementation that you quoted earlier:
> 
> > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/210459
> 
> is similar to a nicer one by Jeremy Fincher:
> 
> ##
> class ListSubclassFifo(list):
>__slots__ = ('back',)
>def __init__(self):
>self.back = []
>def enqueue(self, elt):
>self.back.append(elt)
>def dequeue(self):
>if self:
>return self.pop()
>else:
>self.back.reverse()
>self[:] = self.back
>self.back = []
>return self.pop()
> ##
> 
> (See: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68436)
> 
> Since these implementations guarantee O(1) "constant" time access for a
> queue, even without a hardcoded bound limit, you aren't losing much.  Can
> you use this implementation?
> 
> Finally, there's a 'deque' in the 'collections' Standard Library module
> that you might be able to use:
> 
>http://www.python.org/doc/lib/module-collections.html
> 
> which also should define constant-time guarantees for insertion and
> removal.  So you might just be able to use that, and not have to
> copy-and-paste any code at all.  *grin*
> 
> Best of wishes to you!
> 
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a FIFO with fixed capacity?

2005-03-31 Thread Marcus Goldfish
> Let me make sure I understand.  Let's imagine that we have such a
> CircularQueue, with methods:
> 
>push(element)
>pop()
>isEmpty()
> 
> [example unittest code]

Danny,

Yes, it looks like that is a valid unittest for a circular buffer.  An
enhancement is to modify the accessors:

   push(element) --> push(sequence) 
   pop() --> pop(N)

If pushing caused an overwrite, the consumer could be notified,
perhaps by an overwrite exception.

Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] when to use properties?

2005-04-12 Thread Marcus Goldfish
Are there guidelines for when properties should be used vs. instance
variables?  For example, it often seems more convenient to directly
use instance variables instead of properties, like MyClass2 listed
below.  Is one class more pythonic than the other?

# Example 1: class w/props vs. no-propt
class MyClass1(object):
  def __init__(self, value=0):
 self._value = value
  def getValue(self):
 return self._value
  def setValue(self, value):
 self._value = value
  value = property(getValue, setValue)

class MyClass2(object):
  def __init__(self, value=0):
 self.value = value

x1 = MyClass1(3)
x1.value = 3

# same as this?
x2 = MyClass2(3)
x2.value = 3

On the other hand, I can see how classes that dynamically generate
"properties" might find the construct convenient:

# Example 2: properties "on-the-fly"
import math
class RightTriangle(object):
  def __init__ (self, a=3, b=4):
 self.a = a
 self.b = b
  def getHypotenuse(self):
 return sqrt(a**2 + b**2)
  hypotenuse = property(getHypotenuse)

t = RightTriangle()
t.hypotenuse # returns 5.0

But in Example2 it's still not clear to me whether properties buy
anything-- why not just use the getter function?

Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: when to use properties?

2005-04-13 Thread Marcus Goldfish
Thanks for all of the comments!  The general theme of "don't use a
property unless you need to" is intuitive, and is what I was hoping
the consensus would be.

This raised another design issue for me, tho', regarding property
validation.  In C#/Java, I would typically do validation in all of my
setter methods, but is this really pythonic?  It seems OO--
encapsulation-- but also seems to be one of the biggest wastes of
coding time & typing in those languages.

As a simple example, consider the following class:

#   Example: mixing instance attributes with properties.  Is it pythonic to
#   validate property data in setters?  Note that tens and ones are never
#   validated, so the class can break by setting these directly...
class SillyDecimal(object):
def __init__(self, arg=17):
if isinstance(arg, tuple):
self.tens = arg[0]
self.ones = arg[1]
else:
self.number = arg

def getNumber(self):
return self.tens*10 + self.ones
def setNumber(self, value):
if value < 0 or value > 99:
raise ArgumentException("Must in [0, 99]")
self.tens = value // 10
self.ones = value % 10
number = property(getNumber, setNumber, None, "Complete number, [0-99]")

x = SillyDecimal()
x.number, x.tens, x.ones# returns (17, 7, 1)


Notice that while "tens", "ones" and "number" all appear as
attributes, only "number" has its input validated.  Since the class is
designed to only hold numbers 0 - 99, one can 'break' it by setting
self.tens=11, for example.  Of course this is just a toy example, but
the point should be clear: when is it pythonic to do
attribute/property validation?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] iterator question for a toy class

2005-04-22 Thread Marcus Goldfish
I'm trying to understand custom iterators in Python, and created the
following toy class for sequence comparison, which seems to work:

class Foo(object):
   """A toy class to experiment with __eq__ and __iter__"""
   def __init__(self, listA, listB):
  self.head, self.tail = listA, listB
   def __iter__(self):
  return iter(self.head[:]+self.tail[:])
   def __eq__(self, other):
  """Foo instances are equal if their respective subsequences,
  head, tail, are in the same order"""
  diff = [i for i, j in zip(self, other) if i != j]
  return len(diff) == 0

>>> f1 = Foo( [1,2], ['a','b','c'] )
>>> f2 = Foo( [1,2], ['a','b','c'] )
>>> f3 = Foo( [1,2], ['a','b','d'] )
>>> f1 == f2, f1 == f3
(True, False)


I'm not really sure if I'm implementing iter() correctly, for
instance: should I make copies of the sublists?  Should I try to
implement my own next() method?

Advice, comments, and links to good tutorial web pages on iterators
are appreciated!

Thanks,
Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tracking URL in browser location bar

2005-04-22 Thread Marcus Goldfish
> > A newbie here..I was wondering if python can help me to track the URL in
> > browser (IE6+, FF, Mozilla) location bar.
I think browser helper objects may also be useful.  ASPN has a thread at:

http://aspn.activestate.com/ASPN/Mail/Message/ctypes-users/2263094

Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterator question for a toy class

2005-04-23 Thread Marcus Goldfish
> - As Rich pointed out, making Foo into it's own iterator by adding a next()
> method is not a good idea. A simple way to define your own iterator is to
I see that an iterator is conceptually distinct from the container
object it iterates over, but I am confused that both the iterator and
container implement __iter__() to support the iterator protocol.  In
my original Foo implementation, __iter__() returned a list, which
supports the iterator protocol, so it "just worked" (albeit not for
all cases, and not efficiently).  In general, though, how would I
implement my own iterator (not using generator functions)?  Would I
have to have a FooIterator class?  What would FooIterator.__iter__()
return?

> make __iter__() into a generator function like
... so gfs look much easier!  This is the first concrete use for gf's
I've found in my code so far, and it rocks-- is it always possible to
implement an iterator using gfs?  Is there a performance issue to be
aware of when using gfs?

> you want. A simple definition for __eq__() that finds these unequal would be
>   def __eq__(self, other):
> return self.head == other.head and self.tail == other.tail
Ok, I like the modified __eq__(), but now I want my Foo class to store
the head and tail lists as private attributes (self.__head,
self.__tail).  Is it pythonic to modify the __eq__() method to:

   def __eq__(self, other):
  return self.__head == other._Foo__head and self.__tail == other._Foo__tail

or is this too restrictive (e.g., perhaps I wish to compare a Foo and
Bar class as correlated list sequences.  It is likely that
other._Foo__head will fail for a Bar).

> - If you define __eq__() you should also define __ne__(). Alteratively you can
... because it seems that Foo1 != Foo2 will fail otherwise.  Why is that?

Thanks (you too, Rich) for the very helpful comments!
Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] a generic table data structure for table / 2d array / lookup table?

2005-05-28 Thread Marcus Goldfish
Before I try to reinvent the wheel, can anyone point me to a data
structure suitable for storing non-numeric, 2-d arrays.  For instance,
something that can store the following:

A  B  C  D
 1   'cat' 3object  9
 J4  [1] 56

where the column and row labels in this example are ['A','B','C','D']
and [1,'J'], respectively.  I need to access (set and get values) by
cell, row, and column.

I have a solution using 2-tuple keys and a dict, e.g., d[('A',1)], but
it seems kludgy and doesn't handle the row/column access.

Any pointers or code snippets would be appreciated!

Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] super() and inherited attributes?

2005-06-27 Thread Marcus Goldfish
Hi,

The following example doesn't work as I would like-- the child
instance doesn't expose the attribute set in the parent.  Can someone
point out what I am missing?

Thanks,
Marcus


class Parent(object):
   def __init__(self, name="I am a parent"):
  self.name = name

class Child(Parent):
   def __init__(self, number):
  super(Parent, self).__init__("I am a child")
  self.number = number

# I would like it to produce the following:
>> c = Child(23)
>> c.number
23
>> c.name
"I am a child"

# but I 'AttributeError: 'Child' object has no attribute 'name''
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] file io: reading an int32 at the end of a file?

2005-07-06 Thread Marcus Goldfish
Hi,

I have a file format that ends in a 4-byte (int32) number.  I would
like to read this value in python on a WinXP machine with something
like:

fname = 'somefile'
f = open(fname, 'rb')
f.seek(-4,2)
offset = f.read()

... but this doesn't seem to work.  The value that Python returns is:

   '@\x19\x01\x00'

but I know from similar code in Matlab that the correct sequence is:

   64 25 1 0

Can someone point out my error?

Thanks!
Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] tricky eval() problem

2005-07-22 Thread Marcus Goldfish
Here's a noodler I could use some help on: I need a class that can
call a user-specified function with arbitrary (unknown) parameter
lists.  The trick, here, is that the user will dynamically specify the
funciton to invoke, and each function may differ in the number of
parameters passed during the call.  For instance, suppose I define two
dummy functions with different calling signatures:

def foo1(a1, a2, a3):
   ...

def foo2(a1):
  ...

Then I seek a class, Caller

class Caller(object):
   def execute(self, method, *parms):
  # some way to execute method

That can be used in the following manner:

>> c = Caller();
>> c.execute("foo1", 8, 9, 10)
>> c.execute("foo2", "me")

Any tips on tackling this?

Thanks!
Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] stopping threads?

2005-09-28 Thread Marcus Goldfish
I'm a little confused about threading in Python.  Here is a sample class I've written for monitoring for events.  Included in the comments are a couple of questions, specifically:
 
   (1) can I use super() in the constructor, or is direct call to base class preferred?
   (2) do I need to sleep in the run() method?  If so, why?  It seems to improve my programs responsiveness
   (3) what happens after run() finishes-- does the thread die, get suspended, go away?  Should I try to force the thread into one of these states, and if so how?
 
Any help is appreciated!
Thanks,
Marcus
 
 
class Monitor(threading.Thread):
   def __init__(self):
  threading.Thread.__init__(self) # would super() also work here?  which is preferred
  self.undetected = True        # presumably, when the event occurs it sets this attribute to False
 
   def run(self):
  print "looking for event"
  while self.undetected is True:
 time.sleep(0.1)    # another minor point: why do I need to sleep here?
  self.processEvent()
  # what happens here-- does the thread die?
 
   def processEvent(self):
  print "yeah-- event detected"
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] quirky multiple inheritance example!?

2006-02-08 Thread Marcus Goldfish
Hi,
 
I ran across a strange problem using mulitple inheritance that I hope someone can explain.  Basically, I am implementing a Publisher pattern, and when I try to add threading, the order I list Base classes matters!  Here is the short sample code-- all help explaining this is appreciated!

 
Thanks,
Marcus
 
---
import threading
 
class Publisher(object):
   def __init__(self): self.listeners = {} 
   def register(self, id, object):
  self.listeners[id] = self.listeners.get(id, object)
 
 

# This FAILS with AttributeError: 'FancyPublisher'
# object has no attribute 'listeners'
class FancyPublisher(threading.Thread, Publisher):
   def __init__(self):
  super(FancyPublisher, self).__init__()
 
F = FancyPublisher()
F.register('me', None)    
 
 
# However, this succeeds!?

class FancyPublisher(Publisher, threading.Thread):
   def __init__(self):
  super(FancyPublisher, self).__init__()
 
F = FancyPublisher()
F.register('me', None)    
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] quickie: a better dynamic dictionary update?

2006-07-11 Thread Marcus Goldfish
Hi,I need to keep an updated dictionary of pictures in my application.  I have a function which takes snapshots of the current pictures available.  Some of the pictures in my dictionary have been deleted, so their dict entry needs to be removed.  Here is a snippet of very ugly code I have which works.  I'm looking for quick suggestions for a better implementation-- all nice replies welcomed!
Thanks,Marcus-- code snippet# 1st, find the 'stale' items in our dictionary to delete# lstKeepers is a list of current pictures# Note: if I try to iterate over the keys of the dict and
# remove-as-I-go, I get an exception (dict size changed# during iteration)lstRemove = []for key in myDict:   if key not in lstKeepers:       lstRemove.append(key) # 2nd, remove themfor oldKey in lstRemove:
   del myDict[oldKey]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] custom container subclassing list-- slices are lists!?

2006-08-21 Thread Marcus Goldfish
Hi,I'd like to sublcass the built-in list type to create my own container.  How can I make slices of the list be of type myclass-- currently they are lists.  Example:>>> class MyFoo(list):   def __init__(self, inlist):
  self = inlist[:]>>> me = MyFoo(range(10))>>> type(me)>>> type(me[0:3])All help appreciated!
Thanks,Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] custom container subclassing list-- slices are lists!?

2006-08-21 Thread Marcus Goldfish
On 8/21/06, Marcus Goldfish <[EMAIL PROTECTED]> wrote:
I'd like to sublcass the built-in list type to create my own container.  How can I make slices of the list be of type myclass-- currently they are lists.  Example:>>> class MyFoo(list):   def __init__(self, inlist):
  self = inlist[:]>>> me = MyFoo(range(10))>>> type(me)>>> type(me[0:3])
First, a better example class:class MyFoo(list):   def __init__(self, inlist):  list.__init__(self, inlist)Second, I think I found a partial answer in the Feb 22, 2005 tutor thread 
http://aspn.activestate.com/ASPN/Mail/Message/python-tutor/2502290.  To preserve type, I need to override some special functions.  In the case of slicing, I need to override with something like this:def __getslice__(self, i, j):
   return MyFoo(list.__getslice__(self, i, j))This seems straightforward, but raises other questions: what other functions should I override, e.g., __add__, __radd__?  Is there a preferred pythonic way to creating a custom list container?
Finally, should I slice-copy my input list, inlist, to prevent side effects, or is this handled by list?Thanks,Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] __init__.py for running a file from commandline?

2006-11-10 Thread Marcus Goldfish
Hoping someone can help with this...I have a logical python namespace using a directory tree and __init__.py files.  For example, PYTHONPATH points to ~pyroot, and I have the following:~pyroot/~pyroot/utils/
~pyroot/utils/commands/mygrep.pyWhich makes it nice to code:# some python scriptimport utils.commands.mygrep as grepHowever, I have a problem when running python scripts from the command line.  I would like to do this:
> python utils.commands.mygrep.pybut it doesn't work.  Is there a trick, or something that I am missing, that will let me run scripts like that?Thanks!
Marcusps-- WinXP, python 2.4
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __init__.py for running a file from commandline?

2006-11-27 Thread Marcus Goldfish

On 11/11/06, Kent Johnson <[EMAIL PROTECTED]> wrote:


Marcus Goldfish wrote:
> Hoping someone can help with this...
>
> I have a logical python namespace using a directory tree and __init__.py
> files.  For example, PYTHONPATH points to ~pyroot, and I have the
following:
>
> ~pyroot/
> ~pyroot/utils/
> ~pyroot/utils/commands/mygrep.py
>
> Which makes it nice to code:
>
> # some python script
> import utils.commands.mygrep as grep
>
> However, I have a problem when running python scripts from the command
> line.  I would like to do this:
>
>  > python utils.commands.mygrep.py
>
> but it doesn't work.  Is there a trick, or something that I am missing,
> that will let me run scripts like that?

python utils/commands/mygrep.py
will work if mygrep.py doesn't import other modules from utils; not sure
if it will work with imports.

Kent



Kent,

Hmmm... I tried this on my WinXP box-- didn't work nor with backslashing).
I checked my environment variables in my shell, and PYTHONPATH points to
~pyroot.  Am I missing something?  Could this be a 'nix thing?

Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __init__.py for running a file from commandline?

2006-12-07 Thread Marcus Goldfish

On 11/27/06, Michael P. Reilly <[EMAIL PROTECTED]> wrote:


When you type something from the command-line, you are at the whims of the
WinXP command shell.  You have to follow its rules, not Python's.  It would
need to have "python" in %PATH%, and then it would need to have to run
"python C:\path\to\pyroot\utils\commands\mygrep.py".  The arguments are
determined before Python is even started, and they are parsed by the WinXP
DOS-a-like shell. (Also why you cannot have ".", only Python understands
dots).



Doesn't python receive the command line argument, path-to-script in this
case, for its own use and parsing?

It seems like the solution I really seek is a command line switch that tells
python that I am using namespace conventions, and that it should begin
searching in the directory that PYTHONPATH points to.  For example,

c:> python -namespace utils.commands.mygrep.py

Do either of you know of such a convenience? I suppose I could write a batch
file, python.bat, that could implement this wrapping logic.


Kent mentioned issues with importing modules, and those would still hold

true since those are after Python starts.  Also, the WinXP shell, does
handle forward slashs, but you were probably not in the proper directory for
the shell to find the file using "utils/commands/mygrep.py" pathname.



Good spot-- forward slashes work, simply as relative path specifiers, so you
have to be in the correct directory.  I was not.  Thus the problem.  Also:
it appears forward slashes only work as relative path specifiers (e.g., cd
/temp), but fail if with a drive letter (e.g., c:/temp).

Thanks guys.
Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] curious struct problem

2007-02-02 Thread Marcus Goldfish

I'm trying to read a binary file using struct.  This code works
interactively in the IPython shell, but not as a function invoked from a
command line (Windows).  Can someone point out my error?  Thanks!

import struct

def demux(filename, channel, nchannels):
  "Demultiplexes a stream of shorts (signed int16) from a file."
  fmt = str(nchannels) + 'h'
  sz = struct.calcsize(fmt)

  infile = open(fname, 'rb')
  chunk = infile.read(sz)
  while chunk:
 x = struct.unpack(fmt, chunk)
 chunk = infile.read(sz)
  infile.close()

#struct.error: unpack str size does no match format
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] curious struct problem

2007-02-05 Thread Marcus Goldfish

On 2/2/07, Danny Yoo <[EMAIL PROTECTED]> wrote:


> I'm trying to read a binary file using struct.  This code works
> interactively in the IPython shell, but not as a function invoked from a
> command line (Windows).  Can someone point out my error?  Thanks!

Hi Marcus,

There is something very suspicious in the code.  You don't happen to have
any global variables in your program, do you?

Let me underline what you might want to look at.


> def demux(filename, channel, nchannels):
 



Danny,
Sorry, I had a typo.  Attached below is the complete code actually copied
from my editor.  Notice that it doesn't do anything now, which is fine b.c.
I just want to troubleshoot the problem.  The error is reproduced as a
comment below the source.  As far as I know, there are no globals; I am
invoking this from a command line prompt: python demux.py foo.bin 1 1


# ---
import struct

def demux(fname, ch=1, nchan=1):
   fmt = str(nchan) + 'h'  # nchan of short (int16)
   blockSize = struct.calcsize(fmt)

   # file setup
   infile  = open(fname, 'rb')
   #outfile = open(fname + 'ch' + str(ch), 'wb')

   # iterate over data
   chunk = infile.read(blockSize)
   while chunk:
   x = struct.unpack(fmt, chunk)
   chunk = infile.read(blockSize)

   # file cleanup
   # outfile.close()
   infile.close()

# -
#   main()
#  -
def main(argv=None):
   if argv is None:
   printHelp()
   demux(argv[1], int(argv[2]), int(argv[3])) # filename, ch, nchans


if __name__ == "__main__":
   import sys
   sys.exit(main(sys.argv))


# C:\python\python demux.py demux.py 1 1
# Traceback (most recent call last):
#   File "demux.py", line xx, in ?
# sys.exit(main(sys.argv))
#   File "demux.py", line xx, in main
# demux(argv[1], int(argv[2]), int(argv[3])) # filename, ch, nchans
#   File "demux.py", line xx, in demux
# x = struct.unpack(fmt, chunk)
# struct.error: unpack str size does not match format
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] curious struct problem

2007-02-05 Thread Marcus Goldfish

On 2/2/07, Danny Yoo <[EMAIL PROTECTED]> wrote:



There is something very suspicious in the code.  You don't happen to have
any global variables in your program, do you?



I think I found the problem: the last chunk read is incomplete, so there is
size(chunk) is not sufficient to unpack according to the format string.

Thanks!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] class design - base classes with optional properties?

2009-01-22 Thread Marcus Goldfish
I'm trying to design a base class for a hierarchy.  The properties I want to
specify for the base class depend on the values of other properties of the
base class.  For instance, in this toy example of a base FoodProcessor
class:
class FoodProcessor:
"Model for a kitchen appliance food processor"
speed_settings # example [1, 2, 3, 4]
blade_settings  # example ["slice", "grate", "grind"]
slice_thickness # example ["thin", "thick"], but only if
blade_setting is "slice"

it only make sense to have the slice_thickness property set when
blade_settings = "slice"; otherwise, it would be preferable to only define
the speed_settings and blade_settings properties.  For example:

class ProcessorA(FoodProcessor):
"A slicing-only processor"
speed_settings = [1, 2, 3, 4]
blade_settings = "slice"
slice_thickness = ["thin", "thick"]

class ProcessorB(FoodProcessor):
"A non-slicing processor"
speed_settings = [1,2,3,4]
blade_settings = ["grate", "grind"]
slice_thickness = None

Can anyone suggest some work-arounds, or refactoring for this type of
design?  Is there a design pattern for this?

Thanks!
Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor