Python __builtin__.dict() Examples

The following are 17 code examples of __builtin__.dict(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module __builtin__ , or try the search function .
Example #1
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def openscope(self, customlocals=None):
        '''Opens a new (embedded) scope.

        Args:
            customlocals (dict): By default, the locals of the embedding scope
                are visible in the new one. When this is not the desired
                behaviour a dictionary of customized locals can be passed,
                and those locals will become the only visible ones.
        '''
        self._locals_stack.append(self._locals)
        self._globalrefs_stack.append(self._globalrefs)
        if customlocals is not None:
            self._locals = customlocals.copy()
        elif self._locals is not None:
            self._locals = self._locals.copy()
        else:
            self._locals = {}
        self._globalrefs = set()
        self._scope = self._globals.copy()
        self._scope.update(self._locals) 
Example #2
Source File: assertionchecker.py    From gremlinsdk-python with Apache License 2.0 6 votes vote down vote up
def check_assertions(self, checklist, all=False):
        """Check a set of assertions
        @param all boolean if False, stop at first failure
        @return: False if any assertion fails.
        """

        assert isinstance(checklist, dict) and 'checks' in checklist

        retval = None
        retlist = []

        for assertion in checklist['checks']:
            retval = self.check_assertion(**assertion)
            retlist.append(retval)
            if not retval.success and not all:
                print "Error message:", retval[3]
                return retlist

        return retlist 
Example #3
Source File: assertionchecker.py    From gremlinsdk-python with Apache License 2.0 6 votes vote down vote up
def _check_value_recursively(key, val, haystack):
    """
    Check if there is key _key_ with value _val_ in the given dictionary.
    ..warning:
        This is geared at JSON dictionaries, so some corner cases are ignored,
        we assume all iterables are either arrays or dicts
    """
    if isinstance(haystack, list):
        return any([_check_value_recursively(key, val, l) for l in haystack])
    elif isinstance(haystack, dict):
        if not key in haystack:
            return any([_check_value_recursively(key, val, d) for k, d in haystack.items()
                        if isinstance(d, list) or isinstance(d, dict)])
        else:
            return haystack[key] == val
    else:
        return False 
Example #4
Source File: util.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def dict(*a, **k):
    import __builtin__
    warnings.warn('twisted.python.util.dict is deprecated.  Use __builtin__.dict instead')
    return __builtin__.dict(*a, **k) 
Example #5
Source File: util.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, dict=None, preserve=1):
        """Create an empty dictionary, or update from 'dict'."""
        self.data = {}
        self.preserve=preserve
        if dict:
            self.update(dict) 
Example #6
Source File: util.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def update(self, dict):
        """Copy (key,value) pairs from 'dict'."""
        for k,v in dict.items():
            self[k] = v 
Example #7
Source File: util.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, dict=None, **kwargs):
        self._order = []
        self.data = {}
        if dict is not None:
            if hasattr(dict,'keys'):
                self.update(dict)
            else:
                for k,v in dict: # sequence
                    self[k] = v
        if len(kwargs):
            self.update(kwargs) 
Example #8
Source File: util.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def dict(*a, **k):
    import warnings
    import __builtin__
    warnings.warn('twisted.python.util.dict is deprecated.  Use __builtin__.dict instead')
    return __builtin__.dict(*a, **k) 
Example #9
Source File: util.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def __init__(self, dict=None, preserve=1):
        """Create an empty dictionary, or update from 'dict'."""
        self.data = {}
        self.preserve=preserve
        if dict:
            self.update(dict) 
Example #10
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _get_restricted_builtins(cls):
        bidict = dict(cls._RESTRICTED_BUILTINS)
        major = sys.version_info[0]
        if major == 2:
            bidict['True'] = True
            bidict['False'] = False
        return bidict 
Example #11
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _process_arguments(self, args, keywords):
        kwdict = dict(keywords)
        argdict = {}
        nargs = min(len(args), len(self._argnames))
        for iarg in range(nargs):
            argdict[self._argnames[iarg]] = args[iarg]
        if nargs < len(args):
            if self._varpos is None:
                msg = "macro '{0}' called with too many positional arguments "\
                      "(expected: {1}, received: {2})"\
                      .format(self._name, len(self._argnames), len(args))
                raise FyppFatalError(msg, self._fname, self._spans[0])
            else:
                argdict[self._varpos] = list(args[nargs:])
        elif self._varpos is not None:
            argdict[self._varpos] = []
        for argname in self._argnames[:nargs]:
            if argname in kwdict:
                msg = "got multiple values for argument '{0}'".format(argname)
                raise FyppFatalError(msg, self._fname, self._spans[0])
        if nargs < len(self._argnames):
            for argname in self._argnames[nargs:]:
                if argname in kwdict:
                    argdict[argname] = kwdict.pop(argname)
                elif argname in self._defaults:
                    argdict[argname] = self._defaults[argname]
                else:
                    msg = "macro '{0}' called without mandatory positional "\
                          "argument '{1}'".format(self._name, argname)
                    raise FyppFatalError(msg, self._fname, self._spans[0])
        if kwdict and self._varkw is None:
            kwstr = "', '".join(kwdict.keys())
            msg = "macro '{0}' called with unknown keyword argument(s) '{1}'"\
                  .format(self._name, kwstr)
            raise FyppFatalError(msg, self._fname, self._spans[0])
        if self._varkw is not None:
            argdict[self._varkw] = kwdict
        return argdict 
Example #12
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def process_file(self, infile, outfile=None):
        '''Processes input file and writes result to output file.

        Args:
            infile (str): Name of the file to read and process. If its value is
                '-', input is read from stdin.
            outfile (str, optional): Name of the file to write the result to.
                If its value is '-', result is written to stdout. If not
                present, result will be returned as string.
            env (dict, optional): Additional definitions for the evaluator.

        Returns:
            str: Result of processed input, if no outfile was specified.
        '''
        infile = STDIN if infile == '-' else infile
        output = self._preprocessor.process_file(infile)
        if outfile is None:
            return output
        if outfile == '-':
            outfile = sys.stdout
        else:
            outfile = _open_output_file(outfile, self._encoding,
                                        self._create_parent_folder)
        outfile.write(output)
        if outfile != sys.stdout:
            outfile.close()
        return None 
Example #13
Source File: fypp.py    From fypp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def process_text(self, txt):
        '''Processes a string.

        Args:
            txt (str): String to process.
            env (dict, optional): Additional definitions for the evaluator.

        Returns:
            str: Processed content.
        '''
        return self._preprocessor.process_text(txt) 
Example #14
Source File: DataPairMgr.py    From TransNets with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, filename):
        '''
        filename: inits the UBRR data from the input file
        '''
        
        ub_map = dict()
        ub_ratings = dict()
        
        cnt = 0
        
        #read the file
        if filename.endswith('.gz'):
            f = gzip.open(filename, 'r')
        else:
            f = open(filename, 'r')
        
        for line in f:
            vals = line.split("\t")
            if len(vals) == 0:
                continue
            
            u = vals[0]
            b = vals[1]
            r = float(vals[2])
            d = vals[3].strip()
            
            ub_map[(u,b)] = self._int_list(d)
            ub_ratings[(u,b)] = r
            
            cnt += 1
            
        
        self.user_item_map = ub_map
        self.user_item_rating = ub_ratings
        
        
        f.close()
        print 'Data Pair Manager Initialized with ', cnt, ' reviews' 
Example #15
Source File: util.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def __init__(self, dict=None, **kwargs):
        self._order = []
        self.data = {}
        if dict is not None:
            if hasattr(dict,'keys'):
                self.update(dict)
            else:
                for k,v in dict: # sequence
                    self[k] = v
        if len(kwargs):
            self.update(kwargs) 
Example #16
Source File: util.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def update(self, dict):
        """Copy (key,value) pairs from 'dict'."""
        for k,v in dict.items():
            self[k] = v 
Example #17
Source File: DataMgr.py    From TransNets with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, filename, empty_user = set()):
        '''
        filename: inits the UBRR data from the input file
        empty_user: skip the reviews by this user (keeps the ratings)
        '''
        self.empty_user = empty_user
        
        ur_map = dict()
        br_map = dict()
        
        cnt = 0
        skipped = 0
        
        #read the file
        if filename.endswith('.gz'):
            f = gzip.open(filename, 'r')
        else:
            f = open(filename, 'r')
        
        for line in f:
            vals = line.split("\t")
            if len(vals) == 0:
                continue
            
            u = vals[0]
            b = vals[1]
            r = float(vals[2])
            d = vals[3].strip()
            if u in self.empty_user:
                #we are skipping this review
                d = ''
                skipped += 1
            
            rev = Review(u, b, r, d)  #review obj
            
            
            #store biz -> list of reviews
            if not br_map.has_key(b):
                br_map[b] = []
            
            br_map[b].append(rev)
            
            #store user -> list of reviews
            if not ur_map.has_key(u):
                ur_map[u] = []
                
            ur_map[u].append(rev)
            
            cnt += 1
            
        
        self.biz_map = br_map
        self.user_map = ur_map
        
        
        f.close()
        print 'Review Data Manager Initialized with ', cnt, ' reviews'
        print 'Number of skipped users = ', len(self.empty_user)
        print 'Number of skipped reviews = ', skipped