GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — `__delitem__` for `IList<T>` and `IDictionary<K,V>` by lostmsu · Pull Request #2533 · pythonnet/pythonnet

__delitem__ for IList<T> and IDictionary<K,V> #2533

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
lostmsu merged 3 commits into pythonnet:master from losttech:Del
Apr 11, 2025

Uh oh!

There was an error while loading. Please reload this page.

Merged

__delitem__ for IList<T> and IDictionary<K,V> #2533

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
3 commits
Select commit Hold shift + click to select a range
bb7b12f
added NixOS FHS shell.nix
lostmsu Dec 18, 2024
f630f36
index setter was leaking memory
lostmsu Dec 18, 2024
a14d303
implemented __delitem__ for IDictionary<K,V> and IList<T>
lostmsu Dec 18, 2024
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

4 changes: 4 additions & 0 deletions 4 CHANGELOG.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,13 @@ This document follows the conventions laid out in [Keep a CHANGELOG][].
## Unreleased

### Added

- Support `del obj[...]` for types derived from `IList<T>` and `IDictionary<K, V>`

### Changed
### Fixed

- Fixed crash when trying to `del clrObj[...]` for non-arrays
- ci: properly exclude job (#2542)

## [3.0.5](https://github.com/pythonnet/pythonnet/releases/tag/v3.0.5) - 2024-12-13
Expand Down
1 change: 1 addition & 0 deletions 1 pythonnet.sln
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Repo", "Repo", "{441A0123-F
LICENSE = LICENSE
README.rst = README.rst
version.txt = version.txt
shell.nix = shell.nix
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CI", "CI", "{D301657F-5EAF-4534-B280-B858D651B2E5}"
Expand Down
10 changes: 10 additions & 0 deletions 10 shell.nix
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{ pkgs ? import <nixpkgs> {}}:
let
fhs = pkgs.buildFHSUserEnv {
name = "my-fhs-environment";

targetPkgs = _: [
pkgs.python3
];
};
in fhs.env
17 changes: 17 additions & 0 deletions 17 src/runtime/ClassManager.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ internal static void InitClassBase(Type type, ClassBase impl, ReflectedClrType p
ClassInfo info = GetClassInfo(type, impl);

impl.indexer = info.indexer;
impl.del = info.del;
impl.richcompare.Clear();


Expand Down Expand Up @@ -538,6 +539,21 @@ private static ClassInfo GetClassInfo(Type type, ClassBase impl)

ob = new MethodObject(type, name, mlist);
ci.members[name] = ob.AllocObject();
if (name == nameof(IDictionary<int, int>.Remove)
&& mlist.Any(m => m.DeclaringType?.GetInterfaces()
.Any(i => i.TryGetGenericDefinition() == typeof(IDictionary<,>)) is true))
{
ci.del = new();
ci.del.AddRange(mlist.Where(m => !m.IsStatic));
}
else if (name == nameof(IList<int>.RemoveAt)
&& mlist.Any(m => m.DeclaringType?.GetInterfaces()
.Any(i => i.TryGetGenericDefinition() == typeof(IList<>)) is true))
{
ci.del = new();
ci.del.AddRange(mlist.Where(m => !m.IsStatic));
}

if (mlist.Any(OperatorMethod.IsOperatorMethod))
{
string pyName = OperatorMethod.GetPyMethodName(name);
Expand Down Expand Up @@ -581,6 +597,7 @@ private static ClassInfo GetClassInfo(Type type, ClassBase impl)
private class ClassInfo
{
public Indexer? indexer;
public MethodBinder? del;
public readonly Dictionary<string, PyObject> members = new();

internal ClassInfo()
Expand Down
5 changes: 5 additions & 0 deletions 5 src/runtime/MethodBinder.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ internal void AddMethod(MethodBase m)
list.Add(m);
}

internal void AddRange(IEnumerable<MethodBase> methods)
{
list.AddRange(methods.Select(m => new MaybeMethodBase(m)));
}

/// <summary>
/// Given a sequence of MethodInfo and a sequence of types, return the
/// MethodInfo that matches the signature represented by those types.
Expand Down
6 changes: 6 additions & 0 deletions 6 src/runtime/Types/ArrayObject.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,12 @@ public static NewReference mp_subscript(BorrowedReference ob, BorrowedReference
/// </summary>
public static int mp_ass_subscript(BorrowedReference ob, BorrowedReference idx, BorrowedReference v)
{
if (v.IsNull)
{
Exceptions.RaiseTypeError("'System.Array' object does not support item deletion");
return -1;
}

var obj = (CLRObject)GetManagedObject(ob)!;
var items = (Array)obj.inst;
Type itemType = obj.inst.GetType().GetElementType();
Expand Down
42 changes: 40 additions & 2 deletions 42 src/runtime/Types/ClassBase.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ internal class ClassBase : ManagedType, IDeserializationCallback
[NonSerialized]
internal List<string> dotNetMembers = new();
internal Indexer? indexer;
internal MethodBinder? del;
internal readonly Dictionary<int, MethodObject> richcompare = new();
internal MaybeType type;

Expand Down Expand Up @@ -465,6 +466,11 @@ static int mp_ass_subscript_impl(BorrowedReference ob, BorrowedReference idx, Bo
// with the index arg (method binders expect arg tuples).
NewReference argsTuple = default;

if (v.IsNull)
{
return DelImpl(ob, idx, cls);
}

if (!Runtime.PyTuple_Check(idx))
{
argsTuple = Runtime.PyTuple_New(1);
Expand Down Expand Up @@ -497,13 +503,45 @@ static int mp_ass_subscript_impl(BorrowedReference ob, BorrowedReference idx, Bo
// Add value to argument list
Runtime.PyTuple_SetItem(real.Borrow(), i, v);

cls.indexer.SetItem(ob, real.Borrow());
using var result = cls.indexer.SetItem(ob, real.Borrow());
return result.IsNull() ? -1 : 0;
}

/// Implements __delitem__ (del x[...]) for IList&lt;T&gt; and IDictionary&lt;TKey, TValue&gt;.
private static int DelImpl(BorrowedReference ob, BorrowedReference idx, ClassBase cls)
{
if (cls.del is null)
{
Exceptions.SetError(Exceptions.TypeError, "object does not support item deletion");
return -1;
}

if (Runtime.PyTuple_Check(idx))
{
Exceptions.SetError(Exceptions.TypeError, "multi-index deletion not supported");
return -1;
}

using var argsTuple = Runtime.PyTuple_New(1);
Runtime.PyTuple_SetItem(argsTuple.Borrow(), 0, idx);
using var result = cls.del.Invoke(ob, argsTuple.Borrow(), kw: null);
if (result.IsNull())
return -1;

if (Exceptions.ErrorOccurred())
if (Runtime.PyBool_CheckExact(result.Borrow()))
{
if (Runtime.PyObject_IsTrue(result.Borrow()) != 0)
return 0;

Exceptions.SetError(Exceptions.KeyError, "key not found");
return -1;
}

if (!result.IsNone())
{
Exceptions.warn("unsupported return type for __delitem__", Exceptions.TypeError);
}

return 0;
}

Expand Down
4 changes: 2 additions & 2 deletions 4 src/runtime/Types/Indexer.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ internal NewReference GetItem(BorrowedReference inst, BorrowedReference args)
}


internal void SetItem(BorrowedReference inst, BorrowedReference args)
internal NewReference SetItem(BorrowedReference inst, BorrowedReference args)
{
SetterBinder.Invoke(inst, args, null);
return SetterBinder.Invoke(inst, args, null);
}

internal bool NeedsDefaultArgs(BorrowedReference args)
Expand Down
7 changes: 7 additions & 0 deletions 7 src/runtime/Util/ReflectionUtil.cs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,11 @@ public static BindingFlags GetBindingFlags(this PropertyInfo property)
flags |= accessor.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic;
return flags;
}

public static Type? TryGetGenericDefinition(this Type type)
{
if (type is null) throw new ArgumentNullException(nameof(type));

return type.IsConstructedGenericType ? type.GetGenericTypeDefinition() : null;
}
}
36 changes: 36 additions & 0 deletions 36 tests/test_indexer.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -668,3 +668,39 @@ def test_public_inherited_overloaded_indexer():

with pytest.raises(TypeError):
ob[[]]

def test_del_indexer_dict():
"""Test deleting indexers (__delitem__)."""
from System.Collections.Generic import Dictionary, KeyNotFoundException
d = Dictionary[str, str]()
d["delme"] = "1"
with pytest.raises(KeyError):
del d["nonexistent"]
del d["delme"]
with pytest.raises(KeyError):
del d["delme"]

def test_del_indexer_list():
"""Test deleting indexers (__delitem__)."""
from System import ArgumentOutOfRangeException
from System.Collections.Generic import List
l = List[str]()
l.Add("1")
with pytest.raises(ArgumentOutOfRangeException):
del l[3]
del l[0]
assert len(l) == 0

def test_del_indexer_array():
"""Test deleting indexers (__delitem__)."""
from System import Array
l = Array[str](0)
with pytest.raises(TypeError):
del l[0]

def test_del_indexer_absent():
"""Test deleting indexers (__delitem__)."""
from System import Uri
l = Uri("http://www.example.com")
with pytest.raises(TypeError):
del l[0]
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.