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


Python delattr函数代码示例

本文整理汇总了Python中delattr函数的典型用法代码示例。如果您正苦于以下问题:Python delattr函数的具体用法?Python delattr怎么用?Python delattr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: test_check_for_setup_error

    def test_check_for_setup_error(self):
        mox = self.mox
        drv = self._driver
        drv._client = api.NaServer("127.0.0.1")
        drv._client.set_api_version(1, 9)
        required_flags = [
            'netapp_transport_type',
            'netapp_login',
            'netapp_password',
            'netapp_server_hostname',
            'netapp_server_port']

        # set required flags
        for flag in required_flags:
            setattr(drv.configuration, flag, None)
        # check exception raises when flags are not set
        self.assertRaises(exception.CinderException,
                          drv.check_for_setup_error)

        # set required flags
        for flag in required_flags:
            setattr(drv.configuration, flag, 'val')

        mox.ReplayAll()

        drv.check_for_setup_error()

        mox.VerifyAll()

        # restore initial FLAGS
        for flag in required_flags:
            delattr(drv.configuration, flag)
开发者ID:adelina-t,项目名称:cinder,代码行数:32,代码来源:test_netapp_nfs.py

示例2: disconnect_handlers

	def disconnect_handlers(self, obj):
		HANDLER_IDS = self.HANDLER_IDS
		if hasattr(obj, HANDLER_IDS):
			for l_id in getattr(obj, HANDLER_IDS):
				obj.disconnect(l_id)

			delattr(obj, HANDLER_IDS)
开发者ID:parmarmanor,项目名称:gedit-control-your-tabs,代码行数:7,代码来源:controlyourtabs.py

示例3: patch

def patch(namespace, **values):
    """Patches `namespace`.`name` with `value` for (name, value) in values"""

    originals = {}

    if isinstance(namespace, LazyObject):
        if namespace._wrapped is None:
            namespace._setup()
        namespace = namespace._wrapped

    for (name, value) in values.iteritems():
        try:
            originals[name] = getattr(namespace, name)
        except AttributeError:
            originals[name] = NotImplemented
        if value is NotImplemented:
            if originals[name] is not NotImplemented:
                delattr(namespace, name)
        else:
            setattr(namespace, name, value)

    try:
        yield
    finally:
        for (name, original_value) in originals.iteritems():
            if original_value is NotImplemented:
                if values[name] is not NotImplemented:
                    delattr(namespace, name)
            else:
                setattr(namespace, name, original_value)
开发者ID:Apartments24-7,项目名称:django-bcrypt,代码行数:30,代码来源:tests.py

示例4: test_get_available_capacity_with_df

    def test_get_available_capacity_with_df(self):
        """_get_available_capacity should calculate correct value."""
        mox = self._mox
        drv = self._driver

        df_avail = 1490560
        df_head = "Filesystem 1K-blocks Used Available Use% Mounted on\n"
        df_data = "glusterfs-host:/export 2620544 996864 %d 41%% /mnt" % df_avail
        df_output = df_head + df_data

        setattr(glusterfs.FLAGS, "glusterfs_disk_util", "df")

        mox.StubOutWithMock(drv, "_get_mount_point_for_share")
        drv._get_mount_point_for_share(self.TEST_EXPORT1).AndReturn(self.TEST_MNT_POINT)

        mox.StubOutWithMock(drv, "_execute")
        drv._execute("df", "--portability", "--block-size", "1", self.TEST_MNT_POINT, run_as_root=True).AndReturn(
            (df_output, None)
        )

        mox.ReplayAll()

        self.assertEquals(df_avail, drv._get_available_capacity(self.TEST_EXPORT1))

        mox.VerifyAll()

        delattr(glusterfs.FLAGS, "glusterfs_disk_util")
开发者ID:citrix-openstack,项目名称:cinder,代码行数:27,代码来源:test_glusterfs.py

示例5: __init__

    def __init__(self, *pos, **kw):
        _orig_socket.__init__(self, *pos, **kw)

        self._savedmethods = dict()
        for name in self._savenames:
            self._savedmethods[name] = getattr(self, name)
            delattr(self, name)  # Allows normal overriding mechanism to work
开发者ID:TinySong,项目名称:dotFiles,代码行数:7,代码来源:socks.py

示例6: remove_item

def remove_item(module, attr):
    NONE = object()
    olditem = getattr(module, attr, NONE)
    if olditem is NONE:
        return
    saved.setdefault(module.__name__, {}).setdefault(attr, olditem)
    delattr(module, attr)
开发者ID:easel,项目名称:gevent,代码行数:7,代码来源:monkey.py

示例7: select_group

    def select_group (self, group):
        if self.__group == group:
            return

        if group:
            groups = [ group ] + [ g for g in self.groups if g != group ]
        else:
            groups = self.groups

        # clear dict and only keep some values we want unchanged
        if not self.__base_dict:
            self.__base_dict = self.__dict__.copy()
        else:
            self.__dict__ = self.__base_dict.copy()

        # updating
        for group_ in groups:
            group_.select_group(None)
            if group_.handlers:
                merge(self.handlers, group_.handlers)
            self.__inherits(self.__dict__, group_.__dict__)

        # some value that we must reset to their original state
        for key in ('synctrex', 'group', 'groups', 'children'):
            if key in self.__base_dict:
                setattr(self, key, self.__base_dict[key])
            elif hasattr(self, key):
                delattr(self, key)

        self.__group = group
开发者ID:bkfox,项目名称:synctrex,代码行数:30,代码来源:objects.py

示例8: make_collation_func

def make_collation_func(name, locale, numeric=True, template='_sort_key_template', func='strcmp'):
    c = icu._icu.Collator(locale)
    cname = '%s_test_collator%s' % (name, template)
    setattr(icu, cname, c)
    c.numeric = numeric
    yield icu._make_func(getattr(icu, template), name, collator=cname, collator_func='not_used_xxx', func=func)
    delattr(icu, cname)
开发者ID:MarioJC,项目名称:calibre,代码行数:7,代码来源:icu_test.py

示例9: main

def main(aeta_url, testname_prefix='', email=None, passin=False,
         save_auth=True):
  """Main function invoked if module is run from commandline.

  Args:
    aeta_url: URL where an aeta instance is available.
    testname_prefix: Optional name prefix for tests to be created.
    email: The email address to use for authentication, or None for the user to
        enter it when necessary.
    passin: Whether to read the password from stdin rather than echo-free
        input.
    save_auth: Whether to store authentication cookies in a file.
  """
  try:
    start_time = time.time()
    this_module = inspect.getmodule(main)
    testcases = create_test_cases(aeta_url, unittest.TestCase, testname_prefix,
                                  email=email, passin=passin,
                                  save_auth=save_auth)
    add_test_cases_to_module(testcases, this_module)
    suite = unittest.TestLoader().loadTestsFromModule(this_module)
    if not suite.countTestCases():
      error_msg = 'No tests '
      if testname_prefix:
        error_msg += 'with the prefix "%s" ' % testname_prefix
      error_msg += 'found at "%s"' % aeta_url
      print >> sys.stderr, error_msg
      sys.exit(1)
    _print_test_output(start_time, suite)
    for testcase in testcases:
      delattr(this_module, testcase.__name__)
  except AuthError, e:
    print >> sys.stderr, str(e)
开发者ID:patrickyoung,项目名称:limewasp,代码行数:33,代码来源:local_client.py

示例10: afterRetrieveModifier

 def afterRetrieveModifier(self, obj, repo_clone, preserve=()):
     """If we find any LargeFilePlaceHolders, replace them with the
     values from the current working copy.  If the values are missing
     from the working copy, remove them from the retrieved object."""
     # Search for fields stored via AnnotationStorage
     annotations = getattr(obj, '__annotations__', None)
     orig_annotations = getattr(repo_clone, '__annotations__', None)
     for storage, name, orig_val in self._getFieldValues(repo_clone):
         if isinstance(orig_val, LargeFilePlaceHolder):
             if storage == 'annotation':
                 val = _empty_marker
                 if annotations is not None:
                     val = annotations.get(name, _empty_marker)
                 if val is not _empty_marker:
                     orig_annotations[name] = val
                 else:
                     # remove the annotation if not present on the
                     # working copy, or if annotations are missing
                     # entirely
                     del orig_annotations[name]
             else: # attribute storage
                 val = getattr(obj, name, _empty_marker)
                 if val is not _empty_marker:
                     setattr(repo_clone, name, val)
                 else:
                     delattr(repo_clone, name)
     return [], [], {}
开发者ID:nacho22martin,项目名称:tesis,代码行数:27,代码来源:StandardModifiers.py

示例11: rewrite_for_all_browsers

def rewrite_for_all_browsers(test_class, browser_list, times=1, retry_count=1):
    """
        Magically make test methods for all desired browsers. Note that this method cannot contain
        the word 'test' or nose will decide it is worth running.
    """
    for name in [n for n in dir(test_class) if n.startswith('test_')]:
        test_method = getattr(test_class, name)
        for count in range(1, times + 1):
            for browser in browser_list:
                new_name = "{name}_{browser}".format(name=name, browser=browser.safe_name())
                if times > 1:
                    new_name += "-{}".format(count)
                if retry_count <= 1:
                    new_function = lambda instance, browser_to_use=browser: test_method(instance, browser_to_use)
                else:
                    def auto_retry(instance, test_method, browser_to_use):
                        failure_type, failure_value, failure_traceback = None, None, None
                        for _ in xrange(retry_count):
                            if failure_type:
                                sys.stderr.write("ignoring failure {} for {}\n".format(failure_type, test_method))
                            try:
                                test_method(instance, browser_to_use)
                                return # test success means we return doing nothing
                            except:
                                failure_type, failure_value, failure_traceback = sys.exc_info()
                                instance.tearDown()
                                instance.setUp()
                                pass
                        # reaching here means repeated failure, so let's raise the last failure
                        raise failure_type, failure_value, failure_traceback
                    new_function = lambda instance, browser_to_use=browser: auto_retry(instance, test_method, browser_to_use)

                new_function.__name__ = new_name
                setattr(test_class, new_name, new_function)
        delattr(test_class, name)
开发者ID:cdvillard,项目名称:chime,代码行数:35,代码来源:chime_test_case.py

示例12: test_mixin_field_access

def test_mixin_field_access():
    field_data = DictFieldData({
        'field_a': 5,
        'field_x': [1, 2, 3],
    })
    runtime = TestRuntime(Mock(), mixins=[TestSimpleMixin], services={'field-data': field_data})

    field_tester = runtime.construct_xblock_from_class(FieldTester, Mock())

    assert_equals(5, field_tester.field_a)
    assert_equals(10, field_tester.field_b)
    assert_equals(42, field_tester.field_c)
    assert_equals([1, 2, 3], field_tester.field_x)
    assert_equals('default_value', field_tester.field_y)

    field_tester.field_x = ['a', 'b']
    field_tester.save()
    assert_equals(['a', 'b'], field_tester._field_data.get(field_tester, 'field_x'))

    del field_tester.field_x
    assert_equals([], field_tester.field_x)
    assert_equals([1, 2, 3], field_tester.field_x_with_default)

    with assert_raises(AttributeError):
        getattr(field_tester, 'field_z')
    with assert_raises(AttributeError):
        delattr(field_tester, 'field_z')

    field_tester.field_z = 'foo'
    assert_equals('foo', field_tester.field_z)
    assert_false(field_tester._field_data.has(field_tester, 'field_z'))
开发者ID:Maqlan,项目名称:XBlock,代码行数:31,代码来源:test_runtime.py

示例13: _clear_setup

    def _clear_setup(self):
        if os.path.exists(CONF.working_directory):
            os.chmod(CONF.working_directory, PERM_ALL)
            shutil.rmtree(CONF.working_directory)

        if hasattr(mock.DummySMTP, 'exception'):
            delattr(mock.DummySMTP, 'exception')
开发者ID:ColdrickSotK,项目名称:storyboard,代码行数:7,代码来源:test_base.py

示例14: __init__

    def __init__( self
                , id
                , title=''
                , file=''
                , content_type=''
                , precondition=''
                , subject=()
                , description=''
                , contributors=()
                , effective_date=None
                , expiration_date=None
                , format=None
                , language='en-US'
                , rights=''
                ):
        OFS.Image.File.__init__( self, id, title, file
                               , content_type, precondition )
        self._setId(id)
        delattr(self, '__name__')

        # If no file format has been passed in, rely on what OFS.Image.File
        # detected.
        if format is None:
            format = self.content_type

        DefaultDublinCoreImpl.__init__( self, title, subject, description
                               , contributors, effective_date, expiration_date
                               , format, language, rights )
开发者ID:goschtl,项目名称:zope,代码行数:28,代码来源:Image.py

示例15: undefine

 def undefine(self, f):
     if isinstance(f, basestring):
         name = f
     else:
         name = f.__name__
     del self._impls[name]
     delattr(self, name)
开发者ID:AiTeamUSTC,项目名称:GPE,代码行数:7,代码来源:base.py


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