473,325 Members | 2,608 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

Binding? problem

I may not be using the language properly, but I suspect what I have is a
binding problem and I'm wondering if there's a better solution than
what I've come up with.

I'm working on a Stack based language that can import methods from
predefined libraries. Here's what I mean.
-------
class S:
def __init__(self,value):
self.value = value

def __repr__(self):
return '<%s>' % (self.__class__.__name__)

class Library:

### this method refers to 'self.s' which it isn't
### an attribute or method
def do_this(self):
self.s.value = 'this'
class Runner:
def __init__(self):
self.s = S('whock')

def __repr__(self):
return '<%s %s>' % (self.__class__.__name__,self.S)

def importmethod(self,obj):
#setattr(self,obj..__name__,obj.do_this)
self.do_this = obj.do_this

r = Runner()
print dir(r)

r.importmethod(Library)
r.do_this()
-----------
This basically all I want to do, but the last line raises an error
because the Library class has no attribute 's'. Right now my workaround
is to declare the do_this() method of the Library class:
def do_this(self,parent):
parent.s.value = 'this'

and use this in the Runner class:

def importmethod(self,obj):
setattr(self,'do_this',obj.do_this)
#self.do_this =getattr(obj,'do_this')

Is there a better way to do this?

Thanks,
Josh English
english-at-spiritone.com

Jul 18 '05 #1
5 1498
Josh English wrote:
I'm working on a Stack based language that can import methods from
predefined libraries. Here's what I mean....

Tell us more about the problem you are trying to solve. Normally you'd
do this on classes. Why doesn't this work?:

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

def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.value)

class Mixin_do_this(object):
def do_this(self):
self.s.value = 'this'

class Runner(object):
def __init__(self):
self.s = S('whock')

def __repr__(self):
# self.s below, not self.S
return '<%s %s>' % (self.__class__.__name__, self.s)

class Runner2(Runner, Mixin_do_this): pass

r2 = Runner2()
print r2
r2.do_this()
print r2

-Scott David Daniels
Sc***********@Acm.Org
Jul 18 '05 #2
Scott David Daniels wrote:
Josh English wrote:
I'm working on a Stack based language that can import methods from
predefined libraries. Here's what I mean....

Tell us more about the problem you are trying to solve. Normally you'd
do this on classes. Why doesn't this work?:


What I want to do is have a class method that takes methods from one
class and applies them to the class instance, overriding the 'self' in
the method from the Library class to the Runner class. I'm looking for a
way to do this dynamic importing:

class Library:
... methods that have 'self' calls

r = Runner()
r.Import(Library)

r should now have the methods in the library.

Josh English

Jul 18 '05 #3
Josh English wrote:
What I want to do is have a class method that takes methods from one
class and applies them to the class instance, overriding the 'self' in
the method from the Library class to the Runner class.


There _is_ an issue of methods knowing what class they were bound in.
However, if you are willing to use staticmethod:

# Using curry (someday to show as functional.partial) as defined in:
# <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549>
import new

def curry(*args, **okwargs):
assert args
if okwargs:
def curried(*iargs, **ikwargs):
if ikwargs:
kwargs = okwargs.copy()
kwargs.update(ikwargs)
else:
kwargs = okwargs
return args[0](*(args[1:] + iargs), **kwargs)
return curried

assert len(args) >= 2
if len(args) == 2:
return new.instancemethod(args[0], args[1], object)

if len(args) <= 1:
return args[0]
## The following runs in the wrong order
## return new.function(args[0].func_code,
## args[0].func_globals, argdefs=args[1:])
def scurried(*iargs, **kwargs):
return args[0](*(args[1:] + iargs), **kwargs)
return scurried

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

def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.value)

# Python 2.3 (and 2.2?) synax:
class Library(object):
# Cannot have "true" methods -- must be normal functions
def do_this(self):
self.s.value = 'this'
do_this = staticmethod(do_this)

# Python 2.4 syntax:
# class Library(object):
# # Cannot have "true" methods -- must be normal functions
# @staticmethod
# def do_this(self):
# self.s.value = 'this'

class Runner(object):
def __init__(self):
self.s = S('whock')

def imports(self, library):
for name in dir(library):
if not name.startswith('_'):
value = getattr(library, name)
if callable(value):
setattr(self, name, curry(value, self))

def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self.s)
-Scott David Daniels
Sc***********@Acm.Org
Jul 18 '05 #4
I think that this program does what you want, with certain limitations.
It is related to the so-called Borg singleton pattern, in which all
(distinct) instances of a class have the same __dict__ so that they
appear to be identical. Here, all items in the "faux_mro" of a Runner
have the same dict as the Runner instance they serve, so when Library's
method executes it can access the "s" attribute.

I suspect that in the long run you'd be better off trying to solve your
problem in a less strange way, for instance by using the mix-in class
method suggested in an earlier message. Remember, you can use type()
or new.classobj() to create a class with given base types at run-time:
mixed_class = new.classobj("mixed", (base, mixin1, mixin2, ...), {})
mixed_instance = mixed_class()
Of course,
base = computed_base()
mixin1 = computed_mixin()
mixin2 = other_computed_mixin()
class mixed_class(base, mixin1, mixin2): pass
does the same thing.

class S:
def __init__(self,value):
self.value = value

def __repr__(self):
return '<%s: %r>' % (self.__class__.__name__, self.value)

class Library:

### this method refers to 'self.s' which it isn't
### an attribute or method
def do_this(self):
self.s.value = 'this'

class Runner:
def __init__(self):
self.s = S('whock')
self.faux_mro = []

def importmethod(self, cls):
inst = cls()
inst.__dict__ = self.__dict__
self.faux_mro.insert(-1, inst)

def __repr__(self):
return '<%s %s>' % (self.__class__.__name__,self.s)

def __getattr__(self, attr):
for item in self.faux_mro:
try:
return getattr(item, attr)
except AttributeError:
continue
raise AttributeError, ("Runner@%x nor its faux_mro has attribute %r"
% (id(self), attr))

r = Runner()
print dir(r)
print r
r.importmethod(Library)
r.do_this() # calls Library.do_this with self.__dict__ == r.__dict__
print r # r.s mutated

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.5 (GNU/Linux)

iD8DBQFBRhwhJd01MZaTXX0RAkhnAKCDyxiN8ehO2M8DKg9y+9 SZXiJ4BwCfUs30
57B1Hju1vu7YSJ1UHQT8On8=
=U3Wh
-----END PGP SIGNATURE-----

Jul 18 '05 #5
Thanks for the help. I finally got a chance to play with this and I
think I can get it to work.

Josh English
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Composer | last post by:
I've read many postings about the problem of Access.References.IsBroken and the consensus seems to be that late binding is the cure-all. I have a very complex Access application that needs...
9
by: Zlatko Matiæ | last post by:
I was reading about late binding, but I'm not completely sure what is to be done in order to adjust code to late binding... For example, I'm not sure if this is correct: early binding: Dim ws...
8
by: scorpion53061 | last post by:
I am sorry for this but I am not getting an answer elsewhere so I thought I would try here. It seems the safer way to go prior to deployment is to change my early binding to late binding to...
19
by: Simon Verona | last post by:
I'm not sure if I'm going down the correct route... I have a class which exposes a number of properties of an object (in this case the object represents a customer). Can I then use this...
1
by: Bruce | last post by:
Hi, there, I meet a problem about comboBox binding. -------------------- Database: Northwind Tables: 1) Products 2) Categories I create a form (named "form1") to edit the record from...
0
by: JSantora | last post by:
Essentially, InsertAT is broken! For the past couple of hours, I've been getting this "Parameter name: '-2147483550' is not a valid value for 'index'." error. Apparently, its caused by having...
30
by: lgbjr | last post by:
hi All, I've decided to use Options Strict ON in one of my apps and now I'm trying to fix a late binding issue. I have 5 integer arrays: dim IA1(500), IA2(500), IA3(500), IA4(500), IA5(500) as...
3
by: Simon Tamman | last post by:
I've come across an interesting bug. I have workarounds but i'd like to know the root of the problem. I've stripped it down into a short file and hope someone might have an idea about what's going...
7
by: Steve K | last post by:
First problem: I am specifying a format string for a Binding object like so: <code> Binding binding = new Binding("Text", item.EOBRemittance, "AmountAllowed", true, DataSourceUpdateMode.Never,...
0
by: furqanms | last post by:
Hello, I am new to WPF ,I am developing touch screen system using WPF. I am facing problem in Binding relative reference. Here is my code : <UserControl x:Class="uctlBrowser" ...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.