◐ Shell
clean mode source ↗

Simplify PyScope by delegating ownership to PyObject instance by lostmsu · Pull Request #1367 · pythonnet/pythonnet

Expand Up @@ -29,18 +29,15 @@ public class PyScope : DynamicObject, IDisposable /// <summary> /// the python Module object the scope associated with. /// </summary> internal IntPtr obj; internal BorrowedReference Reference => new BorrowedReference(obj); readonly PyObject obj; internal BorrowedReference Reference => obj.Reference;
/// <summary> /// the variable dict of the scope. /// the variable dict of the scope. Borrowed. /// </summary> internal readonly IntPtr variables; internal BorrowedReference VarsRef => new BorrowedReference(variables);
private bool _isDisposed; private bool _finalized = false;
/// <summary> /// The Manager this scope associated with. /// It provides scopes this scope can import. Expand All @@ -65,7 +62,7 @@ internal PyScope(ref NewReference ptr, PyScopeManager manager) throw new PyScopeException("object is not a module"); } Manager = manager ?? PyScopeManager.Global; obj = ptr.DangerousMoveToPointer(); obj = ptr.MoveToPyObject(); //Refcount of the variables not increase variables = Runtime.PyModule_GetDict(Reference).DangerousGetAddress(); PythonException.ThrowIfIsNull(variables); Expand All @@ -81,7 +78,6 @@ internal PyScope(ref NewReference ptr, PyScopeManager manager) /// <summary> /// return the variable dict of the scope. /// </summary> /// <returns></returns> public PyDict Variables() { Runtime.XIncref(variables); Expand Down Expand Up @@ -136,7 +132,7 @@ public dynamic Import(string name, string asname = null) /// </remarks> public void Import(PyScope scope, string asname) { this.Set(asname, scope.obj); this.SetPyValue(asname, scope.obj.Handle); }
/// <summary> Expand Down Expand Up @@ -335,11 +331,11 @@ private void Exec(string code, BorrowedReference _globals, BorrowedReference _lo public void Set(string name, object value) { IntPtr _value = Converter.ToPython(value, value?.GetType()); Set(name, _value); SetPyValue(name, _value); Runtime.XDecref(_value); }
private void Set(string name, IntPtr value) private void SetPyValue(string name, IntPtr value) { Check(); using (var pyKey = new PyString(name)) Expand Down Expand Up @@ -507,31 +503,16 @@ public override bool TrySetMember(SetMemberBinder binder, object value)
private void Check() { if (_isDisposed) if (this.obj.IsDisposed) { throw new PyScopeException($"The scope of name '{Name}' object has been disposed"); } }
public void Dispose() { if (_isDisposed) { return; } _isDisposed = true; Runtime.XDecref(obj); this.OnDispose?.Invoke(this); }
~PyScope() { if (_finalized || _isDisposed) { return; } _finalized = true; Finalizer.Instance.AddFinalizedObject(ref obj); this.obj.Dispose(); } }
Expand Down