Proposal for removing self - followup

  • Thread starter Ravi Teja Bhupatiraju
  • Start date
R

Ravi Teja Bhupatiraju

Well make it three cents and do an implementation, if you really
care.
I can't post a reply to that thread in Google. So I am posting the
third cent here.

Here is my implementation of the PythonCOM style __private__ ()
attributes for Python.
http://aspn.activestate.com/ASPN/do...ml/com/win32com/HTML/QuickStartServerCom.html

After

http://groups.google.com/[email protected]

the only thing left was __private__

I have done very little testing and this is my first use of
metaclasses, so watch out.

It uses the bytecode hacking module from
http://bytecodehacks.sourceforge.net/

from bytecodehacks.code_editor import Function

class PrivateType(type):
def __new__(cls, className, bases, classDict):
if '__private__' in classDict and
len(classDict['__private__']) > 0 :
# create a map of to-be-renamed functions
private_map = {}
for private_attribute in classDict['__private__']:
private_map[private_attribute] = '_%s__%s' %
(className, private_attribute)

def MutatedFunc(func):
bytecode = Function(func)
for iter, co_name in
enumerate(bytecode.func_code.co_names):
if co_name in private_map.keys():
bytecode.func_code.co_names[iter] =
private_map[co_name]
return bytecode.make_function()

# refactor references within functions
func_type = type(lambda x: x)
for attrib_name, attrib in classDict.items():
if type(attrib) == func_type:
classDict[attrib_name] = MutatedFunc(attrib)

# mangle private attributes
private = classDict['__private__']
for private_attribute in private:
temp = classDict[private_attribute]
del classDict[private_attribute]
privatized_attribute = '_%s__%s' % (className,
private_attribute)
classDict[privatized_attribute] = temp
return type.__new__(cls, className, bases, classDict)
else:
return type.__new__(cls, className, bases, classDict)

class PrivateClass(object):
__metaclass__ = PrivateType

if __name__ == '__main__':
class Foo(PrivateClass):
__private__ = ['private_func']

def public_func(self):

print "calling public func: ",
print "public"
print "calling private func: ",
self.private_func()

def private_func(self):
print "private"

foobar = Foo()
foobar.public_func()
#foobar.private_func()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top