Username must be unique and can't be changed in Mastermind - python

I'm designing a UML class diagram for a Mastermind game and I'm having trouble figuring out how to make the attribute 'Name' unique and not changeable. I'm assuming that I do this by naming the 'Name' attribute private and show it in the class diagram as well. Any sort of help would be highly appreciated. Thanks

As per Python you can only indicate private attributes by adding an underscore in front of the name. Language-wise this is not a language construct but a convention. UML does not care since it's language-agnostic. Model it as private (by showing the - in front of the name). If you are generating code from that UML model the code generator might create the underscore automatically.
In any case, if you create a model with UML and indicate something to be private then the coder for the language must take care. For a closed implementation you just need to train your coders. For an open (library) implementation Python will let you stand in the rain with that.

In short
Since you're looking for the UML notation more than the Python aspects:
More explanations
Not changeable
UML has read-only properties annotated with a {readOnly}. The specifications define the semantics:
If a StructuralFeature is marked with isReadOnly true, then it may not be updated once it has been assigned an initial value. Conversely, when isReadOnly is false (the default), the value may be modified.
UML does however not tell how the initial value is provided. If it's a private property, you'll probably provide the initial name to the constructor. Showing it (with a preceeding «create») will clarify the ambiguity.
Unique
It is likewise possible to indicate {unique} for a property. However, this makes only sense for multivalued properties because it means that there are no duplicates values among the multliple property values of the same object. You'll probably have somePlayer object with a single Name: it then makes no difference if you add {unique} or not.
If you have somewhere a Game associated with two Players you could put a {unique} on the association-end to say that its two different player, but nothing would prevent them having the same name. Fortunately, there are two preagmatic solutions:
Add a natural language constraint to the association, e.g. { player names must be unique }. The advantage is that is clear an unambiguous for human readers. You could translate this into a more formal OCL expression but it's like double coding: onces in OCL and once in Python.
Add {id} after the name, to tell that the name is the identifier for the class. Identifiers are in principle unique within the class. However, although most readers will understand this, it is ambiguous, since UML does not define the semantics of identifiers:
A Property may be marked, via the property isID, as being (part of) the identifier (if any) for Classifiers of which it is a member. The interpretation of this is left open but this could be mapped to implementations such as primary keys for relational database tables or ID attributes in XML.
Moreover, this would prevent two players of a different game having the same name.
On the diagram, I showed both alternatives, but IMHO you should not use id if it has no clear benefits.

Related

How to structure a project into Object Oriented framework?

I have a project and would like ideas/tips on how I could tackle it. This is the project
Each component in a car has a number. Example:
"Hitch" has num: "43". I want to search and return
every car model in the database (CSV file) that has the number "43".
In the future, I would also like to be able to see information about
the car model. Example: "manufacturer", "HP", then info about the
"manufacturer" etc etc.
I have never done anything like this before, but I have researched and found that maybe OOP is the way to go? In that case, how could one structure it?
Since your main question is how do you break your requirement into an Object Oriented framework, I would structure it as follows:
You have objects called Parts and an object called Car.
Parts will have attributes: PartName(string), PartId(integer), PartManufacturer(string).
Car will have objects CarName(string), CarId(int), CarManufacturer(string).
A third object PartsInCar will track the relation between Car and Parts.
This object will have attributes CarPartId (int), CarId(Car), PartId(part).
Alternatively PartsInCar can also be an attribute of Car as a "vector of class Parts".
Depending on how granular you want to maintain the data, there is a possibility to create another class Manufacturer having ManufacturerId(int), ManufacturerName(string).
Now the question is how do you load your csv database into this structure ?
This depends on how your input data looks like.
if you are doing the whole thing in memory, then you could use vector or dictionary to store the whole "list" of parts, cars and parts_in_car.
For each class defined above you will of course need member functions that will allow us easy operation.
E.g.:
Cars object can have a member function that will return all Parts objects associated with it.
Parts object can have a member function that searches all Cars and shortlists those cars that are using this part.
you could use a dictionary with the key being the car name, and the value being a list of information about each car. You can assign certain aspects of the car to each index of the list to keep track of the data. you could use oop for this but it's a bit uncessary if I understood your question correctly

Store reference to non-NDB object in an NDB model

As a caveat: I am an utter novice here. I wouldn't be surprised to learn a) this is already answered, but I can't find it because I lack the vocabulary to describe my problem or b) my question is basically silly to begin with, because what I want to do is silly.
Is there some way to store a reference to a class instance that defined and stored in active memory and not stored in NDB? I'm trying to write an app that would help manage a number of characters/guilds in an MMO. I have a class, CharacterClass, that includes properties such as armor, name, etc. that I define in main.py as a base python object, and then define the properties for each of the classes in the game. Each Character, which would be stored in Datastore, would have a property charClass, which would be a reference to one of those instances of CharacterClass. In theory I would be able to do things like
if character.charClass.armor == "Cloth":
while storing the potentially hundreds of unique characters and their specifc data in Datastore, but without creating a copy of "Cloth" for every cloth-armor character, or querying Datastore for what kind of armor a mage wears thousands of times a day.
I don't know what kind of NDB property to use in Character to store the reference to the applicable CharacterClass. Or if that's the right way to do it, even. Thanks for taking the time to puzzle through my confused question.
A string is all you need. You just need to fetch the class based on the string value. You could create a custom property that automatically instantiates the class on reference.
However I have a feeling that hard coding the values in code might be a bit unwieldy. May be you character class instances should be datastore entities as well. It means you can adjust these parameters without deploying new code.
If you want these objects in memory then you can pre-cache them on warmup.

Python: Should I put my data in lists or object attributes?

I am looking for an appropriate data structure in Python for processing variably structured forms. By variably structured forms I mean that the number of form fields and the types of the form's contents are not known in advance. They are defined by the user who populates the forms with his input.
What are the pros and cons of putting data in A) object attributes (e.g. of an otherwise empty "form"-class) or B) simply lists/dicts? Consider that I have to preserve the sequence of form fields, the form field names and the types.
(Strangely, it has been difficult to find conclusive information on this topic. As I am still new to Python, it's possible that I have searched for the wrong terms. If my question is not clear enough, please ask in the comments and I will try to clarify.)
In Python, as in all object-oriented languages, the purpose of classes is to associate data and closely-related methods that act on that data. If there's no real encapsulation going on (i.e. the methods help define the ways you can interact with the data), the best choice is a conglomeration of builtin types like lists and dictionaries as you mention and perhaps some utility functions that act on those sorts of data structures.
Python classes are literally just two dicts (one for functions, one for data), a name and the rules how Python looks for keys. When you access existing keys, there is absolutely no difference to a dict (unless you overwrote the access rules of cause).
That means that there is no drawback (besides more code) to using classes at all and you should never be afraid to write a class.
In your particular case I think you should go with classes, for one simple reason: You might want to extend them later. Maybe you want to add constraints on the name (length, allowed letters, uniqueness, ...) or the value (not empty, length, type, ...) of a field one day. Maybe you want to validate all fields in a form. If you use a class you can do this without changing any code outside the class! And as I said before, even if you don't, there are no drawbacks!
I guess my rule of thumb for classes is: Don't use a class if you're absolutely sure that there is nothing to add to it. If not just write those few extra lines.
It's not very Pythonic to randomly add members to an object. It would be more Pythonic if you used member methods to do it, but still not the way things are usually done.
Every library I've seen for this kind of thing uses dictionaries or lists. So that is the idiomatically Python way to handle the problem. Sometimes they use an object that overrides __getitem__ so it can behave like a dictionary or list, but it's still dictionary syntax that's used to access the fields.
I think all the pros and cons have to do with people understanding your code, and since I've never seen code that handles this by having an object with members that can appear I don't think many people will find code that does do that to be very understandable.
A list of dictionaries (e.g. [{"type": "text", "name": "field_name", "value": "test value"}, ...]) would be a usable structure, if I understand your requirement correctly.
Whether object are better in this case depends on what you're doing later. If you use the objects just as data storage, you don't gain anything. Maybe a list of field objects, which implement some appropriate methods to deal with your data, would also be a good choice.
maybe if you set up an object to use for each field and store those in a list, but that is practically ending up like a glorified dictionary
then you could access it like
fields[2].name
fields[2].value
ect

Design Golf: modeling an Address in appengine, aka an AddressProperty?

Today I was refactoring some code and revisited an old friend, an Address class (see below). It occurred to me that, in our application, we don't do anything special with addresses-- no queries, only lightweight validation and frequent serialization to JSON. The only "useful" properties from the developer point-of-view are the label and person.
So, I considered refactoring the Address model to use a custom AddressProperty (see below), which strikes me as a good thing to do, but off-the-top I don't see any compelling advantages.
Which method would you choose, why and what tradeoffs guide that decision?
# a lightweight Address for form-based CRUD
# many-to-one relationship with Person objects
class Address(db.Model):
label=db.StringProperty()
person=db.ReferenceProperty(collection_name='addresses')
address1=db.StringProperty()
address2=db.StringProperty()
city=db.StringProperty()
zipcode=db.StringProperty()
# an alternate representation -- worthwhile? tradeoffs?
class Address(db.Model):
label=db.StringProperty()
person=db.ReferenceProperty(collection_name='addresses')
details=AddressProperty() # like db.PostalAddressProperty, more methods
Given that you don't need to query on addresses, and given they tend to be fairly small (as opposed to, say, a large binary blob), I would suggest going with the latter. It'll save space and time (fetching it) - the only real downside is that you have to implement the property yourself.
If you wanted to be a little different you could always store the data in one table as structures and then have another table for lookups and metadata

How do I get the value of a property corresponding to a SQLAlchemy InstrumentedAttribute?

Given a SQLAlchemy mapped class Table and an instance of that class t, how do I get the value of t.colname corresponding to the sqlalchemy.org.attributes.InstrumentedAttribute instance Table.colname?
What if I need to ask the same question with a Column instead of an InstrumentedAttribute?
Given a list of columns in an ORDER BY clause and a row, I would like to find the first n rows that come before or after that row in the given ordering.
To get an objects attribute value corresponding to an InstrumentedAttribute it should be enough to just get the key of the attribute from it's ColumnProperty and fetch it from the object:
t.colname == getattr(t, Table.colname.property.key)
If you have a Column it can get a bit more complicated because the property that corresponds to the Column might have a different key. There currently doesn't seem to be a public API to get from a column to the corresponding property on a mapper. But if you don't need to cover all cases, just fetch the attr using Column.key.
To support descending orderings you'll either need to construct the desc() inside the function or poke a bit at non-public API's. The class of the descending modifier ClauseElement is sqlalchemy.sql.expression._UnaryExpression. To see if it is descending you'll need to check if the .modifier attribute is sqlalchemy.sql.operators.desc_op. If that case you can get at the column inside it via the .element attribute. But as you can see it is a private class, so watch for any changes in that area when upgrading versions.
Checking for descending still doesn't cover all the cases. Fully general support for arbitrary orderings needs to be able to rewrite full SQL expression trees replacing references to a table with corresponding values from an object. Unfortunately this isn't possible with public API's at this moment. The traversal and rewriting part is easy with sqlalchemy.sql.visitors.ReplacingCloningVisitor, the complex part is figuring out which column maps to which attribute given inheritance hierarchies, mappings to joins, aliases and probably some more parts that escape me for now. I'll give a shot at implementing this visitor, maybe I can come up with something robust enough to be worthy of integrating into SQLAlchemy.

Categories

Resources