Skip to content

Instantly share code, notes, and snippets.

@brake
Created March 25, 2017 15:53
Show Gist options
  • Select an option

  • Save brake/76836a029f9ef6ded3af3470cc22d971 to your computer and use it in GitHub Desktop.

Select an option

Save brake/76836a029f9ef6ded3af3470cc22d971 to your computer and use it in GitHub Desktop.
Instance methods dynamic generation depending from __init__'s parameter, avoiding a late binding
from types import MethodType
def fn_factory(i, obj):
"""Function factory - avoids a late binding in closures"""
def fn(self):
return i
return MethodType(fn, obj)
class Aaa(object):
def __init__(self, n):
self.registry = {}
for i in range(n):
fn = fn_factory(i, self)
self.registry[i] = fn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment