How can I access an enum member with an input in python
I am trying to access the value of the enum
variables with an input.
Here is my code:
class Animals(Enum):
Dog = 1
Cat = 2
Cow = 3
Choose = input('Choose an animal')
print(Animals.Choose.value)
Which gives me an error perhaps because Animals
does not contain Choose
.
How can I distinguish between a member in the enum
and my input variable?
So that if I input Dog
it would give 1
(the value of the Dog
variable)?
2 answers
-
answered 2021-01-11 05:18
U11-Forward
You can try using
getattr
:from enum import Enum class Animals(Enum): Dog = 1 Cat = 2 Cow = 3 Choose = input('Choose an animal') print(getattr(Animals, Choose).value)
Output:
1
getattr
stands for "get attribute", which means it gets the variable in the class which it's name is what the second argument is.Enum
s have already builtin__getitem__
methods, so you can directly index it with[]
brackets, like this:print(Animals[Choose].value)
Output:
1
-
answered 2021-01-11 05:23
Mark Tolonen
Enums have built-in access by string and various ways of accessing the result. See the documentation for Enum for more details:
from enum import Enum class Animal(Enum): Dog = 1 Cat = 2 Cow = 3 choice = input('Choose an animal: ') print(Animal[choice]) print(repr(Animal[choice])) print(Animal[choice].value)
Choose an animal: Cat Animal.Cat <Animal.Cat: 2> 2
See also questions close to this topic
-
How deos scikit-learn's KNN calculate the probability estimates?
How does the implementation of KNN algorithm in scikit learn calculate the probability estimates for the
predict_proba(X)
method? -
Is there a way of replacing specific quotation marks?
I'm using Open Trivia DB's API to generate trivia questions.
import requests, json, urllib.parse import url = "https://opentdb.com/api.php" querystring = {"amount":"5","type":"multiple","encode":"url3986"} response = requests.request("GET", url, params=querystring) response_decoded = urllib.parse.unquote(response.text) print(response_decoded) response_dict = json.loads(response_decoded) print(response_dict["results"][0])
However, I keep on running into an error one some occurrences, the error being:
Exception has occurred: JSONDecodeError Expecting ',' delimiter: line 1 column 347 (char 346)
I've worked out that the error is because in some questions are similar to
Who is the main character in "gamename"
. But in the context of the JSON I was returned it looks more like this:"question":"Who is the main character in "gamename"?", "correct_answer":"maincharacter", "incorrect_answers":["wrongname1","wrongname2","wrongname3"]
and the quotation marks around the gamename is messing the dictionary up.
Is there a way for me to replace the inner quotation marks only (around the gamename) to singular quotation marks,
'
, so that it doesn't mess up the dictionary structure? -
Catenary Curve using python - With user imput
Looking to make this using python but not sure where to start. I would like to have a visual display of the Catenary Curve below with a section that allows a user to enter the percentage of span which is located on the bottom and take the value on the left side that corresponds to the Catenary Curve.
-
How to iterate class variables in React?
I am using typescript and I had this class where I need to iterate the values in it.
export default class ModelShadow { story: Story[] = []; name: string = ''; } export interface Story { title: Title[]; header: Title[]; } export interface Title { name: string; description: string; } export const Text1 = ({index}) => { <div> <input name='story.{index}.name'/> </div> <div> <input name='story.{index}.description'/> </div> <button onClick={function that deletes the array depends on the index > delete </button> export const Text2 = ({index}) => { <div> <input name='header.{index}.name'/> </div> <div> <input name='header.{index}.description'/> </div> <button onClick={function that deletes the array depends on the index > delete </button>
I had a Select that adds the Text above to an array and I want to eliminate the null values upon submit. Because every I choose Text1 the index is 0 and add another Text2, the index is 1 and so on so forth.
The result was like this:
story: header: 0: { name: 'test', description: 'test' } 1: null 2: { name: 'test', description: 'test' } title: 0: null 1: { name: test', description: 'test' }
It should be like this,
header: 0: { name: 'test', description: 'test' } 1: { name: 'test', description: 'test' } title: 0: { name: test', description: 'test' }
Thank so much.
-
Function in a function in a while loop can not update an outside class variable?
So this code runs correctly...
class Deck: def __init__(self): self.cards = [] for i in range(6): self.cards.append(i) class Player: def __init__(self): self.cards = [] class Game: def __init__(self): self.player = Player() self.deck = Deck() def play_game(self): self.add_card() print(self.player.cards) def add_card(self): self.player.cards.append(self.deck.cards.pop()) game = Game() game.play_game()
But if I add
while True:
to theplay_game(self)
function like this...def play_game(self): while True: self.add_card() print(self.player.cards)
It says it can not
pop()
from an empty list. So I assume the function within the while loop is not able to access the variableself.player.cards
, within the same instance as the correctly stated code does. Am I right about that?Basically I just want to understand why this doesn't work, and what is going on...?
I do apologize if my wording is not accurate, I am new to Python...
Thanks!
-
c++ method wont override at all?
I am very confused, the code below throws "OVERRIDE ME" when read(..) is called:
class static_stream : public bytestream { protected: uint8* buf; public: uint8* read(uint32 size) override; static_stream(uint8* buf, uint64 size); ~static_stream(); uint8* get_buffer(); }; //this overrides: virtual uint8* read(uint32 size) { throw "OVERRIDE ME "; } // in bytestream.h
The function overrides in other classes but not this one. Any ideas why? Its not called in the constructor. (Function definitions are excluded)
An example of it being used:
static_stream* info_list = new static_stream(ttarch_stream->read(filelist_size), filelist_size); uint8* test = info_list->read(100); // throws override me
-
How can I store Object in Enum in Java
With the Spigot-API, in Minecraft, I want to check if the Player is holding a specific Item in his hand. Can I somehow get the Item as comparative value from an Enum? I want to do that because I have some special Items with custom meta data and I want to have them in a enumeration list. Is this an eligible way? I tried something with a constructor in the enum but also I am too inexperienced in enums. -Or what would be a good way to store the items?
I just want to get the Item by doing:
Items.NAME;
Would this be a solution?
public enum Items{ GRANADE (getGranade()); ItemStack item; Items(ItemStack item) { this.item = item; } private static ItemStack getGranade() { //some code here }
}
-
How to discover missing type-maps for mapping enum to enum in AutoMapper?
How to discover missing type-maps for mapping enum to enum in AutoMapper?
Ok folks, this is a rather long question, where I´m trying my best to describe the current situation and provide some meaningful context, before I´m comming to my actual question.
TL;DR;
I need a way to identify missing type-maps of mappings from enum-to-enum-properties in AutoMapper, so that I can configure to use mapping per-name instead of AutoMapper´s default behavior of mapping per-value (which is, using the internal integer-representation of an enum).
Some Context
So my team and I are maintaining this rather complex set of REST-APIs...complex at least when it comes down to the actual object-graphs involved. We have to deal with some hundreds of models in total. To raise structural complexity, the original architectures went with full n-tier-style on an inner API-level.
On top of that, we´re having multiple of such architectured services, which sometimes need calling each other. This is achieved through either ordinary http-calls here, some messaging there, you get the idea.
For letting an API communicate with another, and to maintain SOA- and/or microservice-principles, every API at least provides a corresponding client-library, which manages communication with it´s representing API, regardless of the actual underlying protocol involved.
Boiling this down, this incorporates at least the following layers per API (top-down)
- Client-Layer
- API-Layer
- Domain-Layer
- Persistence-Layer
Additionally, all those layers maintain their own representation of the various models. Often, those are 1:1 representation, just in another namespace. Sometimes there are more significant differences in between these layers. It depends...
To reduce boiler-plate when communicating between these layers, we´re falling back on AutoMapper most of the time (hate it or love it).
The problem:
As we evolve our overall system, we more and more noticed problems when mapping enum-to-enum properties within the various representations of the models. Sometimes it´s because some dev just forgot to add a new enum-value in one of the layers, sometimes we re-generated an Open-API based generated client, etc., which then leads to out-of-sync definitions of those enums. Another issue happens, if, for some reason, these enums are par member-wise, but have another ordering or naming, hence internal representation of the actual enum value. This can get really nasty, especially when we remember how AutoMapper handles enum-to-enum-mappings per default: per Value.
Let´s say we have this (very very over-simplified) model-representations
public enum Source { A, B, C, D } public enum Destination { C, B, A } class SourceType { public string Name { get; set; } public Source Enum { get; set; } } class DestinationType { public string Name { get; set; } public Destination Enum { get; set; } }
Now let´s say our AutoMapper config looks something like this:
var mapperConfig = new MapperConfiguration(config => { config.CreateMap<SourceType, DestinationType>(); });
So mapping the following models is kind of a jeopardy, semantic-wise (or at least offers some very odd fun while debugging).
var a = mapper.Map<DestinationType>(new SourceType { Name = "A", Enum = Source.A ); //a is { // Name = "A", Enum = Destination.A <-- ✔️ looks good //} var b = mapper.Map<DestinationType>(new SourceType { Name = "B", Enum = Source.B ); //b is { // Name = "B", Enum = Destination.B <-- ✔️ looks good //} var c = mapper.Map<DestinationType>(new SourceType { Name = "C", Enum = Source.C ); //c is { // Name = "C", Enum = Destination.C <-- ✔️ looks good //} var d = mapper.Map<DestinationType>(new SourceType { Name = "D", Enum = Source.D ); //d is { // Name = "D", Enum = 3 <-- ❗ wtf, are you serious? //}
Fewer fun can be observed, when this ultimately causes some nasty production-bugs, which also may have more or less serious business-impact - especially when this kind of issue only happens during run-time, rather than test- and/or build-time.
Additionally, the problem is not exclusive to n-tier-ish architectures, but could also be an issue in orthogonal/onion-/clean-ish-architecture styles (wheras in such cases it should be more likely that such value-types would be placed somewhere in the center of the APIs, rather than on every corner / outer-ring /adapter-layer or whatever the current terminology is)
A (temporary) solution
Despite trying to reduce the shear amount of redundancy within the respective layers, or (manually) maintaining explicit enum-values within the definitions itself (which both are valid options, but heck, this is a lot of PITA-work), there is not much left to do while trying to mitigate this kind of issues.
Gladly, there is a nice option available, which levereages mapping enum-to-enum-properties per-name instead of per-value, as well as doing more customization on a very fine-granular level on a per-member-basis.
[AutoMapper.Extensions.EnumMapping] to the rescue!
from the docs:
The package AutoMapper.Extensions.EnumMapping will map all values from Source type to Destination type if both enum types have the same value (or by name or by value)
and
This package adds an extra EnumMapperConfigurationExpressionExtensions.EnableEnumMappingValidation extension method to extend the existing AssertConfigurationIsValid() method to validate also the enum mappings.
To enable and cusomize mappings, one should just need to create the respective type-maps within AutoMapper-configuration:
var mapperConfig = new MapperConfiguration(config => { config.CreateMap<SourceType, DestinationType>(); config.CreateMap<Source, Destination>().ConvertUsingEnumMapping(opt => opt.MapByName()); config.EnableEnumMappingValidation(); }); mapperConfig.AssertConfigurationIsValid();
Which then would validate even enum-to-enum mappings.
The question (finally ^^)
As our team previously did not (need to) configure AutoMapper with maps for every enum-to-enum mapping (as was the case for dynamic-maps in previous-versions of AutoMapper), we´re a bit lost on how to efficiently and deterministically discover every map needed to be configured this way. Especially, as we´re dealing with possibly a couple of dozens of such cases per api (and per layer).
How could we possibly get to the point, where we have validated and adapted our existing code-base, as well as further preventing this kind of dumbery in the first place?
-
Dictionary<enum, enum> runtime issue
Why the following code, in VisualStudio, behaves this way?
On the IDE
Test.two = Test2.two2
but in debugTest.two = one
public enum Test { one = Test2.one2, two = Test2.two2 } public enum Test2 { one2 = Test3.three, two2 = Test3.three } public enum Test3 { three } static void Main(string[] args) { Dictionary<Test, Test2> dtest = new Dictionary<Test, Test2>(); dtest.Add(Test.one, Test2.one2); dtest.Add(Test.two, Test2.two2); // * } // On runtime I get this exception: // * System.ArgumentException: 'An item with the same key has already been added. Key: one'
I understand that I am assigning enums to enums and all converge into index 0, if this is correct,
Test.two
becomesone
because its index is 0.But still I was hopping to stick with the enum values themselves, is there a way to override the index or get the real value regardless of the index?
-
AttributeError: 'StandardScaler' object has no attribute 'var_'
I get this error message attempting to use the .var_ and .mean_ attribute of StandardScaler from Sci-Kit Learn. I saw in another SO post that it is no longer supported in newer versions so I downloaded an older one and it did not work either.
-
Python: Workaround for NoneType in ElementTree
Good day to all of you,
I'm trying to load an .xml-file with ElementTree with the following code:
data = [] root = et.fromstring(r.content) user = root.findall('.//user') for u in user: data.append( {'id': u.get('id'), 'firstName': u.find('firstName').text, 'lastName': u.find('lastName').text, 'personnelNumber': u.find('personnelNumber').text} )
I know that there are a few - maybe half a dozen - rows where 'personnelNumber' is empty, so I'm getting the following error:
AttributeError: 'NoneType' object has no attribute 'text'
I would like to ask if someone knows a workaround for this problem? I honestly don't care about the few missing entrys, so that I only achieve the rest!?
Thanks for all your help and a great weekend!
-
AttributeError: 'PostgresConnection' object has no attribute 'db_check'
I am new to python and trying to create a unit test, but I receive an "attribute error: 'PostgresConnection' object has no attribute db_check". The code I am unit testing is as follows:
class PostgresConnection: def __init__(self, pg_dict): self.database = pg_dict['database'] if 'database' in pg_dict else None self.user = pg_dict['user'] self.password = pg_dict['password'] self.host = pg_dict['host'] def set_database(self, db): flush_print("Ensuring database exists", db) db_exists = self.db_check(db) if not db_exists: flush_print("Database not found, creating") self.run_query(f'CREATE DATABASE "{db}"', True) self.database = db if not db_exists: flush_print("Adding Post GIS Extension") self.create_postgis_ext()
The name of the script I am unit testing is called admin_clip, which is imported into the unit test. My unit test code is as follows:
import unittest import admin_clip class PostgresConnection(unittest.TestCase): def test__init__(self): pg_dict = { "database": "UnitTests", "host": "xx.xxx.xxx.xx", "password": "postgres", "user": "postgres" } admin_clip.PostgresConnection.__init__(self,pg_dict) def test_set_database(self): pg_dict = { "database": "UnitTests", "host": "xx.xxx.xxx.xx", "password": "postgres", "user": "postgres" } db = pg_dict result = admin_clip.PostgresConnection.set_database(self, db) print(result) if __name__== '__main__': unittest.main()