Re: Class Definitions

2020-11-14 Thread Terry Reedy

On 11/14/2020 4:09 AM, Manfred Lotz wrote:

On 11 Nov 2020 19:21:57 GMT
r...@zedat.fu-berlin.de (Stefan Ram) wrote:


   In my Python course I gave the assignment to define a
   counter class "Main" so that

counter0 = Main()
counter1 = Main()
counter1.count(); counter1.count(); counter1.count()
counter1.count(); counter1.count()
print( counter0.value )
print( counter1.value )

   would print

0
5

   .

   I expected this solution:

class Main:
 def __init__( self ):
 self.value = 0
 def count( self ):
 self.value += 1

   but a student turned in the following solution:

class Main:
 value = 0
 def count(self):
 self.value += 1

   .


I am still a Python beginner and didn't even believe that the student's
solution would work. I had expected an error as the instance variable
self.value was not initialized.


It was not.  But self.x as a value, rather than a target, first looks 
for instance x, then class x, then superclass x, up to object.x.  Such 
lookup is routine for methods, much rarer for data.


self.value += 1 is roughly equivalent to
self.value = self.value +1 where the right self.value is Main.value. 
'self' is only looked up once, but apparently the value attribute is 
looked up twice, in spite of what one might think from the doc, so that 
the first assignment to self.value initializes an instance value rather 
than overwriting the class value.


--
Terry Jan Reedy

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


Re: Class Definitions

2020-11-14 Thread Manfred Lotz
On Sat, 14 Nov 2020 05:08:07 -0600
2qdxy4rzwzuui...@potatochowder.com wrote:

> On 2020-11-14 at 10:09:32 +0100,
> Manfred Lotz  wrote:
> 
> > On 11 Nov 2020 19:21:57 GMT
> > r...@zedat.fu-berlin.de (Stefan Ram) wrote:
> >   
> > >   In my Python course I gave the assignment to define a
> > >   counter class "Main" so that
> > > 
> > > counter0 = Main()
> > > counter1 = Main()
> > > counter1.count(); counter1.count(); counter1.count()
> > > counter1.count(); counter1.count()
> > > print( counter0.value )
> > > print( counter1.value )
> > > 
> > >   would print
> > > 
> > > 0
> > > 5
> > > 
> > >   .
> > > 
> > >   I expected this solution:
> > > 
> > > class Main:
> > > def __init__( self ):
> > > self.value = 0
> > > def count( self ):
> > > self.value += 1
> > > 
> > >   but a student turned in the following solution:
> > > 
> > > class Main:
> > > value = 0
> > > def count(self):
> > > self.value += 1
> > > 
> > >   .  
> > 
> > I am still a Python beginner and didn't even believe that the
> > student's solution would work. I had expected an error as the
> > instance variable self.value was not initialized.  
> 
> Remember:  (1) x += 1 behaves like x = x + 1, and (2) bindings created
> inside a class statement but outside any method create class
> attributes.
> 
> So after counter0 = Main(), Main (the class) has an attribute called
> "value" whose value is 0, and counter0.value refers to that attribute.
> 
> Then counter0.count() executes self.value += 1, which behaves like
> self.value = self.value + 1.  The right side of that assignment
> evaluates to 1 (the value of the class attribute plus the constant 1),
> and then the assignment statement initializes self.value to *that*
> value.
> 
> There's nothing special about initializing instance attributes in
> __init__.  An instance attribute can be created/initialized anywhere.
> 
>

Thanks to you and Stefan.


I did not know that if an instance variable doesn't exist the same
name is searched for as a class variable. 


-- 
Manfred

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


Re: Class Definitions

2020-11-14 Thread 2QdxY4RzWzUUiLuE
On 2020-11-14 at 10:09:32 +0100,
Manfred Lotz  wrote:

> On 11 Nov 2020 19:21:57 GMT
> r...@zedat.fu-berlin.de (Stefan Ram) wrote:
> 
> >   In my Python course I gave the assignment to define a
> >   counter class "Main" so that
> > 
> > counter0 = Main()
> > counter1 = Main()
> > counter1.count(); counter1.count(); counter1.count()
> > counter1.count(); counter1.count()
> > print( counter0.value )
> > print( counter1.value )
> > 
> >   would print
> > 
> > 0
> > 5
> > 
> >   .
> > 
> >   I expected this solution:
> > 
> > class Main:
> > def __init__( self ):
> > self.value = 0
> > def count( self ):
> > self.value += 1
> > 
> >   but a student turned in the following solution:
> > 
> > class Main:
> > value = 0
> > def count(self):
> > self.value += 1
> > 
> >   .
> 
> I am still a Python beginner and didn't even believe that the student's
> solution would work. I had expected an error as the instance variable
> self.value was not initialized.

Remember:  (1) x += 1 behaves like x = x + 1, and (2) bindings created
inside a class statement but outside any method create class attributes.

So after counter0 = Main(), Main (the class) has an attribute called
"value" whose value is 0, and counter0.value refers to that attribute.

Then counter0.count() executes self.value += 1, which behaves like
self.value = self.value + 1.  The right side of that assignment
evaluates to 1 (the value of the class attribute plus the constant 1),
and then the assignment statement initializes self.value to *that*
value.

There's nothing special about initializing instance attributes in
__init__.  An instance attribute can be created/initialized anywhere.

HTH,
Dan
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Class Definitions

2020-11-14 Thread Manfred Lotz
On 11 Nov 2020 19:21:57 GMT
r...@zedat.fu-berlin.de (Stefan Ram) wrote:

>   In my Python course I gave the assignment to define a
>   counter class "Main" so that
> 
> counter0 = Main()
> counter1 = Main()
> counter1.count(); counter1.count(); counter1.count()
> counter1.count(); counter1.count()
> print( counter0.value )
> print( counter1.value )
> 
>   would print
> 
> 0
> 5
> 
>   .
> 
>   I expected this solution:
> 
> class Main:
> def __init__( self ):
> self.value = 0
> def count( self ):
> self.value += 1
> 
>   but a student turned in the following solution:
> 
> class Main:
> value = 0
> def count(self):
> self.value += 1
> 
>   .

I am still a Python beginner and didn't even believe that the student's
solution would work. I had expected an error as the instance variable
self.value was not initialized.


-- 
Manfred


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


Re: Class Definitions

2020-11-12 Thread dn via Python-list




On 13/11/2020 08:47, Alan Bawden wrote:

r...@zedat.fu-berlin.de (Stefan Ram) writes:

  I expected this solution:

class Main:
def __init__( self ):
self.value = 0
def count( self ):
self.value += 1

  but a student turned in the following solution:

class Main:
value = 0
def count(self):
self.value += 1

  I thought that the solution of the student had a shortcoming
  but I was not able to put my finger on it. Can you?

Not exactly a shortcoming, but the fact that it works as a solution to
your problem may cause the student to someday write something like:

   class Main:
   value = []
   def add(self, x):
   self.value += [x]

and be suprised by the resulting behavior.



You are right to be concerned - although largely because the differences 
between class-variables and instance-variables is (sadly) one of those 
topics poorly-understood by many, and thus best avoided simply to 
prevent confusion. (I'll be the first to concur that this not a good 
reason, and particularly not for someone in education/training, but 
that's life ["as we know it, Jim"])


A worthwhile read is: https://docs.python.org/3/tutorial/classes.html

(including @Alan's most-pertinent warning of the subtleties introduced 
by mutable data-structures)



On the other hand, Python has long?always had an aversion to the 
object-induced 'boiler-plate' required in other languages - and I have 
to say, even building Python classes with __init__(), __str__(), and 
__repr__()  etc "magic methods", can seem a slog for low return-value.


AFTER teaching/learning about the 'classic form', you may like to 
consider DataClasses (Python 3.7+). These look very similar to your 
student's submission. One of their objectives is to cut-through a load 
of the boiler-plate - in many circumstances.

https://www.python.org/dev/peps/pep-0557/
https://docs.python.org/3/library/dataclasses.html

See also Counter Objects: 
https://docs.python.org/3/library/collections.html#counter-objects

--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Class Definitions

2020-11-12 Thread Alan Bawden
r...@zedat.fu-berlin.de (Stefan Ram) writes:

 I expected this solution:

   class Main:
   def __init__( self ):
   self.value = 0
   def count( self ):
   self.value += 1

 but a student turned in the following solution:

   class Main:
   value = 0
   def count(self):
   self.value += 1

 I thought that the solution of the student had a shortcoming
 but I was not able to put my finger on it. Can you?

Not exactly a shortcoming, but the fact that it works as a solution to
your problem may cause the student to someday write something like:

  class Main:
  value = []
  def add(self, x):
  self.value += [x]

and be suprised by the resulting behavior.

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


Re: Brainstorming on recursive class definitions

2017-09-12 Thread moogyd--- via Python-list
On Tuesday, September 12, 2017 at 5:37:31 PM UTC+2, Johannes Bauer wrote:
> Hi group,
> 
> so I'm having a problem that I'd like to solve *nicely*. I know plenty
> of ways to solve it, but am curious if there's a solution that allows me
> to write the solution in a way that is most comfortable for the user.
> 
> I'm trying to map registers of a processor. So assume you have a n bit
> address space, the processor might have duplicate units of identical
> functionality mapped at different places in memory. For example, assume
> there's a GPIO unit that has registers FOO, BAR and KOO and two GPIO
> ports GPIOA and GPIOB. I'd like to write code along the lines of this:
> 
> class GpioMap(BaseRegisterMap):
>   FOO = 0x0
>   BAR = 0x4
>   KOO = 0x8
> 
> class CPURegisterMap(BaseRegisterMap):
>   GPIOA = GpioMap(0x1)
>   GPIOB = GpioMap(0x2)
> 
> cpu = CPURegisterMap(0x8000)
> 
> assert(cpu.addr == 0x8000)
> assert(cpu.GPIOA.addr == 0x8000 + 0x1)
> assert(cpu.GPIOB.addr == 0x8000 + 0x2)
> assert(cpu.GPIOA.FOO.addr == 0x8000 + 0x1 + 0x0)
> assert(cpu.GPIOA.KOO.addr == 0x8000 + 0x1 + 0x8)
> assert(cpu.GPIOB.BAR.addr == 0x8000 + 0x2 + 0x4)
> 
> So, obviously, FOO, BAR and KOO are of type "int" without any "addr"
> property, so there would need to be some magic there. Additionally,
> through some way the instanciation of GpioMap() would need the knowledge
> of its parent base, which I'm not sure is even possible. Maybe (that's
> what I'm currently trying to get right) the __getattribute__ would
> propagate the information about the accumulated parent's base address to
> the child during lookup.
> 
> Anyways, I'm looking for your ideas on how to solve such a thing
> "nicely". Note that "BaseRegisterMap" is allowed to do dirty things as
> long as the definition code has a clean look & feel.
> 
> Cheers,
> Joe
> 
> 
> -- 
> >> Wo hattest Du das Beben nochmal GENAU vorhergesagt?
> > Zumindest nicht öffentlich!
> Ah, der neueste und bis heute genialste Streich unsere großen
> Kosmologen: Die Geheim-Vorhersage.
>  - Karl Kaos über Rüdiger Thomas in dsa 

A child (e.g. instance of GpioMap) should not have any knowledge of it's own 
base address. This is a function of the GPIORegisyerMap only.
i.e. The GPIORegisyerMap  would do the selection of particular instance.

It may be worth looking at some of the IP-XACT documentation, which defines 
some common terms (IIRC register, address map, address space etc). Having a 
consistent definition here will definitely help moving forward
Although it may seem OTT at the moment, it is something you should consider at 
the outset.
e.g. A single GPIO register may occur at two different addresses, depending on 
the bus master (CPU Core, Debugger, External SPI access).

Steven

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


Re: Brainstorming on recursive class definitions

2017-09-12 Thread Johannes Bauer
By the way, here's my work in progress:
https://gist.github.com/johndoe31415/7e432b4f47f0030f0903dbd6a401e5dc

I really really love the look & feel, but am unsure if there's a better
way for this?

Cheers,
Joe


-- 
>> Wo hattest Du das Beben nochmal GENAU vorhergesagt?
> Zumindest nicht öffentlich!
Ah, der neueste und bis heute genialste Streich unsere großen
Kosmologen: Die Geheim-Vorhersage.
 - Karl Kaos über Rüdiger Thomas in dsa 
-- 
https://mail.python.org/mailman/listinfo/python-list


Brainstorming on recursive class definitions

2017-09-12 Thread Johannes Bauer
Hi group,

so I'm having a problem that I'd like to solve *nicely*. I know plenty
of ways to solve it, but am curious if there's a solution that allows me
to write the solution in a way that is most comfortable for the user.

I'm trying to map registers of a processor. So assume you have a n bit
address space, the processor might have duplicate units of identical
functionality mapped at different places in memory. For example, assume
there's a GPIO unit that has registers FOO, BAR and KOO and two GPIO
ports GPIOA and GPIOB. I'd like to write code along the lines of this:

class GpioMap(BaseRegisterMap):
FOO = 0x0
BAR = 0x4
KOO = 0x8

class CPURegisterMap(BaseRegisterMap):
GPIOA = GpioMap(0x1)
GPIOB = GpioMap(0x2)

cpu = CPURegisterMap(0x8000)

assert(cpu.addr == 0x8000)
assert(cpu.GPIOA.addr == 0x8000 + 0x1)
assert(cpu.GPIOB.addr == 0x8000 + 0x2)
assert(cpu.GPIOA.FOO.addr == 0x8000 + 0x1 + 0x0)
assert(cpu.GPIOA.KOO.addr == 0x8000 + 0x1 + 0x8)
assert(cpu.GPIOB.BAR.addr == 0x8000 + 0x2 + 0x4)

So, obviously, FOO, BAR and KOO are of type "int" without any "addr"
property, so there would need to be some magic there. Additionally,
through some way the instanciation of GpioMap() would need the knowledge
of its parent base, which I'm not sure is even possible. Maybe (that's
what I'm currently trying to get right) the __getattribute__ would
propagate the information about the accumulated parent's base address to
the child during lookup.

Anyways, I'm looking for your ideas on how to solve such a thing
"nicely". Note that "BaseRegisterMap" is allowed to do dirty things as
long as the definition code has a clean look & feel.

Cheers,
Joe


-- 
>> Wo hattest Du das Beben nochmal GENAU vorhergesagt?
> Zumindest nicht öffentlich!
Ah, der neueste und bis heute genialste Streich unsere großen
Kosmologen: Die Geheim-Vorhersage.
 - Karl Kaos über Rüdiger Thomas in dsa 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Scoping rules for class definitions

2014-04-08 Thread Rotwang

On 04/04/2014 19:55, Ian Kelly wrote:

On Fri, Apr 4, 2014 at 12:37 PM, Rotwang  wrote:

Hi all. I thought I had a pretty good grasp of Python's scoping rules, but
today I noticed something that I don't understand. Can anyone explain to me
why this happens?


x = 'global'
def f1():

 x = 'local'
 class C:
 y = x
 return C.y


def f2():

 x = 'local'
 class C:
 x = x
 return C.x


f1()

'local'

f2()

'global'


Start by comparing the disassembly of the two class bodies:


dis.dis(f1.__code__.co_consts[2])

   3   0 LOAD_NAME0 (__name__)
   3 STORE_NAME   1 (__module__)
   6 LOAD_CONST   0 ('f1..C')
   9 STORE_NAME   2 (__qualname__)

   4  12 LOAD_CLASSDEREF  0 (x)
  15 STORE_NAME   3 (y)
  18 LOAD_CONST   1 (None)
  21 RETURN_VALUE

dis.dis(f2.__code__.co_consts[2])

   3   0 LOAD_NAME0 (__name__)
   3 STORE_NAME   1 (__module__)
   6 LOAD_CONST   0 ('f2..C')
   9 STORE_NAME   2 (__qualname__)

   4  12 LOAD_NAME3 (x)
  15 STORE_NAME   3 (x)
  18 LOAD_CONST   1 (None)
  21 RETURN_VALUE

The only significant difference is that the first uses
LOAD_CLASSDEREF, which I guess is the class version of LOAD_DEREF for
loading values from closures, at line 4 whereas the second uses
LOAD_NAME.  So the first one knows about the x in the nonlocal scope,
whereas the second does not and just loads the global (since x doesn't
yet exist in the locals dict).

Now why doesn't the second version also use LOAD_CLASSDEREF?  My guess
is because it's the name of a local; if it were referenced a second
time in the class then the second LOAD_CLASSDEREF would again get the
x from the nonlocal scope, which would be incorrect.


Thanks (sorry for the slow reply, I've had a busy few days).

For anyone who's interested, I also found an interesting discussion of 
the above in the following thread:


https://mail.python.org/pipermail/python-dev/2002-April/023427.html
--
https://mail.python.org/mailman/listinfo/python-list


Re: Scoping rules for class definitions

2014-04-04 Thread Ian Kelly
On Fri, Apr 4, 2014 at 12:37 PM, Rotwang  wrote:
> Hi all. I thought I had a pretty good grasp of Python's scoping rules, but
> today I noticed something that I don't understand. Can anyone explain to me
> why this happens?
>
 x = 'global'
 def f1():
> x = 'local'
> class C:
> y = x
> return C.y
>
 def f2():
> x = 'local'
> class C:
> x = x
> return C.x
>
 f1()
> 'local'
 f2()
> 'global'

Start by comparing the disassembly of the two class bodies:

>>> dis.dis(f1.__code__.co_consts[2])
  3   0 LOAD_NAME0 (__name__)
  3 STORE_NAME   1 (__module__)
  6 LOAD_CONST   0 ('f1..C')
  9 STORE_NAME   2 (__qualname__)

  4  12 LOAD_CLASSDEREF  0 (x)
 15 STORE_NAME   3 (y)
 18 LOAD_CONST   1 (None)
 21 RETURN_VALUE
>>> dis.dis(f2.__code__.co_consts[2])
  3   0 LOAD_NAME0 (__name__)
  3 STORE_NAME   1 (__module__)
  6 LOAD_CONST   0 ('f2..C')
  9 STORE_NAME   2 (__qualname__)

  4  12 LOAD_NAME3 (x)
 15 STORE_NAME   3 (x)
 18 LOAD_CONST   1 (None)
 21 RETURN_VALUE

The only significant difference is that the first uses
LOAD_CLASSDEREF, which I guess is the class version of LOAD_DEREF for
loading values from closures, at line 4 whereas the second uses
LOAD_NAME.  So the first one knows about the x in the nonlocal scope,
whereas the second does not and just loads the global (since x doesn't
yet exist in the locals dict).

Now why doesn't the second version also use LOAD_CLASSDEREF?  My guess
is because it's the name of a local; if it were referenced a second
time in the class then the second LOAD_CLASSDEREF would again get the
x from the nonlocal scope, which would be incorrect.
-- 
https://mail.python.org/mailman/listinfo/python-list


Scoping rules for class definitions

2014-04-04 Thread Rotwang
Hi all. I thought I had a pretty good grasp of Python's scoping rules, 
but today I noticed something that I don't understand. Can anyone 
explain to me why this happens?


>>> x = 'global'
>>> def f1():
x = 'local'
class C:
y = x
return C.y

>>> def f2():
x = 'local'
class C:
x = x
return C.x

>>> f1()
'local'
>>> f2()
'global'
--
https://mail.python.org/mailman/listinfo/python-list


Re: Generating class definitions at runtime in memory from XSD or JSON

2012-02-17 Thread Stefan Behnel
Stodge, 17.02.2012 02:15:
> Does anyone know of a library to generate class definitions in memory,
> at runtime, from XSD or JSON?

The question is: why do you want to do that? There may be other ways to do
what you *actually* want to do, but we don't know what that is.

Stefan

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


Re: Generating class definitions at runtime in memory from XSD or JSON

2012-02-17 Thread Nobody
On Thu, 16 Feb 2012 17:15:59 -0800, Stodge wrote:

> Does anyone know of a library to generate class definitions in memory,
> at runtime, from XSD or JSON? I know about PyXB, generateDS and some
> others, but they all rely on generating python source files at the
> command line, and then using those to parse XML.

You don't need a library to generate classes. If the type() function is
called with 3 arguments, it creates and returns a new class. The first
argument is the name of the class, the second argument a tuple of base
classes, the third argument is the class' dictionary. E.g.:

class Foo(Bar, Baz):
def __init__(self):
pass

could be written as:

def foo_init(self):
pass

Foo = type('Foo', (Bar, Baz), {'__init__': foo_init})

If you want to generate the function bodies from the contents of the
JSON or XML file, use exec().

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


Generating class definitions at runtime in memory from XSD or JSON

2012-02-16 Thread Stodge
Does anyone know of a library to generate class definitions in memory,
at runtime, from XSD or JSON? I know about PyXB, generateDS and some
others, but they all rely on generating python source files at the
command line, and then using those to parse XML.

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


Re: Amateur question on class definitions...

2011-11-29 Thread Ian Kelly
On Tue, Nov 29, 2011 at 8:21 AM, J. Marc Edwards  wrote:
> So I am defining my Python classes for a Django data model.  I have a the
> following class hierarchy and would value some expert input on how to best
> implement this.
>
> I have many instances of a particular class which I call a "workflow", e.g.
> wf_1, wf_2, wf_3, etc.
> These class instances of workflows can be combined into "composite
> workflows", e.g. {cwf_1 is comprised of wf1 & wf_3}, {cwf_2 is wf_2 and
> wf_3}, or {cwf_3 is just wf_2}, etc.
> The workflows that constitute the composite workflow is positionally
> dependent, i.e. if cwf_1 is comprised of wf_1 and wf_3, then wf_1 comes 1st
> AND wf_3 is 2nd.
> As I have many workflow instances that accumulate in my persistent database
> (Django data model), then the composite workflows become an ordered
> collection of workflow instances.
>
> My first thought here is that the composite workflow class should have a
> field that is a simple list of workflows, i.e. list(workflows), but I am
> somewhat unsure of how to code this correctly.
>
> Here is a sample pseudo-code...
>
> class a_workflow(models.Model):
> ...
>
> class composite_workflow(models.Model):
>     ...a list of "a_workflows", i.e. a composite workflow, should I use this
> syntax?
>     set_of_workflows = list(a_workflow)
>
> Is this how a pro would do this?

That would work in general, but since these are Django models I assume
that this relationship will need to be stored in the database.  You'll
need to use a ManyToManyField instead.  I would do something like
this:

class Workflow(models.Model):
pass

class CompositeWorkflow(models.Model):
workflow_set = models.ManyToManyField('Workflow',
through='CompositeWorkflowOrder')

class CompositeWorkflowOrder(models.Model):
workflow = models.ForeignKey('Workflow')
composite_workflow = models.ForeignKey('CompositeWorkflow')
sequence_num = models.IntegerField()

The CompositeWorkflowOrder model is then responsible for tracking
which workflows are contained by which composite workflows, and in
what order they appear (using sequence_num).  See the Django docs on
ManyToManyFields for more info.

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


Re: Amateur question on class definitions...

2011-11-29 Thread Chris Angelico
On Wed, Nov 30, 2011 at 2:21 AM, J. Marc Edwards  wrote:
>     ...a list of "a_workflows", i.e. a composite workflow, should I use this
> syntax?
>     set_of_workflows = list(a_workflow)
>

This would be usual:

set_of_workflows = [a_workflow]

Using the list() constructor directly is for when you have some other
iterable; for instance, a string is iterable over its characters:

>>> list("Hello")
['H', 'e', 'l', 'l', 'o']

When you want to wrap up a single object in a list, square brackets
syntax is what you want.

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


Amateur question on class definitions...

2011-11-29 Thread J. Marc Edwards
So I am defining my Python classes for a Django data model.  I have a
the following class hierarchy and would value some expert input on how
to best implement this.

I have many instances of a particular class which I call a "workflow",
e.g. wf_1, wf_2, wf_3, etc.
These class instances of workflows can be combined into "composite
workflows", e.g. {cwf_1 is comprised of wf1 & wf_3}, {cwf_2 is wf_2 and
wf_3}, or {cwf_3 is just wf_2}, etc.
The workflows that constitute the composite workflow is positionally
dependent, i.e. if cwf_1 is comprised of wf_1 and wf_3, then wf_1 comes
1st AND wf_3 is 2nd.
As I have many workflow instances that accumulate in my persistent
database (Django data model), then the composite workflows become an
ordered collection of workflow instances.

My first thought here is that the composite workflow class should have a
field that is a simple list of workflows, i.e. list(workflows), but I am
somewhat unsure of how to code this correctly.

Here is a sample pseudo-code...

class a_workflow(models.Model):
...

class composite_workflow(models.Model):
...a list of "a_workflows", i.e. a composite workflow, should I use
this syntax?
set_of_workflows = list(a_workflow)

Is this how a pro would do this?

Regards, Marc
-- 

J. Marc Edwards
Lead Architect - Semiconductor Design Portals
Nimbis Services, Inc.
Skype: (919) 747-3775
Cell:  (919) 345-1021
Fax:   (919) 882-8602
marc.edwa...@nimbisservices.com
www.nimbisservices.com

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


Re: Newbie Question. Class definitions on the fly.

2006-08-27 Thread Simon Forman
ishtar2020 wrote:
> Hi everyone
>
> I'm sure this question is kinda stupid and has been answered a few
> times before... but I need your help!
>
>  I'm writing a small application where the user can analyze some text
> based on a set of changing conditions , and right now I'm stuck on a
> point where I'd like to automatically generate new classes that operate
> based on those user-defined conditions.
>
> Is there a way in python to define a class in runtime? For instance,
> can I define a class which extends another(that I have previously
> defined in some module) , create some instance completely on the fly
> and then add/redefine methods to it?
>
> If affirmative, I've thought of a problem I would maybe have to face:
> as the class has been defined by direct input to the python
> interpreter, I could only create instances of it on the same session I
> entered the definition(because it's not on a module I can load on
> future uses) but not afterwards.  Is there a way to keep that code?
>
> Even more newbie paranoia: what would happen if I make that 'on the
> fly" object persist via pickle? Where would Python find the code to
> handle it once unpickled on another session (once again, i take that no
> code with the definition of that instance would exist, as it was never
> stored on a module).
>
> Hope it wasn't too ridiculous an idea.
>
> Thank you for your time, guys.

It's not ridiculous at all.  The easiest way to do what you want would
be to build a string containing your new class and then run it with the
exec statement:

|>> s = 'class foo: pass'
|>> exec s
|>> foo


If you want to keep your new class around between runs of your script
(and if you want to make it pickle-able) then you should write your
strings to a .py file (be sure to include an import statement to import
the classes you're subclassing) and import that file.

If you do that and are going to modify the class(es) during a single
session, be sure to call reload() on your new (modified) file (rather
than just importing it again) otherwise you won't get the changes.

See http://docs.python.org/ref/exec.html for the exec statement and
http://docs.python.org/lib/built-in-funcs.html#l2h-59 for the reload()
function.

Peace,
~Simon

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


Re: Newbie Question. Class definitions on the fly.

2006-08-27 Thread hiaips

ishtar2020 wrote:
> Hi everyone
>
> I'm sure this question is kinda stupid and has been answered a few
> times before... but I need your help!
>
>  I'm writing a small application where the user can analyze some text
> based on a set of changing conditions , and right now I'm stuck on a
> point where I'd like to automatically generate new classes that operate
> based on those user-defined conditions.
>
> Is there a way in python to define a class in runtime? For instance,
> can I define a class which extends another(that I have previously
> defined in some module) , create some instance completely on the fly
> and then add/redefine methods to it?
>
> If affirmative, I've thought of a problem I would maybe have to face:
> as the class has been defined by direct input to the python
> interpreter, I could only create instances of it on the same session I
> entered the definition(because it's not on a module I can load on
> future uses) but not afterwards.  Is there a way to keep that code?
>
> Even more newbie paranoia: what would happen if I make that 'on the
> fly" object persist via pickle? Where would Python find the code to
> handle it once unpickled on another session (once again, i take that no
> code with the definition of that instance would exist, as it was never
> stored on a module).
>
> Hope it wasn't too ridiculous an idea.
>
> Thank you for your time, guys.

You might check out the following link on metaclass programming:

http://www-128.ibm.com/developerworks/linux/library/l-pymeta.html

The author gives at least one short example of creating a class
dynamically and using an instance of it. There are also links to other,
related articles and topics at the bottom.

--dave

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


Newbie Question. Class definitions on the fly.

2006-08-27 Thread ishtar2020
Hi everyone

I'm sure this question is kinda stupid and has been answered a few
times before... but I need your help!

 I'm writing a small application where the user can analyze some text
based on a set of changing conditions , and right now I'm stuck on a
point where I'd like to automatically generate new classes that operate
based on those user-defined conditions.

Is there a way in python to define a class in runtime? For instance,
can I define a class which extends another(that I have previously
defined in some module) , create some instance completely on the fly
and then add/redefine methods to it?

If affirmative, I've thought of a problem I would maybe have to face:
as the class has been defined by direct input to the python
interpreter, I could only create instances of it on the same session I
entered the definition(because it's not on a module I can load on
future uses) but not afterwards.  Is there a way to keep that code?

Even more newbie paranoia: what would happen if I make that 'on the
fly" object persist via pickle? Where would Python find the code to
handle it once unpickled on another session (once again, i take that no
code with the definition of that instance would exist, as it was never
stored on a module).

Hope it wasn't too ridiculous an idea.

Thank you for your time, guys.

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


Re: Dynamically Update Class Definitions?

2005-11-12 Thread Chris Spencer
Jean-Paul Calderone wrote:

> There are lots of cases where you cannot rebind the __class__ 
> attribute.  For a comprehensive treatment of this idea (but still not a 
> completely functionality implementation), take a look at 
> .
>   
> On another note, the usage of threads in this code is totally insane and 
> unsafe.  Even for strictly development purposes, I would expect it to 
> introduce so many non-deterministic and undebuggable failures as to make 
> it cost more time than it saves.  You really want to stop the rest of 
> the program, then update things, then let everything get going again.

I used a thread to quickly detect changes in the source code, but you're 
absolutely right. In any non-toy application you'll definitely need 
control over when the upgrade process occurs. Thanks for the help.

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


Re: Dynamically Update Class Definitions?

2005-11-11 Thread Jean-Paul Calderone
On Sat, 12 Nov 2005 06:24:57 GMT, Chris Spencer <[EMAIL PROTECTED]> wrote:
>Chris Spencer wrote:
>> Alex Martelli wrote:
>
>>> If you're in no hurry, you COULD loop over all of gc.get_objects(),
>>> identify all those which are instances of old_class and "somehow" change
>>> their classes to new_class -- of course, x.__class__ = new_class may
>>> well not be sufficient, in which case you'll have to pass to update a
>>> callable to do the instance-per-instance job.
>>
>>
>> Couldn't I just loop over gc.get_referrers(cls), checking for instances
>> of the class object? Since class instances refer to their class, the gc
>> seems to be doing the exact same thing as Hudson's fancy metaclass. Or
>> am I missing something?
>>
>> Chris
>
>In fact, the following code seems to work, and doesn't require any
>modification to new-style class based code:

There are lots of cases where you cannot rebind the __class__ attribute.  For a 
comprehensive treatment of this idea (but still not a completely functionality 
implementation), take a look at 
.
  On another note, the usage of threads in this code is totally insane and 
unsafe.  Even for strictly development purposes, I would expect it to introduce 
so many non-deterministic and undebuggable failures as to make it cost more 
time than it saves.  You really want to stop the rest of the program, then 
update things, then let everything get going again.

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


Re: Dynamically Update Class Definitions?

2005-11-11 Thread Chris Spencer
Chris Spencer wrote:
> Alex Martelli wrote:

>> If you're in no hurry, you COULD loop over all of gc.get_objects(),
>> identify all those which are instances of old_class and "somehow" change
>> their classes to new_class -- of course, x.__class__ = new_class may
>> well not be sufficient, in which case you'll have to pass to update a
>> callable to do the instance-per-instance job.
> 
> 
> Couldn't I just loop over gc.get_referrers(cls), checking for instances 
> of the class object? Since class instances refer to their class, the gc 
> seems to be doing the exact same thing as Hudson's fancy metaclass. Or 
> am I missing something?
> 
> Chris

In fact, the following code seems to work, and doesn't require any 
modification to new-style class based code:

import os
import time
import threading
import inspect
import gc
import copy

class ModuleUpdater(object):
 '''
 This will constantly check a module's source file for updates, reload
 if any are detected, and update all class instances.
 Only works for new-style classes.

 Use like:
 checker = ModuleUpdater(module=mymod)
 checker.start()
 '''
 def __init__(self, module):
 self.module = module
 self.lastloaded = time.time()
 self.running = 0
 self.t = None
 def __call__(self):
 self.running = 1
 while self.running:
 self.check()
 time.sleep(1)
 def check(self):
 lastmodified = os.stat(inspect.getsourcefile(self.module))[8]
 if lastmodified > self.lastloaded:
 print 'update detected for',self.module.__name__
 oldmod = copy.copy(self.module.__dict__)
 newmod = reload(self.module)
 try:
 for name,obj in oldmod.items():
 if isinstance(obj,type) and name in newmod.__dict__:
 newobj = newmod.__dict__[name]
 referrers = gc.get_referrers(obj)
 for referrer in referrers:
 if isinstance(referrer,obj):
 # update old class instances to use new 
class
 referrer.__class__ = newobj
 print 'update loaded for',self.module.__name__
 except Exception, e:
 print 'unable to load update for %s: %s' % 
(self.module.__name__, str(e))
 self.lastloaded = lastmodified
 return 1
 return 0
 def start(self):
 t = threading.Thread(target=self)
 t.setDaemon(1)
 t.start()
 self.t = t
 return t
 def stop(self, blocking=0):
 self.running = 0
 if blocking:
 self.t.join()

if __name__ == '__main__':

 import testmod # any module containing class Bar with method meth
 uc = ModuleUpdater(testmod)

 uc.start()

 b=testmod.Bar(1)
 while 1: # meanwhile, modify the source to testmod.py
 time.sleep(1)
 print b.meth()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamically Update Class Definitions?

2005-11-11 Thread Chris Spencer
Alex Martelli wrote:
> <[EMAIL PROTECTED]> wrote:
> 
> 
>>Is there a way to loop through all instantiated objects and update
>>their classes when a source file changes? I know about Michael Hudson's
>>method
>>(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164), but
>>you have to modify all your classes to subclass AutoReloader. Is there
>>something less intrusive (visitor pattern?) that you can use like
>>update(old_class, new_class) to automagically do the work?
> 
> 
> If you're in no hurry, you COULD loop over all of gc.get_objects(),
> identify all those which are instances of old_class and "somehow" change
> their classes to new_class -- of course, x.__class__ = new_class may
> well not be sufficient, in which case you'll have to pass to update a
> callable to do the instance-per-instance job.

Couldn't I just loop over gc.get_referrers(cls), checking for instances 
of the class object? Since class instances refer to their class, the gc 
seems to be doing the exact same thing as Hudson's fancy metaclass. Or 
am I missing something?

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


Re: Dynamically Update Class Definitions?

2005-11-11 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:

> Is there a way to loop through all instantiated objects and update
> their classes when a source file changes? I know about Michael Hudson's
> method
> (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164), but
> you have to modify all your classes to subclass AutoReloader. Is there
> something less intrusive (visitor pattern?) that you can use like
> update(old_class, new_class) to automagically do the work?

If you're in no hurry, you COULD loop over all of gc.get_objects(),
identify all those which are instances of old_class and "somehow" change
their classes to new_class -- of course, x.__class__ = new_class may
well not be sufficient, in which case you'll have to pass to update a
callable to do the instance-per-instance job.


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


Dynamically Update Class Definitions?

2005-11-11 Thread chrisspen
Is there a way to loop through all instantiated objects and update
their classes when a source file changes? I know about Michael Hudson's
method
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164), but
you have to modify all your classes to subclass AutoReloader. Is there
something less intrusive (visitor pattern?) that you can use like
update(old_class, new_class) to automagically do the work?

Chris

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