Skip to content

Allow conversion of number to enum type when underlying type is assignable #1179

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.

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

Closed
wants to merge 2 commits into from
Closed

Allow conversion of number to enum type when underlying type is assignable #1179

wants to merge 2 commits into from

Conversation

slide
Copy link
Contributor

@slide slide commented Jul 6, 2020

What does this implement/fix? Explain your changes.

In .NET you can do the following:

enum FooEnum {
    One = 1,
    Three = 3,
    Four = 4,
}

FooEnum x = (FooEnum)2;

This patch allows this from Python code as well.

Does this close any currently open issues?

Possibly #935

Any other comments?

I would definitely like eyes on this, I am possibly missing something :-)

Checklist

Check all those that are applicable and complete.

  • Make sure to include one or more tests for your change
  • If an enhancement PR, please create docs and at best an example
  • Add yourself to AUTHORS
  • Updated the CHANGELOG

slide added 2 commits July 6, 2020 10:23
In .NET you can do the following:
```
enum FooEnum {
	One = 1,
	Three = 3,
	Four = 4,
}

FooEnum x = (FooEnum)2;
```

This patch allows this from Python code as well.
@lostmsu
Copy link
Member

lostmsu commented Jul 6, 2020

@slide in .NET you can't just assign a numeric value to an enum. You have to make an explicit cast for a good reason. The most pythonic way I see this could work is FooEnum(42). Implicit conversion is a bad idea.

@slide
Copy link
Contributor Author

slide commented Jul 6, 2020

That's true, it does require the typecast. This only allows assignment/coercion when the underlying type is assignable, is that still too lenient?

@lostmsu
Copy link
Member

lostmsu commented Jul 6, 2020

@slide oh, I checked the code of ToEnum and it seems problematic on its own. I think what you will find is that IsAssignableFrom will succeed in most cases.

I actually think Python.NET should have required an explicit cast from the beginning, and should not have converted enum values to Python int, which we have an opportunity to fix given 3.0 is a major version bump. I'd definitely take a PR, that would make that change.

Summoning @filmor into conversation.

@slide
Copy link
Contributor Author

slide commented Jul 6, 2020

Ok, thanks, I'll see if I can work on something like that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants