nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: ipython/traitlets
Pull request #238 (2016-06-02 12:45:20)

add keys to bunch.__dir__
so they are exposed to attribute completions


Patch:
diff --git a/traitlets/utils/bunch.py b/traitlets/utils/bunch.py
index a47564e..2edb830 100644
--- a/traitlets/utils/bunch.py
+++ b/traitlets/utils/bunch.py
@@ -16,3 +16,10 @@ class Bunch(dict):
     
     def __setattr__(self, key, value):
         self.__setitem__(key, value)
+    
+    def __dir__(self):
+        # py2-compat: can't use super because dict doesn't have __dir__
+        names = dir({})
+        names.extend(self.keys())
+        return names
+


Test patch:
diff --git a/traitlets/utils/tests/test_bunch.py b/traitlets/utils/tests/test_bunch.py
index ccca543..ef5c3c1 100644
--- a/traitlets/utils/tests/test_bunch.py
+++ b/traitlets/utils/tests/test_bunch.py
@@ -7,3 +7,8 @@ def test_bunch():
     assert b.x == 5
     b['a'] = 'hi'
     assert b.a == 'hi'
+
+def test_bunch_dir():
+    b = Bunch(x=5, y=10)
+    assert 'x' in dir(b)
+    assert 'keys' in dir(b)
Repository: ipython/traitlets
Pull request #339 (2016-10-25 14:15:25)

nicer repr of LazyConfigValues
include contents of the config value


Patch:
diff --git a/traitlets/config/loader.py b/traitlets/config/loader.py
index 20076c2..21dbed1 100644
--- a/traitlets/config/loader.py
+++ b/traitlets/config/loader.py
@@ -146,6 +146,12 @@ class LazyConfigValue(HasTraits):
             d['inserts'] = self._inserts
         return d
 
+    def __repr__(self):
+        if self._value is not None:
+            return "<%s value=%r>" % (self.__class__.__name__, self._value)
+        else:
+            return "<%s %r>" % (self.__class__.__name__, self.to_dict())
+
 
 def _is_section_key(key):
     """Is a Config key a section name (does it start with a capital)?"""


Test patch:
diff --git a/traitlets/config/tests/test_loader.py b/traitlets/config/tests/test_loader.py
index 0fca256..bfca88f 100644
--- a/traitlets/config/tests/test_loader.py
+++ b/traitlets/config/tests/test_loader.py
@@ -483,6 +483,20 @@ class TestConfig(TestCase):
             _ = cfg._repr_html_
         self.assertNotIn('_repr_html_', cfg)
         self.assertEqual(len(cfg), 0)
+    
+    def test_lazy_config_repr(self):
+        cfg = Config()
+        cfg.Class.lazy.append(1)
+        cfg_repr = repr(cfg)
+        assert '<LazyConfigValue' in cfg_repr
+        assert "extend" in cfg_repr
+        assert " [1]}>" in cfg_repr
+        assert 'value=' not in cfg_repr
+        cfg.Class.lazy.get_value([0])
+        repr2 = repr(cfg)
+        assert repr([0,1]) in repr2
+        assert 'value=' in repr2
+        
 
     def test_getitem_not_section(self):
         cfg = Config()
Repository: ipython/traitlets
Pull request #356 (2017-01-03 14:07:17)

Allow "cls" and "self" as keyword argument in __new__
The way how `HasTraits.__new__` is currently written, it does not allow `cls` or `self` as keyword argument. This might be a purely "academic" issue (I did not encounter it in the wild), but better fix it anyway.


Patch:
diff --git a/traitlets/traitlets.py b/traitlets/traitlets.py
index 2c0fc4f..fa25064 100644
--- a/traitlets/traitlets.py
+++ b/traitlets/traitlets.py
@@ -944,7 +944,11 @@ class HasDescriptors(six.with_metaclass(MetaHasDescriptors, object)):
     """The base class for all classes that have descriptors.
     """
 
-    def __new__(cls, *args, **kwargs):
+    def __new__(*args, **kwargs):
+        # Pass cls as args[0] to allow "cls" as keyword argument
+        cls = args[0]
+        args = args[1:]
+
         # This is needed because object.__new__ only accepts
         # the cls argument.
         new_meth = super(HasDescriptors, cls).__new__
@@ -955,10 +959,14 @@ class HasDescriptors(six.with_metaclass(MetaHasDescriptors, object)):
         inst.setup_instance(*args, **kwargs)
         return inst
 
-    def setup_instance(self, *args, **kwargs):
+    def setup_instance(*args, **kwargs):
         """
         This is called **before** self.__init__ is called.
         """
+        # Pass self as args[0] to allow "self" as keyword argument
+        self = args[0]
+        args = args[1:]
+
         self._cross_validation_lock = False
         cls = self.__class__
         for key in dir(cls):
@@ -976,7 +984,11 @@ class HasDescriptors(six.with_metaclass(MetaHasDescriptors, object)):
 
 class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
 
-    def setup_instance(self, *args, **kwargs):
+    def setup_instance(*args, **kwargs):
+        # Pass self as args[0] to allow "self" as keyword argument
+        self = args[0]
+        args = args[1:]
+
         self._trait_values = {}
         self._trait_notifiers = {}
         self._trait_validators = {}


Test patch:
diff --git a/traitlets/tests/test_traitlets.py b/traitlets/tests/test_traitlets.py
index 953b35a..bdbbc97 100644
--- a/traitlets/tests/test_traitlets.py
+++ b/traitlets/tests/test_traitlets.py
@@ -2486,3 +2486,11 @@ def test_super_bad_args():
         obj = SuperHasTraits(a=1, b=2)
     assert obj.a ==  1 
     assert not hasattr(obj, 'b')
+
+
+def test_cls_self_argument():
+    class X(HasTraits):
+        def __init__(__self, cls, self):
+            pass
+
+    x = X(cls=None, self=None)
Repository: ipython/traitlets
Pull request #376 (2017-02-17 10:35:08)

Bless config metadata in trait constructors
After updating many applications to the 4.1 API, requiring `.tag(config=True)` does not seem to be an improvement, plus the definition of the config metadata is defined in this package.

Blessing the longstanding behavior makes upgrading a lot less tedious.


Patch:
diff --git a/traitlets/traitlets.py b/traitlets/traitlets.py
index 4e2e4d8..3c3bf63 100644
--- a/traitlets/traitlets.py
+++ b/traitlets/traitlets.py
@@ -432,7 +432,8 @@ class TraitType(BaseDescriptor):
                     "use @default decorator instead.")
             cls._trait_default_generators[self.name] = method
 
-    def __init__(self, default_value=Undefined, allow_none=False, read_only=None, help=None, **kwargs):
+    def __init__(self, default_value=Undefined, allow_none=False, read_only=None, help=None,
+        config=None, **kwargs):
         """Declare a traitlet.
 
         If *allow_none* is True, None is a valid value in addition to any
@@ -472,6 +473,8 @@ class TraitType(BaseDescriptor):
                 self.metadata = kwargs
         else:
             self.metadata = self.metadata.copy()
+        if config is not None:
+            self.metadata['config'] = config
 
         # We add help to the metadata during a deprecation period so that
         # code that looks for the help string there can find it.


Test patch:
diff --git a/traitlets/config/tests/test_configurable.py b/traitlets/config/tests/test_configurable.py
index 8a95ca3..93a44e7 100644
--- a/traitlets/config/tests/test_configurable.py
+++ b/traitlets/config/tests/test_configurable.py
@@ -439,7 +439,7 @@ class TestConfigContainers(TestCase):
 
         # reset deprecation limiter
         _deprecations_shown.clear()
-        with expected_warnings(['metadata should be set using the \.tag\(\) method', "use @default decorator instead\\."]):
+        with expected_warnings(["use @default decorator instead\\."]):
             class DefaultConfigurable(Configurable):
                 a = Integer(config=True)
                 def _config_default(self):
Repository: ipython/traitlets
Pull request #377 (2017-02-17 10:46:16)

undeprecate `_trait_default`
After upgrading several applications to the 4.1 API, requiring the default decorator results in a bunch of redundant code.

Since the signature and behavior are unchanged, just remove the deprecation message on default-value generators.

I won't propose undeprecating change/validate methods, since their signatures change with the decorators.

SylvainCorlay: This makes sense for defaults.

Although I like using the `@default` decorator in a class where I have calls to `@validate` and `observe` which make the whole thing more uniform... 


Patch:
diff --git a/docs/source/migration.rst b/docs/source/migration.rst
index c88cd9d..59f7026 100644
--- a/docs/source/migration.rst
+++ b/docs/source/migration.rst
@@ -118,11 +118,12 @@ by notification type.
         def handler_all(self, change):
             pass
 
-Deprecation of magic method for dynamic defaults generation
------------------------------------------------------------
+dynamic defaults generation with decorators
+-------------------------------------------
 
 The use of the magic methods ``_{trait}_default`` for dynamic default
-generation is deprecated, in favor a new ``@default`` method decorator.
+generation is not deprecated, but a new ``@default`` method decorator
+is added.
 
 **Example:**
 
diff --git a/traitlets/traitlets.py b/traitlets/traitlets.py
index 3c3bf63..b6abacf 100644
--- a/traitlets/traitlets.py
+++ b/traitlets/traitlets.py
@@ -427,9 +427,6 @@ class TraitType(BaseDescriptor):
     def subclass_init(self, cls):
         if '_%s_default' % self.name in cls.__dict__:
             method = getattr(cls, '_%s_default' % self.name)
-            if not isinstance(method, EventHandler):
-                _deprecated_method(method, cls, '_%s_default' % self.name,
-                    "use @default decorator instead.")
             cls._trait_default_generators[self.name] = method
 
     def __init__(self, default_value=Undefined, allow_none=False, read_only=None, help=None,


Test patch:
diff --git a/traitlets/config/tests/test_configurable.py b/traitlets/config/tests/test_configurable.py
index 93a44e7..b3ccae1 100644
--- a/traitlets/config/tests/test_configurable.py
+++ b/traitlets/config/tests/test_configurable.py
@@ -439,7 +439,7 @@ class TestConfigContainers(TestCase):
 
         # reset deprecation limiter
         _deprecations_shown.clear()
-        with expected_warnings(["use @default decorator instead\\."]):
+        with expected_warnings([]):
             class DefaultConfigurable(Configurable):
                 a = Integer(config=True)
                 def _config_default(self):
diff --git a/traitlets/tests/test_traitlets.py b/traitlets/tests/test_traitlets.py
index bdbbc97..b3efaa2 100644
--- a/traitlets/tests/test_traitlets.py
+++ b/traitlets/tests/test_traitlets.py
@@ -161,7 +161,7 @@ class TestTraitType(TestCase):
 
         assert obj.x == 5
 
-        with expected_warnings(['@default', '@validate', '@observe']) as w:
+        with expected_warnings(['@validate', '@observe']) as w:
             class ShouldWarn(HasTraits):
                 x = Integer()
Repository: ipython/traitlets
Pull request #392 (2017-04-13 11:57:55)

style(cfg): apply review items in #385 for gen-config
Minor changes in the formatting of the generated sample configuration-file,
as reviewed by @ankostis on #385.

The differences in the generated config-file are shown below for this code:

```python
import traitlets.config as trtc
import traitlets as trt

class C(trtc.Configurable):
    a = trt.Enum(['aa', 'BB'], help='1st help line.\n\nOther lines.').tag(config=True)

class A(trtc.Application, C):
    pass

print(A().generate_config_file())
```

## Wihtout this PR:
```python
#------------------------------------------------------------------------------
# A(Application, C) configuration
#------------------------------------------------------------------------------
## This is an application.

## 1st help line.
#  See also C.a
# c.A.a = traitlets.Undefined
```

## WITH this PR:
```python
THIS PR:
##------------------------------------------------------------------------------
## A(Application, C) configuration
##------------------------------------------------------------------------------
## This is an application.

## 1st help line.
#  See also: C.a
#c.A.a = traitlets.Undefined
```


Patch:
diff --git a/traitlets/config/configurable.py b/traitlets/config/configurable.py
index 71072fd..b677977 100644
--- a/traitlets/config/configurable.py
+++ b/traitlets/config/configurable.py
@@ -365,7 +365,7 @@ class Configurable(HasTraits):
                 # Truncate help to first line + "See also Original.trait"
                 if trait.help:
                     lines.append(c(trait.help.split('\n', 1)[0]))
-                lines.append('#  See also %s.%s' % (defining_class.__name__, name))
+                lines.append('#  See also: %s.%s' % (defining_class.__name__, name))
 
             lines.append('# c.%s.%s = %s' % (cls.__name__, name, default_repr))
             lines.append('')


Test patch:
diff --git a/traitlets/config/tests/test_application.py b/traitlets/config/tests/test_application.py
index 87cb845..23a0f46 100644
--- a/traitlets/config/tests/test_application.py
+++ b/traitlets/config/tests/test_application.py
@@ -438,13 +438,13 @@ class TestApplication(TestCase):
         self.assertIn('# c.NoTraits.i', conf_txt)
         self.assertIn('# c.NoTraits.j', conf_txt)
         self.assertIn('# c.NoTraits.n', conf_txt)
-        self.assertIn('#  See also Foo.j', conf_txt)
-        self.assertIn('#  See also Bar.b', conf_txt)
+        self.assertIn('#  See also: Foo.j', conf_txt)
+        self.assertIn('#  See also: Bar.b', conf_txt)
         self.assertEqual(conf_txt.count('Details about i.'), 1)
 
         # inherited traits, parent not in class list:
         self.assertIn("# c.NoTraits.from_hidden", conf_txt)
-        self.assertNotIn('#  See also NotInConfig.', conf_txt)
+        self.assertNotIn('#  See also: NotInConfig.', conf_txt)
         self.assertEqual(conf_txt.count('Details about from_hidden.'), 1)
         self.assertNotIn("NotInConfig", conf_txt)
Repository: ipython/traitlets
Pull request #413 (2017-06-05 02:48:17)

Has Trait Value Method
A method to check whether a trait has a value yet (not including its default). This is related to a part of ipywidget's sliders which have circular validation dependencies between their `min`, `max` and `value` traits. Solving this problem requires something akin to `hasattr` which does not currently exist. This PR changes that by adding a `has_trait_value` method.

Associated ipywidgets issue: https://github.com/jupyter-widgets/ipywidgets/pull/1409

cc: @minrk, @ellisonbg, @jasongrout - see the above issue to determine how breaking this change to traitlets' validation will be to the rest of the jupyter stack - there may have been other places that exploited this lack of validation for default values.



ellisonbg: Can you add some tests, so we can see/verify how this works?
rmorshea: @ellisonbg, of course, `has_trait_value` is pretty simple though, it just returns `name in self._trait_values` since that is both a check of whether `name` is a trait, and whether that trait has a value.

Patch:
diff --git a/traitlets/traitlets.py b/traitlets/traitlets.py
index 535592c..c39605e 100644
--- a/traitlets/traitlets.py
+++ b/traitlets/traitlets.py
@@ -1438,6 +1438,27 @@ class HasTraits(six.with_metaclass(MetaHasTraits, HasDescriptors)):
         """Returns True if the object has a trait with the specified name."""
         return isinstance(getattr(self.__class__, name, None), TraitType)
 
+    def trait_has_value(self, name):
+        """Returns True if the specified trait has a value.
+
+        This will return false even if ``getattr`` would return a
+        dynamically generated default value. These default values
+        will be recognized as existing only after they have been
+        generated.
+
+        Example
+
+        .. code-block:: python
+            class MyClass(HasTraits):
+                i = Int()
+
+            mc = MyClass()
+            assert not mc.trait_has_value("i")
+            mc.i # generates a default value
+            assert mc.trait_has_value("i")
+        """
+        return name in self._trait_values
+
     def trait_values(self, **metadata):
         """A ``dict`` of trait names and their values.
 


Test patch:
diff --git a/traitlets/tests/test_traitlets.py b/traitlets/tests/test_traitlets.py
index 3a81e88..a8dac03 100644
--- a/traitlets/tests/test_traitlets.py
+++ b/traitlets/tests/test_traitlets.py
@@ -765,6 +765,18 @@ class TestHasTraits(TestCase):
         self.assertTrue(a.has_trait('f'))
         self.assertFalse(a.has_trait('g'))
 
+    def test_trait_has_value(self):
+        class A(HasTraits):
+            i = Int()
+            f = Float()
+        a = A()
+        self.assertFalse(a.trait_has_value('f'))
+        self.assertFalse(a.trait_has_value('g'))
+        a.i = 1
+        a.f
+        self.assertTrue(a.trait_has_value('i'))
+        self.assertTrue(a.trait_has_value('f'))
+
     def test_trait_metadata_deprecated(self):
         with expected_warnings(['metadata should be set using the \.tag\(\) method']):
             class A(HasTraits):
Repository: ipython/traitlets
Pull request #430 (2017-07-22 15:47:54)

Fix parsing of deprecated list options failing with empty strings
When a list trait is aliased, and a single empty-string is given in command-line, like this:
```
foo -=seq-option=""
```
The `traitlets.config.loader` fails when attempting to parse it as `[deprecated, list, format]`, with this error:
```
  File "/home/user/traitlets/config/application.py", line 702, in parse_command_line
    self.cli_config = deepcopy(loader.load_config())
  File "/home/user/traitlets/config/loader.py", line 804, in load_config
    self._convert_to_config()
  File "/home/user/traitlets/config/loader.py", line 947, in _convert_to_config
    self._exec_config_str(k, v, trait=trait)
  File "/home/user/traitlets/config/loader.py", line 542, in _exec_config_str
    (r[0] == '[' and r[-1] == ']') or
IndexError: string index out of range
```

- The fix consists of skipping deprecated-list parsing on zero-length strings.
- A TC is included proving the problem is fixed.


Patch:
diff --git a/traitlets/config/loader.py b/traitlets/config/loader.py
index 2734524..dc637bb 100644
--- a/traitlets/config/loader.py
+++ b/traitlets/config/loader.py
@@ -543,7 +543,7 @@ class CommandLineConfigLoader(ConfigLoader):
 
         elif isinstance(rhs, (list, tuple)):
             value = None
-            if len(rhs) == 1:
+            if len(rhs) == 1 and len(rhs[0]) > 0:
                 # check for deprecated --Class.trait="['a', 'b', 'c']"
                 r = rhs[0]
                 if (


Test patch:
diff --git a/traitlets/config/tests/test_loader.py b/traitlets/config/tests/test_loader.py
index bfbce5c..3fc0fb3 100644
--- a/traitlets/config/tests/test_loader.py
+++ b/traitlets/config/tests/test_loader.py
@@ -345,6 +345,13 @@ class TestArgParseKVCL(TestKeyValueCL):
         self.assertEqual(config.CSub.d, [1, 'BBB'])
         self.assertEqual(config.CSub.e, [1, 'a', 'bcd'])
 
+    def test_seq_traits_single_empty_string(self):
+        cl = self.klass(log=log, classes=(CBase, ))
+        aliases = {'seqopt': 'CBase.c'}
+        argv = ['--seqopt', '']
+        config = cl.load_config(argv, aliases=aliases)
+        self.assertEqual(config.CBase.c, [''])
+
     def test_dict_traits(self):
         cl = self.klass(log=log, classes=(CBase, CSub))
         aliases = {'D': 'CBase.adict', 'E': 'CSub.bdict'}
Repository: ipython/traitlets
Pull request #525 (2019-06-22 03:12:45)

Fix backward compatibility and tests
Hello,

I'd like to propose some fixes.
Hope you find them useful.

Thanks!


Patch:
diff --git a/.travis.yml b/.travis.yml
index d7c928f..7fe677f 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -11,6 +11,7 @@ install:
   - pip install .
   - pip install --pre --upgrade traitlets[test] pytest pytest-cov codecov
   - test -z ${TEST_DEPS} || pip install --upgrade ${TEST_DEPS}
+  - pip freeze
 
 script:
   - ${TEST:-py.test --cov traitlets -v traitlets}
@@ -26,7 +27,7 @@ matrix:
         - TEST=iptest
     - python: 3.6
       env:
-        - TEST_DEPS=nbconvert[test]
+        - TEST_DEPS=git+https://github.com/jupyter/nbconvert.git#egg=nbconvert[test]
         - TEST="py.test --pyargs nbconvert"
     - python: 3.6
       env:
diff --git a/traitlets/traitlets.py b/traitlets/traitlets.py
index 8b56942..efb45d5 100644
--- a/traitlets/traitlets.py
+++ b/traitlets/traitlets.py
@@ -521,9 +521,13 @@ class TraitType(BaseDescriptor):
             # Check for a dynamic initializer.
             default = obj.trait_defaults(self.name)
             if default is Undefined:
-                raise TraitError("No default value found for "
-                    "the '%s' trait named '%s' of %r" % (
-                    type(self).__name__, self.name, obj))
+                warn(
+                    "Explicit using of Undefined as the default value "
+                    "is deprecated in traitlets 4.4, and may cause "
+                    "exceptions in the future",
+                    DeprecationWarning,
+                    stacklevel=2
+                )
             with obj.cross_validation_lock:
                 value = self._validate(obj, default)
             obj._trait_values[self.name] = value


Test patch:
diff --git a/traitlets/tests/test_traitlets.py b/traitlets/tests/test_traitlets.py
index acb8a63..e2efe30 100644
--- a/traitlets/tests/test_traitlets.py
+++ b/traitlets/tests/test_traitlets.py
@@ -56,8 +56,7 @@ class TestTraitType(TestCase):
         class A(HasTraits):
             a = TraitType
         a = A()
-        with self.assertRaises(TraitError):
-            a.a
+        assert a.a is Undefined
 
     def test_set(self):
         class A(HasTraitsStub):
Repository: ipython/traitlets
Pull request #611 (2020-09-02 18:28:19)

update cast_unicode to use Python 3 decode method
Fixes ipython/ipykernel#543.

`traitlets.utils` was still pointing at an old `decode` function from `ipython_genutils`. Here, I'm updating it to use Python 3's sting decode method.


Patch:
diff --git a/traitlets/utils/__init__.py b/traitlets/utils/__init__.py
index a7b24e9..aeca2bb 100644
--- a/traitlets/utils/__init__.py
+++ b/traitlets/utils/__init__.py
@@ -1,6 +1,6 @@
 
 # vestigal things from IPython_genutils.
-def cast_unicode(s, encoding=None):
+def cast_unicode(s, encoding='utf-8'):
     if isinstance(s, bytes):
-        return decode(s, encoding)
+        return s.decode(encoding, 'replace')
     return s


Test patch:
diff --git a/traitlets/tests/test_traitlets.py b/traitlets/tests/test_traitlets.py
index ff064c2..af4599c 100644
--- a/traitlets/tests/test_traitlets.py
+++ b/traitlets/tests/test_traitlets.py
@@ -61,6 +61,8 @@ from traitlets import (
     HasDescriptors,
     CUnicode,
 )
+from traitlets.utils import cast_unicode
+
 
 def change_dict(*ordered_values):
     change_names = ('name', 'old', 'new', 'owner', 'type')
@@ -1462,16 +1464,20 @@ class UnicodeTrait(HasTraits):
 
     value = Unicode('unicode')
 
+
 class TestUnicode(TraitTestBase):
 
     obj = UnicodeTrait()
 
     _default_value = 'unicode'
     _good_values   = ['10', '-10', '10L', '-10L', '10.1',
-                      '-10.1', '', 'string', "€"]
+                      '-10.1', '', 'string', "€", b"bytestring"]
     _bad_values    = [10, -10, 10.1, -10.1, 1j,
                       [10], ['ten'], {'ten': 10},(10,), None]
 
+    def coerce(self, v):
+        return cast_unicode(v)
+
 
 class ObjectNameTrait(HasTraits):
     value = ObjectName("abc")
@@ -1495,7 +1501,7 @@ class TestDottedObjectName(TraitTestBase):
     _default_value = "a.b"
     _good_values = ["A", "y.t", "y765.__repr__", "os.path.join"]
     _bad_values = [1, "abc.€", "_.@", ".", ".abc", "abc.", ".abc.", None]
-    
+
     _good_values.append("t.þ")