当前位置: 首页>>代码示例>>Python>>正文


Python WeakSet.copy方法代码示例

本文整理汇总了Python中weakref.WeakSet.copy方法的典型用法代码示例。如果您正苦于以下问题:Python WeakSet.copy方法的具体用法?Python WeakSet.copy怎么用?Python WeakSet.copy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在weakref.WeakSet的用法示例。


在下文中一共展示了WeakSet.copy方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_weak_destroy_and_mutate_while_iterating

# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import copy [as 别名]
    def test_weak_destroy_and_mutate_while_iterating(self):
        # Issue #7105: iterators shouldn't crash when a key is implicitly removed
        items = [SomeClass(c) for c in string.ascii_letters]
        s = WeakSet(items)
        @contextlib.contextmanager
        def testcontext():
            try:
                it = iter(s)
                next(it)
                # Schedule an item for removal and recreate it
                u = SomeClass(str(items.pop()))
                test_support.gc_collect()      # just in case
                yield u
            finally:
                it = None           # should commit all removals

        test_support.gc_collect()

        with testcontext() as u:
            self.assertNotIn(u, s)
        with testcontext() as u:
            self.assertRaises(KeyError, s.remove, u)
        self.assertNotIn(u, s)
        with testcontext() as u:
            s.add(u)
        self.assertIn(u, s)
        t = s.copy()
        with testcontext() as u:
            s.update(t)
        self.assertEqual(len(s), len(t))
        with testcontext() as u:
            s.clear()
        self.assertEqual(len(s), 0)
开发者ID:Stewori,项目名称:jython,代码行数:35,代码来源:test_weakset.py

示例2: Signal

# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import copy [as 别名]
class Signal(object):
    def __init__(self):
        self._functions = WeakSet()
        self._methods = WeakKeyDictionary()

    def __call__(self, *args, **kargs):
        # Call handler functions
        to_be_removed = []
        for func in self._functions.copy():
            try:
                func(*args, **kargs)
            except RuntimeError:
                Warning.warn('Signals func->RuntimeError: func "{}" will be removed.'.format(func))
                to_be_removed.append(func)

        for remove in to_be_removed:
            self._functions.discard(remove)

        # Call handler methods
        to_be_removed = []
        emitters = self._methods.copy()
        for obj, funcs in emitters.items():
            msg_debug('obj is type "{}"'.format(type(obj)))
            for func in funcs.copy():
                try:
                    func(obj, *args, **kargs)
                except RuntimeError:
                    warnings.warn('Signals methods->RuntimeError, obj.func "{}.{}" will be removed'.format(obj, func))
                    to_be_removed.append((obj, func))

        for obj, func in to_be_removed:
            self._methods[obj].discard(func)

    def connect(self, slot):
        if inspect.ismethod(slot):
            if slot.__self__ not in self._methods:
                self._methods[slot.__self__] = set()

            self._methods[slot.__self__].add(slot.__func__)

        else:
            self._functions.add(slot)

    def disconnect(self, slot):
        if inspect.ismethod(slot):
            if slot.__self__ in self._methods:
                self._methods[slot.__self__].remove(slot.__func__)
        else:
            if slot in self._functions:
                self._functions.remove(slot)

    def clear(self):
        self._functions.clear()
        self._methods.clear()
开发者ID:dhomeier,项目名称:specview,代码行数:56,代码来源:signal_slot.py

示例3: test_weak_destroy_and_mutate_while_iterating

# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import copy [as 别名]
    def test_weak_destroy_and_mutate_while_iterating(self):
        # Issue #7105: iterators shouldn't crash when a key is implicitly removed
        items = [ustr(c) for c in string.ascii_letters]
        s = WeakSet(items)
        @contextlib.contextmanager
        def testcontext():
            try:
                it = iter(s)
                # Start iterator
                yielded = ustr(str(next(it)))
                # Schedule an item for removal and recreate it
                u = ustr(str(items.pop()))
                if yielded == u:
                    # The iterator still has a reference to the removed item,
                    # advance it (issue #20006).
                    next(it)
                gc.collect()      # just in case
                yield u
            finally:
                it = None           # should commit all removals

        with testcontext() as u:
            self.assertNotIn(u, s)
        with testcontext() as u:
            self.assertRaises(KeyError, s.remove, u)
        self.assertNotIn(u, s)
        with testcontext() as u:
            s.add(u)
        self.assertIn(u, s)
        t = s.copy()
        with testcontext() as u:
            s.update(t)
        self.assertEqual(len(s), len(t))
        with testcontext() as u:
            s.clear()
        self.assertEqual(len(s), 0)
开发者ID:0jpq0,项目名称:kbengine,代码行数:38,代码来源:test_weakset.py

示例4: TestWeakSet

# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import copy [as 别名]

#.........这里部分代码省略.........
        class H(WeakSet):
            def __hash__(self):
                return int(id(self) & 0x7fffffff)
        s=H()
        f=set()
        f.add(s)
        self.assertIn(s, f)
        f.remove(s)
        f.add(s)
        f.discard(s)

    def test_init(self):
        s = WeakSet()
        s.__init__(self.items)
        self.assertEqual(s, self.s)
        s.__init__(self.items2)
        self.assertEqual(s, WeakSet(self.items2))
        self.assertRaises(TypeError, s.__init__, s, 2);
        self.assertRaises(TypeError, s.__init__, 1);

    def test_constructor_identity(self):
        s = WeakSet(self.items)
        t = WeakSet(s)
        self.assertNotEqual(id(s), id(t))

    def test_hash(self):
        self.assertRaises(TypeError, hash, self.s)

    def test_clear(self):
        self.s.clear()
        self.assertEqual(self.s, WeakSet([]))
        self.assertEqual(len(self.s), 0)

    def test_copy(self):
        dup = self.s.copy()
        self.assertEqual(self.s, dup)
        self.assertNotEqual(id(self.s), id(dup))

    def test_add(self):
        x = SomeClass('Q')
        self.s.add(x)
        self.assertIn(x, self.s)
        dup = self.s.copy()
        self.s.add(x)
        self.assertEqual(self.s, dup)
        if not test_support.is_jython:  # Jython/JVM can weakly reference list and other objects
            self.assertRaises(TypeError, self.s.add, [])
        self.fs.add(Foo())
        test_support.gc_collect()  # CPython assumes Foo() went out of scope and was collected, so ensure the same
        self.assertEqual(len(list(self.fs)), 1)
        self.fs.add(self.obj)
        self.assertEqual(len(list(self.fs)), 1)

    def test_remove(self):
        x = SomeClass('a')
        self.s.remove(x)
        self.assertNotIn(x, self.s)
        self.assertRaises(KeyError, self.s.remove, x)
        if not test_support.is_jython:  # Jython/JVM can weakly reference list and other objects
            self.assertRaises(TypeError, self.s.remove, [])

    def test_discard(self):
        a, q = SomeClass('a'), SomeClass('Q')
        self.s.discard(a)
        self.assertNotIn(a, self.s)
        self.s.discard(q)
开发者ID:Stewori,项目名称:jython,代码行数:70,代码来源:test_weakset.py

示例5: Block

# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import copy [as 别名]
class Block(object):
    # TODO: let's make blocks that can be more than a single fixed size
    material = Material()
    bindings = []
    direction = 0  # 0-3 for the cardinal directions
    health = 3
    damage = 0
    has_exploded = False

    # sprites
    image = 'basic'
    # TODO: calculate this based on individual block size
    image_anchor = Vec2d(BLOCK_SIZE / 2, BLOCK_SIZE / 2)

    def __init__(self, point):
        self._joints = WeakSet()
        self._adjacent_blocks = WeakSet()
        # load images
        base_path = "images/blocks/{}.png".format(self.image)
        damaged_path = "images/blocks/{}_damaged.png".format(self.image)
        destroyed_path = "images/blocks/{}_destroyed.png".format(self.image)
        self.img = load_image(base_path, self.image_anchor)
        self.img_damaged = load_image(damaged_path, self.image_anchor)
        self.img_destroyed = load_image(destroyed_path, self.image_anchor)

        w = h = BLOCK_SIZE
        # using (density * 1 ** 2) for these because our units are BLOCK_SIZE
        inertia = pymunk.moment_for_box(self.material.density, w, h)
        self._body = pymunk.Body(self.material.density, inertia)
        self._body.position = point
        self._shape = pymunk.Poly.create_box(self._body, (w, h))
        self._shape.elasticity = self.material.elasticity
        self._shape.friction = self.material.friction
        self._shape.collision_type = self.material.collision_type
        self._shape._get_block = ref(self)
        SPACE.add(self._body, self._shape)
        SPACE.register_block(self)

    def weld_to(self, block):
        pj = PivotJoint(self._body, block._body,
                              (self._body.position + block._body.position) / 2)
        gj = GearJoint(self._body, block._body, 0, 1)
        SPACE.add(pj, gj)
        # add weak references to each other
        block._adjacent_blocks.add(self)
        self._adjacent_blocks.add(block)
        # and to the joint
        self._joints.add(pj)
        block._joints.add(pj)
        self._joints.add(gj)
        block._joints.add(gj)

    def draw(self):
        if off_screen(self._body.position):
            return
        if self.damage >= self.health:
            tex = self.img_destroyed.id
        elif self.damage > 0:
            tex = self.img_damaged.id
        else:
            tex = self.img.id
        draw_rect(tex, self._shape.get_vertices(), direction=self.direction)

    def take_physics_damage(self):
        for joint in self._joints.copy():
            self.take_damage(joint.impulse // 250)

    def take_damage(self, amount):
        self.damage += amount
        if self.damage >= self.health and not self.has_exploded:
            # create an explosion
            self.has_exploded = True
            Explosion(self._body.position, BLOCK_SIZE,
                      velocity=self._body.velocity)
            # remove joints
            for block in self._adjacent_blocks:
                toremove = self._joints & block._joints
                for joint in toremove:
                    block._joints.remove(joint)
            SPACE.remove(*self._joints)
            self._joints = WeakSet()
            # remove ties to the construction
            for block in self._adjacent_blocks:
                block._adjacent_blocks.remove(self)
            self._adjacent_blocks = WeakSet()
        elif self.damage >= self.health * 2:
            Explosion(self._body.position, BLOCK_SIZE,
                      velocity=self._body.velocity)
            for i in range(random.randint(1,5)):
                Resource(self)
            SPACE.remove(self._body, self._shape)
            SPACE.blocks.remove(self)
            if self in SPACE.controllable_blocks:
                SPACE.controllable_blocks.remove(self)
            if self in SPACE.controller_blocks:
                SPACE.controller_blocks.remove(self)

    @property
    def construction(self):
        c = WeakSet()
#.........这里部分代码省略.........
开发者ID:mappy13,项目名称:nihil-ace,代码行数:103,代码来源:blocks.py

示例6: HealthMonitor

# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import copy [as 别名]
class HealthMonitor(object):
    """
    Monitors whether a particular host is marked as up or down.
    This class is primarily intended for internal use, although
    applications may find it useful to check whether a given node
    is up or down.
    """

    is_up = True
    """
    A boolean representing the current state of the node.
    """

    def __init__(self, conviction_policy):
        self._conviction_policy = conviction_policy
        self._host = conviction_policy.host
        # self._listeners will hold, among other things, references to
        # Cluster objects.  To allow those to be GC'ed (and shutdown) even
        # though we've implemented __del__, use weak references.
        self._listeners = WeakSet()
        self._lock = RLock()

    def register(self, listener):
        with self._lock:
            self._listeners.add(listener)

    def unregister(self, listener):
        with self._lock:
            self._listeners.remove(listener)

    def set_up(self):
        if self.is_up:
            return

        self._conviction_policy.reset()
        log.info("Host %s is considered up", self._host)

        with self._lock:
            listeners = self._listeners.copy()

        for listener in listeners:
            listener.on_up(self._host)

        self.is_up = True

    def set_down(self):
        if not self.is_up:
            return

        self.is_up = False
        log.info("Host %s is considered down", self._host)

        with self._lock:
            listeners = self._listeners.copy()

        for listener in listeners:
            listener.on_down(self._host)

    def reset(self):
        return self.set_up()

    def signal_connection_failure(self, connection_exc):
        is_down = self._conviction_policy.add_failure(connection_exc)
        if is_down:
            self.set_down()
        return is_down
开发者ID:Kami,项目名称:python-driver,代码行数:68,代码来源:pool.py

示例7: TestWeakSet

# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import copy [as 别名]

#.........这里部分代码省略.........
        class H(WeakSet):
            def __hash__(self):
                return int(id(self) & 0x7fffffff)
        s=H()
        f=set()
        f.add(s)
        self.assertIn(s, f)
        f.remove(s)
        f.add(s)
        f.discard(s)

    def test_init(self):
        s = WeakSet()
        s.__init__(self.items)
        self.assertEqual(s, self.s)
        s.__init__(self.items2)
        self.assertEqual(s, WeakSet(self.items2))
        self.assertRaises(TypeError, s.__init__, s, 2);
        self.assertRaises(TypeError, s.__init__, 1);

    def test_constructor_identity(self):
        s = WeakSet(self.items)
        t = WeakSet(s)
        self.assertNotEqual(id(s), id(t))

    def test_hash(self):
        self.assertRaises(TypeError, hash, self.s)

    def test_clear(self):
        self.s.clear()
        self.assertEqual(self.s, WeakSet([]))
        self.assertEqual(len(self.s), 0)

    def test_copy(self):
        dup = self.s.copy()
        self.assertEqual(self.s, dup)
        self.assertNotEqual(id(self.s), id(dup))

    def test_add(self):
        x = SomeClass('Q')
        self.s.add(x)
        self.assertIn(x, self.s)
        dup = self.s.copy()
        self.s.add(x)
        self.assertEqual(self.s, dup)
        self.assertRaises(TypeError, self.s.add, [])
        self.fs.add(Foo())
        self.assertTrue(len(self.fs) == 1)
        self.fs.add(self.obj)
        self.assertTrue(len(self.fs) == 1)

    def test_remove(self):
        x = SomeClass('a')
        self.s.remove(x)
        self.assertNotIn(x, self.s)
        self.assertRaises(KeyError, self.s.remove, x)
        self.assertRaises(TypeError, self.s.remove, [])

    def test_discard(self):
        a, q = SomeClass('a'), SomeClass('Q')
        self.s.discard(a)
        self.assertNotIn(a, self.s)
        self.s.discard(q)
        self.assertRaises(TypeError, self.s.discard, [])

    def test_pop(self):
开发者ID:89sos98,项目名称:main,代码行数:70,代码来源:test_weakset.py

示例8: TestWeakSet

# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import copy [as 别名]

#.........这里部分代码省略.........
        class H(WeakSet):
            def __hash__(self):
                return int(id(self) & 0x7fffffff)
        s=H()
        f=set()
        f.add(s)
        self.assertIn(s, f)
        f.remove(s)
        f.add(s)
        f.discard(s)

    def test_init(self):
        s = WeakSet()
        s.__init__(self.items)
        self.assertEqual(s, self.s)
        s.__init__(self.items2)
        self.assertEqual(s, WeakSet(self.items2))
        self.assertRaises(TypeError, s.__init__, s, 2);
        self.assertRaises(TypeError, s.__init__, 1);

    def test_constructor_identity(self):
        s = WeakSet(self.items)
        t = WeakSet(s)
        self.assertNotEqual(id(s), id(t))

    def test_hash(self):
        self.assertRaises(TypeError, hash, self.s)

    def test_clear(self):
        self.s.clear()
        self.assertEqual(self.s, WeakSet([]))
        self.assertEqual(len(self.s), 0)

    def test_copy(self):
        dup = self.s.copy()
        self.assertEqual(self.s, dup)
        self.assertNotEqual(id(self.s), id(dup))

    def test_add(self):
        x = ustr('Q')
        self.s.add(x)
        self.assertIn(x, self.s)
        dup = self.s.copy()
        self.s.add(x)
        self.assertEqual(self.s, dup)
        self.assertRaises(TypeError, self.s.add, [])
        self.fs.add(Foo())
        support.gc_collect()
        self.assertTrue(len(self.fs) == 1)
        self.fs.add(self.obj)
        self.assertTrue(len(self.fs) == 1)

    def test_remove(self):
        x = ustr('a')
        self.s.remove(x)
        self.assertNotIn(x, self.s)
        self.assertRaises(KeyError, self.s.remove, x)
        self.assertRaises(TypeError, self.s.remove, [])

    def test_discard(self):
        a, q = ustr('a'), ustr('Q')
        self.s.discard(a)
        self.assertNotIn(a, self.s)
        self.s.discard(q)
        self.assertRaises(TypeError, self.s.discard, [])
开发者ID:timm,项目名称:timmnix,代码行数:69,代码来源:test_weakset.py


注:本文中的weakref.WeakSet.copy方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。