Search Results

Search found 15 results on 1 pages for 'hashable'.

Page 1/1 | 1 

  • Hashable, immutable

    - by joaquin
    From a recent SO question I realized I probably had a wrong concept of the meaning of hashable and immutable objects in python. What hashable means in practice?, What the relation between hashable and immmutable is? There are mutable objects that are hashable? And immutable not hashable?

    Read the article

  • Python hashable dicts

    - by TokenMacGuy
    As an exercise, and mostly for my own amusement, I'm implementing a backtracking packrat parser. The inspiration for this is i'd like to have a better idea about how hygenic macros would work in an algol-like language (as apposed to the syntax free lisp dialects you normally find them in). Because of this, different passes through the input might see different grammars, so cached parse results are invalid, unless I also store the current version of the grammar along with the cached parse results. (EDIT: a consequence of this use of key-value collections is that they should be immutable, but I don't intend to expose the interface to allow them to be changed, so either mutable or immutable collections are fine) The problem is that python dicts cannot appear as keys to other dicts. Even using a tuple (as I'd be doing anyways) doesn't help. >>> cache = {} >>> rule = {"foo":"bar"} >>> cache[(rule, "baz")] = "quux" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict' >>> I guess it has to be tuples all the way down. Now the python standard library provides approximately what i'd need, collections.namedtuple has a very different syntax, but can be used as a key. continuing from above session: >>> from collections import namedtuple >>> Rule = namedtuple("Rule",rule.keys()) >>> cache[(Rule(**rule), "baz")] = "quux" >>> cache {(Rule(foo='bar'), 'baz'): 'quux'} Ok. But I have to make a class for each possible combination of keys in the rule I would want to use, which isn't so bad, because each parse rule knows exactly what parameters it uses, so that class can be defined at the same time as the function that parses the rule. But combining the rules together is much more dynamic. In particular, I'd like a simple way to have rules override other rules, but collections.namedtuple has no analogue to dict.update(). Edit: An additional problem with namedtuples is that they are strictly positional. Two tuples that look like they should be different can in fact be the same: >>> you = namedtuple("foo",["bar","baz"]) >>> me = namedtuple("foo",["bar","quux"]) >>> you(bar=1,baz=2) == me(bar=1,quux=2) True >>> bob = namedtuple("foo",["baz","bar"]) >>> you(bar=1,baz=2) == bob(bar=1,baz=2) False tl'dr: How do I get dicts that can be used as keys to other dicts? Having hacked a bit on the answers, here's the more complete solution I'm using. Note that this does a bit extra work to make the resulting dicts vaguely immutable for practical purposes. Of course it's still quite easy to hack around it by calling dict.__setitem__(instance, key, value) but we're all adults here. class hashdict(dict): """ hashable dict implementation, suitable for use as a key into other dicts. >>> h1 = hashdict({"apples": 1, "bananas":2}) >>> h2 = hashdict({"bananas": 3, "mangoes": 5}) >>> h1+h2 hashdict(apples=1, bananas=3, mangoes=5) >>> d1 = {} >>> d1[h1] = "salad" >>> d1[h1] 'salad' >>> d1[h2] Traceback (most recent call last): ... KeyError: hashdict(bananas=3, mangoes=5) based on answers from http://stackoverflow.com/questions/1151658/python-hashable-dicts """ def __key(self): return tuple(sorted(self.items())) def __repr__(self): return "{0}({1})".format(self.__class__.__name__, ", ".join("{0}={1}".format( str(i[0]),repr(i[1])) for i in self.__key())) def __hash__(self): return hash(self.__key()) def __setitem__(self, key, value): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def __delitem__(self, key): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def clear(self): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def pop(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def popitem(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def setdefault(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def update(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def __add__(self, right): result = hashdict(self) dict.update(result, right) return result if __name__ == "__main__": import doctest doctest.testmod()

    Read the article

  • Is this an example of polymorphism?

    - by computer-science-student
    I'm working on a homework assignment (a project), for which one criterion is that I must make use of polymorphism in a way which noticeably improves the overall quality or functionality of my code. I made a Hash Table which looks like this: public class HashTable<E extends Hashable>{ ... } where Hashable is an interface I made that has a hash() function. I know that using generics this way improves the quality of my code, since now HashTable can work with pretty much any type I want (instead of just ints or Strings for example). But I'm not sure if it demonstrates polymorphism. I think it does, because E can be any type that implements Hashable. In other words HashTable is a class which can work with (practically) any type. But I'm not quite sure - is that polymorphism? Perhaps can I get some clarification as to what exactly polymorphism is? Thanks in advance!

    Read the article

  • Graph diffing and versioning tool

    - by hashable
    I am working with a team that edits large DAGs represented as single files. Currently we are unable to work with multiple users concurrently modifying the DAG. Is there a tool (somewhat like the Eclipse SVN plugin) that can do do revision control on the file (manage timestamps/revision stamps) to identify incoming/outgoing/conflicting changes (Node/Link insertion/deletion/modification) and merge changes just like programmers do with source code files? The system should be able to do dependency management also. E.g. an incoming Link must not be accepted when one of the two Nodes is absent. That is, it should not "break" the existing DAG by allowing partial updates. If there is a framework to do this using generic "Node" and "Link" interfaces? Note: I am aware of Protege and its plugins. They currently do not satisfy my requirements.

    Read the article

  • Autoformat pom.xml without using m2eclipse plugin

    - by hashable
    I don't use the Eclipse maven plugin while developing in Eclipse. I generate my Eclipse classpath externally using the following command: mvn eclipse:eclipse This has worked fine for quite some time and I am not inclined to add a maven plugin. However, I would like to be able to "autoformat" my pom.xml file. My pom.xml is not showing up as a "Source" file and therefore the contextual "Source" menu doesn't show up. Control-Shift-F doesn't work either. Is there a way to do this without installing the m2eclipse plugin? Is there any other generic "XML Editor" plugin that can help with this?

    Read the article

  • Scalable (half-million files) version control system

    - by hashable
    We use SVN for our source-code revision control and are experimenting using it for non-source-code files. We are working with a large set (300-500k) of short (1-4kB) text files that will be updated on a regular basis and need to version control it. We tried using SVN in flat-file mode and it is struggling to handle the first commit (500k files checked in) taking about 36 hours. On a daily basis, we need the system to be able to handle 10k modified files per commit transaction in a short time (<5 min). My questions: Is SVN the right solution for my purpose. The initial speed seems too slow for practical use. If Yes, is there a particular svn server implementation that is fast? (We are currently using the gnu/linux default svn server and command line client.) If No, what are the best f/oss/commercial alternatives Thanks

    Read the article

  • Deterministic key serialization

    - by Mike Boers
    I'm writing a mapping class which uses SQLite as the storage backend. I am currently allowing only basestring keys but it would be nice if I could use a couple more types hopefully up to anything that is hashable (ie. same requirements as the builtin dict). To that end I would like to derive a deterministic serialization scheme. Ideally, I would like to know if any implementation/protocol combination of pickle is deterministic for hashable objects (e.g. can only use cPickle with protocol 0). I noticed that pickle and cPickle do not match: >>> import pickle >>> import cPickle >>> def dumps(x): ... print repr(pickle.dumps(x)) ... print repr(cPickle.dumps(x)) ... >>> dumps(1) 'I1\n.' 'I1\n.' >>> dumps('hello') "S'hello'\np0\n." "S'hello'\np1\n." >>> dumps((1, 2, 'hello')) "(I1\nI2\nS'hello'\np0\ntp1\n." "(I1\nI2\nS'hello'\np1\ntp2\n." Another option is to use repr to dump and ast.literal_eval to load. This would only be valid for builtin hashable types. I have written a function to determine if a given key would survive this process (it is rather conservative on the types it allows): def is_reprable_key(key): return type(key) in (int, str, unicode) or (type(key) == tuple and all( is_reprable_key(x) for x in key)) The question for this method is if repr itself is deterministic for the types that I have allowed here. I believe this would not survive the 2/3 version barrier due to the change in str/unicode literals. This also would not work for integers where 2**32 - 1 < x < 2**64 jumping between 32 and 64 bit platforms. Are there any other conditions (ie. do strings serialize differently under different conditions)? (If this all fails miserably then I can store the hash of the key along with the pickle of both the key and value, then iterate across rows that have a matching hash looking for one that unpickles to the expected key, but that really does complicate a few other things and I would rather not do it.) Any insights?

    Read the article

  • Contrary to Python 3.1 Docs, hash(obj) != id(obj). So which is correct?

    - by Don O'Donnell
    The following is from the Python v3.1.2 documentation: From The Python Language Reference Section 3.3.1 Basic Customization: object.__hash__(self) ... User-defined classes have __eq__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns id(x). From The Glossary: hashable ... Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id(). This is true up through version 2.6.5: Python 2.6.5 (r265:79096, Mar 19 2010 21:48:26) ... ... >>> class C(object): pass ... >>> c = C() >>> id(c) 11335856 >>> hash(c) 11335856 But in version 3.1.2: Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) ... ... >>> class C: pass ... >>> c = C() >>> id(c) 11893680 >>> hash(c) 743355 So which is it? Should I report a documentation bug or a program bug? And if it's a documentation bug, and the default hash() value for a user class instance is no longer the same as the id() value, then it would be interesting to know what it is or how it is calculated, and why it was changed in version 3.

    Read the article

  • Python most common element in a list

    - by Richard
    What is an efficient way to find the most common element in a Python list? My list items may not be hashable so can't use a dictionary. Also in case of draws the item with the lowest index should be returned. Example: >>> most_common(['duck', 'duck', 'goose']) 'duck' >>> most_common(['goose', 'duck', 'duck', 'goose']) 'goose'

    Read the article

  • what would be a frozen dict ?

    - by dugres
    A frozen set is a frozenset. A frozen list could be a tuple. What would be a frozen dict ? An immutable, hashable dict. I guess it could be something like collections.namedtuple, but namedtuple is more like a frozenkeys dict (an half-frozen dict). No ?

    Read the article

  • Java - Make an object collection friendly

    - by DutrowLLC
    If an object holds a unique primary key, what interfaces does it need to implement in order to be collection friendly especially in terms of being efficiently sortable, hashable, etc...? If the primary key is a string, how are these interfaces best implemented? Thanks!

    Read the article

  • Implementing a multimap in Swift with Arrays and Dictionaries

    - by stuffy
    I'm trying to implement a basic multimap in Swift. Here's a relevant (non-functioning) snippet: class Multimap<K: Hashable, V> { var _dict = Dictionary<K, V[]>() func put(key: K, value: V) { if let existingValues = self._dict[key] { existingValues += value } else { self._dict[key] = [value] } } } However, I'm getting an error on the existingValues += value line: Could not find an overload for '+=' that accepts the supplied arguments This seems to imply that the value type T[] is defined as an immutable array, but I can't find any way to explicitly declare it as mutable. Is this possible in Swift?

    Read the article

  • What does these FindBug messages show?

    - by Hans Klock
    Not every description from from http://findbugs.sourceforge.net/bugDescriptions.html is clear to me. Sure, I can study the implementation but if somebody is more experienced then me, some explanation and examples would be great. Do you have some examples for UI_INHERITANCE_UNSAFE_GETRESOURCE when this is getting a problem? In BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR I don't see the problem either. If one type is "bigger" then the other, for example int and float, then the result is float. If its Integer and Float its the wrapper Float too. That's what I expect. Does the GC_UNRELATED_TYPES really help to find errors? Isn't it the job of the compiler to check, if--taking the given example--Foo can't go into a Collection<String>. Does HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS mean something like bla(Foo f){hashtable.put(f);}, where ´Foo´ is not hashable? Does FingBugs "see" the subclasses too? NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH is stronger "wrong" then NP_ALWAYS_NULL_EXCEPTION? Why two error cases and with NP_NULL_ON_SOME_PATH_EXCEPTION even one more? Sounds very similar to me. What is an example of SIO_SUPERFLUOUS_INSTANCEOF? Something like foo(String s){if (s intenceof String) .... This does a null check too, but this is not the test here... NN_NAKED_NOTIFY. I my opinion the description is not clear. A change of the state is not necessary. If I use new Object() to wait and notify on I don't change the object state. Or is state the lock-state? I don't get it. SP_SPIN_ON_FIELD. Can this really happen that a compiler will move this outside from a loop? This doesn't make sense to me because from outside a Thread can always change the values. And if the variable is volatile the JVM can't cache the value. So what's the meaning? That is the difference between STCAL_STATIC_CALENDAR_INSTANCE and STCAL_INVOKE_ON_STATIC_CALENDAR_INSTANCE or STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE/STCAL_STATIC_SIMPLE_DATE_FORMAT_INSTANCE? Why is XXXX.class in WL_USING_GETCLASS_RATHER_THAN_CLASS_LITERAL better then getClass()? A getClass() in a superclass called from the subclass will always return the Class object from the subclass which is good I think. What exactly does EQ_UNUSUAL do? It should check that the argument is of the same type of the class itself but it does't? Did you ever had problems with breaks? Is there real value with SF_SWITCH_FALLTHROUGH? Sounds to strong for me. No idea what TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_ALWAYS_SINK and TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_NEVER_SINK could be.

    Read the article

1