Visitar URL original
Non-breaking workaround for BinaryFormatter deprecation, issue #2469 by Legion-ale · Pull Request #2621 · pythonnet/pythonnet · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Non-breaking workaround for BinaryFormatter deprecation, issue #2469
  • Loading branch information
Legion-ale authored Sep 23, 2025
commit 50752e88d4fc014e764c7a32bab8a1d133239ecd
6 changes: 5 additions & 1 deletion src/runtime/StateSerialization/NoopFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
namespace Python.Runtime;

public class NoopFormatter : IFormatter {
public object Deserialize(Stream s) => throw new NotImplementedException();

public object Deserialize(Stream s) => throw new NotImplementedException(
"Cannot deserialize using 'NoopFormatter', implement 'Python.Runtime.RuntimeData.FormatterType' if needed"
);

public void Serialize(Stream s, object o) {}

public SerializationBinder? Binder { get; set; }
Expand Down
29 changes: 27 additions & 2 deletions src/runtime/StateSerialization/RuntimeData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,43 @@ namespace Python.Runtime
{
public static class RuntimeData
{
//TODO: put it in a utility class instead of inside the RuntimeData Class.
private static Version? GetNetVersion(string verToCheck)
{
// Examples:
// ".NET 8.0.0"
// ".NET 9.0.0"
// ".NET Framework 4.8.1"
// ".NET Core 3.1.32"
string desc = RuntimeInformation.FrameworkDescription;
if (desc.StartsWith(verToCheck, StringComparison.OrdinalIgnoreCase))
{
var verStr = desc.Split(' ').Last();
if (Version.TryParse(verStr, out var ver))
return ver;
}
return null;
}

public readonly static Func<IFormatter> DefaultFormatterFactory = () =>
{
try
//The issue here is that just instancing BynaryFormatter doesn't solve the problem.
//you need to use it to generate the exception.
/*try
{
return new BinaryFormatter();
}
catch
{
return new NoopFormatter();
}*/
var ver = GetNetVersion(".NET");
if(ver != null && ver.Major >= 9) {
return new NoopFormatter();
} else {
return new BinaryFormatter();
}
};
}

private static Func<IFormatter> _formatterFactory { get; set; } = DefaultFormatterFactory;

Expand Down
Loading