signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
---|---|---|---|
def get_soft_bounds(self): | if self.bounds is None:<EOL><INDENT>hl,hu=(None,None)<EOL><DEDENT>else:<EOL><INDENT>hl,hu=self.bounds<EOL><DEDENT>if self.softbounds is None:<EOL><INDENT>sl,su=(None,None)<EOL><DEDENT>else:<EOL><INDENT>sl,su=self.softbounds<EOL><DEDENT>if sl is None: l = hl<EOL>else: l = sl<EOL>if su is None: u = hu<EOL>else: u = su<EOL>return (l,u)<EOL> | For each soft bound (upper and lower), if there is a defined bound (not equal to None)
then it is returned, otherwise it defaults to the hard bound. The hard bound could still be None. | f1241:c33:m2 |
def __init__(self, metaclass=False): | <EOL>self.order = ['<STR_LIT:name>', '<STR_LIT>', '<STR_LIT:value>', '<STR_LIT:type>', '<STR_LIT>', '<STR_LIT>']<EOL>self.metaclass = metaclass<EOL> | If metaclass is set to True, the checks for Parameterized
classes objects are disabled. This option is for use in
ParameterizedMetaclass for automatic docstring generation. | f1242:c0:m0 |
def get_param_info(self, obj, include_super=True): | params = dict(obj.param.objects('<STR_LIT>'))<EOL>if isinstance(obj,type):<EOL><INDENT>changed = []<EOL>val_dict = dict((k,p.default) for (k,p) in params.items())<EOL>self_class = obj<EOL><DEDENT>else:<EOL><INDENT>changed = [name for (name,_) in obj.param.get_param_values(onlychanged=True)]<EOL>val_dict = dict(obj.param.get_param_values())<EOL>self_class = obj.__class__<EOL><DEDENT>if not include_super:<EOL><INDENT>params = dict((k,v) for (k,v) in params.items()<EOL>if k in self_class.__dict__)<EOL><DEDENT>params.pop('<STR_LIT:name>') <EOL>return (params, val_dict, changed)<EOL> | Get the parameter dictionary, the list of modifed parameters
and the dictionary or parameter values. If include_super is
True, parameters are also collected from the super classes. | f1242:c0:m1 |
def param_docstrings(self, info, max_col_len=<NUM_LIT:100>, only_changed=False): | (params, val_dict, changed) = info<EOL>contents = []<EOL>displayed_params = {}<EOL>for name, p in params.items():<EOL><INDENT>if only_changed and not (name in changed):<EOL><INDENT>continue<EOL><DEDENT>displayed_params[name] = p<EOL><DEDENT>right_shift = max(len(name) for name in displayed_params.keys())+<NUM_LIT:2><EOL>for i, name in enumerate(sorted(displayed_params)):<EOL><INDENT>p = displayed_params[name]<EOL>heading = "<STR_LIT>" % name<EOL>unindented = textwrap.dedent("<STR_LIT>" if p.doc is None else p.doc)<EOL>if (WARN_MISFORMATTED_DOCSTRINGS<EOL>and not unindented.startswith("<STR_LIT:\n>") and len(unindented.splitlines()) > <NUM_LIT:1>):<EOL><INDENT>param.main.warning("<STR_LIT>"<EOL>"<STR_LIT>", name)<EOL><DEDENT>while unindented.startswith("<STR_LIT:\n>"):<EOL><INDENT>unindented = unindented[<NUM_LIT:1>:]<EOL><DEDENT>lines = unindented.splitlines()<EOL>if len(lines) > <NUM_LIT:1>:<EOL><INDENT>tail = ['<STR_LIT>' % ('<STR_LIT:U+0020>' * right_shift, line) for line in lines[<NUM_LIT:1>:]]<EOL>all_lines = [ heading.ljust(right_shift) + lines[<NUM_LIT:0>]] + tail<EOL><DEDENT>elif len(lines) == <NUM_LIT:1>:<EOL><INDENT>all_lines = [ heading.ljust(right_shift) + lines[<NUM_LIT:0>]]<EOL><DEDENT>else:<EOL><INDENT>all_lines = []<EOL><DEDENT>if i % <NUM_LIT:2>: <EOL><INDENT>contents.extend([red %el for el in all_lines])<EOL><DEDENT>else:<EOL><INDENT>contents.extend([blue %el for el in all_lines])<EOL><DEDENT><DEDENT>return "<STR_LIT:\n>".join(contents)<EOL> | Build a string to that presents all of the parameter
docstrings in a clean format (alternating red and blue for
readability). | f1242:c0:m2 |
def _build_table(self, info, order, max_col_len=<NUM_LIT>, only_changed=False): | info_dict, bounds_dict = {}, {}<EOL>(params, val_dict, changed) = info<EOL>col_widths = dict((k,<NUM_LIT:0>) for k in order)<EOL>for name, p in params.items():<EOL><INDENT>if only_changed and not (name in changed):<EOL><INDENT>continue<EOL><DEDENT>constant = '<STR_LIT:C>' if p.constant else '<STR_LIT>'<EOL>readonly = '<STR_LIT>' if p.readonly else '<STR_LIT>'<EOL>allow_None = '<STR_LIT>' if hasattr(p, '<STR_LIT>') and p.allow_None else '<STR_LIT>'<EOL>mode = '<STR_LIT>' % (constant, readonly, allow_None)<EOL>info_dict[name] = {'<STR_LIT:name>': name, '<STR_LIT:type>':p.__class__.__name__,<EOL>'<STR_LIT>':mode}<EOL>if hasattr(p, '<STR_LIT>'):<EOL><INDENT>lbound, ubound = (None,None) if p.bounds is None else p.bounds<EOL>mark_lbound, mark_ubound = False, False<EOL>if hasattr(p, '<STR_LIT>'):<EOL><INDENT>soft_lbound, soft_ubound = p.get_soft_bounds()<EOL>if lbound is None and soft_lbound is not None:<EOL><INDENT>lbound = soft_lbound<EOL>mark_lbound = True<EOL><DEDENT>if ubound is None and soft_ubound is not None:<EOL><INDENT>ubound = soft_ubound<EOL>mark_ubound = True<EOL><DEDENT><DEDENT>if (lbound, ubound) != (None,None):<EOL><INDENT>bounds_dict[name] = (mark_lbound, mark_ubound)<EOL>info_dict[name]['<STR_LIT>'] = '<STR_LIT>' % (lbound, ubound)<EOL><DEDENT><DEDENT>value = repr(val_dict[name])<EOL>if len(value) > (max_col_len - <NUM_LIT:3>):<EOL><INDENT>value = value[:max_col_len-<NUM_LIT:3>] + '<STR_LIT>'<EOL><DEDENT>info_dict[name]['<STR_LIT:value>'] = value<EOL>for col in info_dict[name]:<EOL><INDENT>max_width = max([col_widths[col], len(info_dict[name][col])])<EOL>col_widths[col] = max_width<EOL><DEDENT><DEDENT>return self._tabulate(info_dict, col_widths, changed, order, bounds_dict)<EOL> | Collect the information about parameters needed to build a
properly formatted table and then tabulate it. | f1242:c0:m3 |
def _tabulate(self, info_dict, col_widths, changed, order, bounds_dict): | contents, tail = [], []<EOL>column_set = set(k for row in info_dict.values() for k in row)<EOL>columns = [col for col in order if col in column_set]<EOL>title_row = []<EOL>for i, col in enumerate(columns):<EOL><INDENT>width = col_widths[col]+<NUM_LIT:2><EOL>col = col.capitalize()<EOL>formatted = col.ljust(width) if i == <NUM_LIT:0> else col.center(width)<EOL>title_row.append(formatted)<EOL><DEDENT>contents.append(blue % '<STR_LIT>'.join(title_row)+"<STR_LIT:\n>")<EOL>for row in sorted(info_dict):<EOL><INDENT>row_list = []<EOL>info = info_dict[row]<EOL>for i,col in enumerate(columns):<EOL><INDENT>width = col_widths[col]+<NUM_LIT:2><EOL>val = info[col] if (col in info) else '<STR_LIT>'<EOL>formatted = val.ljust(width) if i==<NUM_LIT:0> else val.center(width)<EOL>if col == '<STR_LIT>' and bounds_dict.get(row,False):<EOL><INDENT>(mark_lbound, mark_ubound) = bounds_dict[row]<EOL>lval, uval = formatted.rsplit('<STR_LIT:U+002C>')<EOL>lspace, lstr = lval.rsplit('<STR_LIT:(>')<EOL>ustr, uspace = uval.rsplit('<STR_LIT:)>')<EOL>lbound = lspace + '<STR_LIT:(>'+(cyan % lstr) if mark_lbound else lval<EOL>ubound = (cyan % ustr)+'<STR_LIT:)>'+uspace if mark_ubound else uval<EOL>formatted = "<STR_LIT>" % (lbound, ubound)<EOL><DEDENT>row_list.append(formatted)<EOL><DEDENT>row_text = '<STR_LIT>'.join(row_list)<EOL>if row in changed:<EOL><INDENT>row_text = red % row_text<EOL><DEDENT>contents.append(row_text)<EOL><DEDENT>return '<STR_LIT:\n>'.join(contents+tail)<EOL> | Returns the supplied information as a table suitable for
printing or paging.
info_dict: Dictionary of the parameters name, type and mode.
col_widths: Dictionary of column widths in characters
changed: List of parameters modified from their defaults.
order: The order of the table columns
bound_dict: Dictionary of appropriately formatted bounds | f1242:c0:m4 |
def __call__(self, param_obj): | title = None<EOL>if not self.metaclass:<EOL><INDENT>parameterized_object = isinstance(param_obj, param.Parameterized)<EOL>parameterized_class = (isinstance(param_obj,type)<EOL>and issubclass(param_obj,param.Parameterized))<EOL>if not (parameterized_object or parameterized_class):<EOL><INDENT>print("<STR_LIT>")<EOL>return<EOL><DEDENT>if parameterized_object:<EOL><INDENT>class_name = param_obj.__class__.__name__<EOL>default_name = re.match('<STR_LIT>'+class_name+'<STR_LIT>', param_obj.name)<EOL>obj_name = '<STR_LIT>' if default_name else ('<STR_LIT>' % param_obj.name)<EOL>title = '<STR_LIT>' % (class_name, obj_name)<EOL><DEDENT><DEDENT>if title is None:<EOL><INDENT>title = '<STR_LIT>' % param_obj.name<EOL><DEDENT>heading_line = '<STR_LIT:=>' * len(title)<EOL>heading_text = "<STR_LIT>" % (title, heading_line)<EOL>param_info = self.get_param_info(param_obj, include_super=True)<EOL>if not param_info[<NUM_LIT:0>]:<EOL><INDENT>return "<STR_LIT>" % ((green % heading_text), "<STR_LIT>")<EOL><DEDENT>table = self._build_table(param_info, self.order, max_col_len=<NUM_LIT>,<EOL>only_changed=False)<EOL>docstrings = self.param_docstrings(param_info, max_col_len=<NUM_LIT:100>, only_changed=False)<EOL>dflt_msg = "<STR_LIT>"<EOL>top_heading = (green % heading_text)<EOL>top_heading += "<STR_LIT>" % (red % dflt_msg)<EOL>top_heading += "<STR_LIT>" % (cyan % "<STR_LIT>")<EOL>top_heading += '<STR_LIT>'<EOL>heading_text = '<STR_LIT>'<EOL>heading_string = "<STR_LIT>" % (heading_text, '<STR_LIT:=>' * len(heading_text))<EOL>docstring_heading = (green % heading_string)<EOL>return "<STR_LIT>" % (top_heading, table, docstring_heading, docstrings)<EOL> | Given a Parameterized object or class, display information
about the parameters in the IPython pager. | f1242:c0:m5 |
def emit(self, record): | self.acquire()<EOL>try:<EOL><INDENT>self.messages[record.levelname].append(record.getMessage())<EOL><DEDENT>finally:<EOL><INDENT>self.release()<EOL><DEDENT> | Store a message to the instance's messages dictionary | f1283:c0:m1 |
def tail(self, level, n=<NUM_LIT:1>): | return [str(el) for el in self.messages[level][-n:]]<EOL> | Returns the last n lines captured at the given level | f1283:c0:m3 |
def assertEndsWith(self, level, substring): | msg='<STR_LIT>'<EOL>last_line = self.tail(level, n=<NUM_LIT:1>)<EOL>if len(last_line) == <NUM_LIT:0>:<EOL><INDENT>raise AssertionError('<STR_LIT>'.format(<EOL>method=self.param_methods[level], substring=repr(substring)))<EOL><DEDENT>if not last_line[<NUM_LIT:0>].endswith(substring):<EOL><INDENT>raise AssertionError(msg.format(method=self.param_methods[level],<EOL>last_line=repr(last_line[<NUM_LIT:0>]),<EOL>substring=repr(substring)))<EOL><DEDENT> | Assert that the last line captured at the given level ends with
a particular substring. | f1283:c0:m4 |
def assertContains(self, level, substring): | msg='<STR_LIT>'<EOL>last_line = self.tail(level, n=<NUM_LIT:1>)<EOL>if len(last_line) == <NUM_LIT:0>:<EOL><INDENT>raise AssertionError('<STR_LIT>'.format(<EOL>method=self.param_methods[level], substring=repr(substring)))<EOL><DEDENT>if substring not in last_line[<NUM_LIT:0>]:<EOL><INDENT>raise AssertionError(msg.format(method=self.param_methods[level],<EOL>last_line=repr(last_line[<NUM_LIT:0>]),<EOL>substring=repr(substring)))<EOL><DEDENT> | Assert that the last line captured at the given level contains a
particular substring. | f1283:c0:m5 |
def get_setup_version(reponame): | <EOL>from param.version import Version<EOL>return Version.setup_version(os.path.dirname(__file__),reponame,archive_commit="<STR_LIT>")<EOL> | Use autover to get up to date version. | f1288:m0 |
def _check_time_fn(self, time_instance=False): | if time_instance and not isinstance(self.time_fn, param.Time):<EOL><INDENT>raise AssertionError("<STR_LIT>"<EOL>% self.__class__.__name__)<EOL><DEDENT>if self.time_dependent:<EOL><INDENT>global_timefn = self.time_fn is param.Dynamic.time_fn<EOL>if global_timefn and not param.Dynamic.time_dependent:<EOL><INDENT>raise AssertionError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT> | If time_fn is the global time function supplied by
param.Dynamic.time_fn, make sure Dynamic parameters are using
this time function to control their behaviour.
If time_instance is True, time_fn must be a param.Time instance. | f1289:c0:m1 |
def __init__(self,lhs,rhs,operator,reverse=False,**args): | <EOL>super(BinaryOperator,self).__init__()<EOL>if reverse:<EOL><INDENT>self.lhs=rhs<EOL>self.rhs=lhs<EOL><DEDENT>else:<EOL><INDENT>self.lhs=lhs<EOL>self.rhs=rhs<EOL><DEDENT>self.operator=operator<EOL>self.args=args<EOL> | Accepts two NumberGenerator operands, an operator, and
optional arguments to be provided to the operator when calling
it on the two operands. | f1289:c3:m0 |
def __init__(self,operand,operator,**args): | <EOL>super(UnaryOperator,self).__init__()<EOL>self.operand=operand<EOL>self.operator=operator<EOL>self.args=args<EOL> | Accepts a NumberGenerator operand, an operator, and
optional arguments to be provided to the operator when calling
it on the operand. | f1289:c4:m0 |
def _rational(self, val): | I32 = <NUM_LIT> <EOL>if isinstance(val, int):<EOL><INDENT>numer, denom = val, <NUM_LIT:1><EOL><DEDENT>elif isinstance(val, fractions.Fraction):<EOL><INDENT>numer, denom = val.numerator, val.denominator<EOL><DEDENT>elif hasattr(val, '<STR_LIT>'):<EOL><INDENT>(numer, denom) = (int(val.numer()), int(val.denom()))<EOL><DEDENT>else:<EOL><INDENT>param.main.param.warning("<STR_LIT>"<EOL>% type(val).__name__)<EOL>frac = fractions.Fraction(str(val))<EOL>numer, denom = frac.numerator, frac.denominator<EOL><DEDENT>return numer % I32, denom % I32<EOL> | Convert the given value to a rational, if necessary. | f1289:c5:m1 |
def __getstate__(self): | d = self.__dict__.copy()<EOL>d.pop('<STR_LIT>')<EOL>d.pop('<STR_LIT>')<EOL>return d<EOL> | Avoid Hashlib.md5 TypeError in deepcopy (hashlib issue) | f1289:c5:m2 |
def __call__(self, *vals): | <EOL>pairs = [self._rational(val) for val in vals]<EOL>ints = [el for pair in pairs for el in pair]<EOL>digest = self._digest.copy()<EOL>digest.update(self._hash_struct.pack(*ints))<EOL>return int(digest.hexdigest()[:<NUM_LIT:7>], <NUM_LIT:16>)<EOL> | Given integer or rational inputs, generate a cross-platform,
architecture-independent 32-bit integer hash. | f1289:c5:m4 |
def _initialize_random_state(self, seed=None, shared=True, name=None): | if seed is None: <EOL><INDENT>seed = random.Random().randint(<NUM_LIT:0>, <NUM_LIT>)<EOL>suffix = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>suffix = str(seed)<EOL><DEDENT>if self.time_dependent or not shared:<EOL><INDENT>self.random_generator = type(self.random_generator)(seed)<EOL><DEDENT>if not shared:<EOL><INDENT>self.random_generator.seed(seed)<EOL><DEDENT>if name is None:<EOL><INDENT>self._verify_constrained_hash()<EOL><DEDENT>hash_name = name if name else self.name<EOL>if not shared: hash_name += suffix<EOL>self._hashfn = Hash(hash_name, input_count=<NUM_LIT:2>)<EOL>if self.time_dependent:<EOL><INDENT>self._hash_and_seed()<EOL><DEDENT> | Initialization method to be called in the constructor of
subclasses to initialize the random state correctly.
If seed is None, there is no control over the random stream
(no reproducibility of the stream).
If shared is True (and not time-dependent), the random state
is shared across all objects of the given class. This can be
overridden per object by creating new random state to assign
to the random_generator parameter. | f1289:c6:m0 |
def _verify_constrained_hash(self): | changed_params = dict(self.param.get_param_values(onlychanged=True))<EOL>if self.time_dependent and ('<STR_LIT:name>' not in changed_params):<EOL><INDENT>self.param.warning("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT> | Warn if the object name is not explicitly set. | f1289:c6:m1 |
def _hash_and_seed(self): | hashval = self._hashfn(self.time_fn(), param.random_seed)<EOL>self.random_generator.seed(hashval)<EOL> | To be called between blocks of random number generation. A
'block' can be an unbounded sequence of random numbers so long
as the time value (as returned by time_fn) is guaranteed not
to change within the block. If this condition holds, each
block of random numbers is time-dependent.
Note: param.random_seed is assumed to be integer or rational. | f1289:c6:m2 |
def __init__(self,**params): | super(RandomDistribution,self).__init__(**params)<EOL>self._initialize_random_state(seed=self.seed, shared=False)<EOL> | Initialize a new Random() instance and store the supplied
positional and keyword arguments.
If seed=X is specified, sets the Random() instance's seed.
Otherwise, calls creates an unseeded Random instance which is
likely to result in a state very different from any just used. | f1289:c7:m0 |
def __init__(self, worker, **kwargs): | worker.app.listenclosely_app = ListenCloselyApp(import_string(conf.LISTENCLOSELY_MESSAGE_SERVICE_BACKEND),<EOL>import_string(conf.LISTENCLOSELY_AGENT_STRATEGY),<EOL>int(conf.LISTENCLOSELY_QUERY_TIME_OBSOLETE))<EOL>logger.info("<STR_LIT>")<EOL> | :param worker: celery worker | f1294:c0:m0 |
def send_message(self, id_service, content): | if not content:<EOL><INDENT>return<EOL><DEDENT>with self._lock:<EOL><INDENT>try:<EOL><INDENT>message = "<STR_LIT>" % (content, id_service)<EOL>self.write_message(message)<EOL>self.stream.flush() <EOL>return "<STR_LIT>"<EOL><DEDENT>except Exception:<EOL><INDENT>if not self.fail_silently:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT> | Write all messages to the stream in a thread-safe way. | f1298:c0:m2 |
def listen(self): | raise NotImplementedError('<STR_LIT>')<EOL> | Connect to service and listen for receive messages.
To implement in concrete services | f1299:c0:m1 |
def send_message(self, id_service, content): | raise NotImplementedError('<STR_LIT>')<EOL> | Send message to a instant messages service
To implement in concrete services
:rtype string message_id: identifier for message service | f1299:c0:m2 |
def disconnect(self): | raise NotImplementedError('<STR_LIT>')<EOL> | Disconnect to service.
To implement in concrete services | f1299:c0:m3 |
@transition(field=state, source=OFFLINE, target=ONLINE)<EOL><INDENT>def register(self):<DEDENT> | Agent is registered into the system so now is online to answers | f1302:c3:m1 |
|
@transition(field=state, source=ONLINE, target=OFFLINE)<EOL><INDENT>def unregister(self):<DEDENT> | Agent is not online anymore | f1302:c3:m2 |
|
@transition(field=state, source=ONLINE, target=BUSY)<EOL><INDENT>def attend(self, chat):<DEDENT> | chat.agent = self<EOL> | Agent is assigned to a chat so it is busy answering | f1302:c3:m3 |
@transition(field=state, source=BUSY, target=ONLINE)<EOL><INDENT>def release(self, chat):<DEDENT> | Agent finishes chat | f1302:c3:m4 |
|
@transition(field=state, source=LIVE, target=TERMINATED)<EOL><INDENT>def terminate(self):<DEDENT> | self.agent.release(self)<EOL>self.agent.save()<EOL> | Chat is finished and Agent is free | f1302:c4:m3 |
def is_obsolete(self, time_offset): | return now() > datetime.timedelta(seconds=time_offset) + self.last_modified<EOL> | Check if chat is obsolete | f1302:c4:m4 |
def listen(self): | self.listening = True<EOL>try:<EOL><INDENT>self.service_backend.listen()<EOL><DEDENT>except AuthenticationError:<EOL><INDENT>self.listening = False<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>self.listening = False<EOL><DEDENT> | Listen/Connect to message service loop to start receiving messages.
Do not include in constructor, in this way it can be included in tasks | f1304:c0:m1 |
def disconnect(self): | try:<EOL><INDENT>self.service_backend.disconnect()<EOL><DEDENT>except ConnectionError:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>self.listening = False<EOL><DEDENT> | Disconnect and not listen anymore | f1304:c0:m2 |
def attend_pendings(self): | chats_attended = []<EOL>pending_chats = Chat.pending.all()<EOL>for pending_chat in pending_chats:<EOL><INDENT>free_agent = self.strategy.free_agent() <EOL>if free_agent:<EOL><INDENT>pending_chat.attend_pending(free_agent, self)<EOL>pending_chat.save()<EOL>chats_attended.append(pending_chat)<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return chats_attended<EOL> | Check all chats created with no agent assigned yet.
Schedule a timer timeout to call it. | f1304:c0:m3 |
def terminate_obsolete(self): | chats_terminated = []<EOL>live_chats = Chat.live.all()<EOL>for live_chat in live_chats:<EOL><INDENT>if live_chat.is_obsolete(self.time_obsolete_offset):<EOL><INDENT>live_chat.terminate()<EOL>live_chat.save()<EOL>chats_terminated.append(live_chat)<EOL><DEDENT><DEDENT>return chats_terminated<EOL> | Check chats can be considered as obsolete to terminate them | f1304:c0:m4 |
def on_message(self, message_id_service, contact_id_service, content): | try:<EOL><INDENT>live_chat = Chat.live.get(<EOL>Q(agent__id_service=contact_id_service) | Q(asker__id_service=contact_id_service)) <EOL><DEDENT>except ObjectDoesNotExist:<EOL><INDENT>self._new_chat_processing(message_id_service, contact_id_service, content)<EOL><DEDENT>else:<EOL><INDENT>live_chat.handle_message(message_id_service, contact_id_service, content, self)<EOL><DEDENT> | To use as callback in message service backend | f1304:c0:m7 |
def login(self): | if not self.auth.access_token or(hasattr(self.auth, '<STR_LIT>') and self.auth.access_token_expired):<EOL><INDENT>import httplib2<EOL>http = httplib2.Http()<EOL>self.auth.refresh(http)<EOL><DEDENT>self.session.headers.update({<EOL>'<STR_LIT>': '<STR_LIT>' % self.auth.access_token<EOL>})<EOL> | Authorize client. | f1319:c0:m1 |
def open(self, title): | try:<EOL><INDENT>properties = finditem(<EOL>lambda x: x['<STR_LIT:name>'] == title,<EOL>self.list_spreadsheet_files()<EOL>)<EOL>properties['<STR_LIT:title>'] = properties['<STR_LIT:name>']<EOL>return Spreadsheet(self, properties)<EOL><DEDENT>except StopIteration:<EOL><INDENT>raise SpreadsheetNotFound<EOL><DEDENT> | Opens a spreadsheet.
:param title: A title of a spreadsheet.
:type title: str
:returns: a :class:`~gspread.models.Spreadsheet` instance.
If there's more than one spreadsheet with same title the first one
will be opened.
:raises gspread.SpreadsheetNotFound: if no spreadsheet with
specified `title` is found.
>>> c = gspread.authorize(credentials)
>>> c.open('My fancy spreadsheet') | f1319:c0:m4 |
def open_by_key(self, key): | return Spreadsheet(self, {'<STR_LIT:id>': key})<EOL> | Opens a spreadsheet specified by `key`.
:param key: A key of a spreadsheet as it appears in a URL in a browser.
:type key: str
:returns: a :class:`~gspread.models.Spreadsheet` instance.
>>> c = gspread.authorize(credentials)
>>> c.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE') | f1319:c0:m5 |
def open_by_url(self, url): | return self.open_by_key(extract_id_from_url(url))<EOL> | Opens a spreadsheet specified by `url`.
:param url: URL of a spreadsheet as it appears in a browser.
:type url: str
:returns: a :class:`~gspread.models.Spreadsheet` instance.
:raises gspread.SpreadsheetNotFound: if no spreadsheet with
specified `url` is found.
>>> c = gspread.authorize(credentials)
>>> c.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm...FE&hl') | f1319:c0:m6 |
def openall(self, title=None): | spreadsheet_files = self.list_spreadsheet_files()<EOL>return [<EOL>Spreadsheet(self, dict(title=x['<STR_LIT:name>'], **x))<EOL>for x in spreadsheet_files<EOL>]<EOL> | Opens all available spreadsheets.
:param title: (optional) If specified can be used to filter
spreadsheets by title.
:type title: str
:returns: a list of :class:`~gspread.models.Spreadsheet` instances. | f1319:c0:m7 |
def create(self, title): | payload = {<EOL>'<STR_LIT:title>': title,<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>r = self.request(<EOL>'<STR_LIT>',<EOL>DRIVE_FILES_API_V2_URL,<EOL>json=payload<EOL>)<EOL>spreadsheet_id = r.json()['<STR_LIT:id>']<EOL>return self.open_by_key(spreadsheet_id)<EOL> | Creates a new spreadsheet.
:param title: A title of a new spreadsheet.
:type title: str
:returns: a :class:`~gspread.models.Spreadsheet` instance.
.. note::
In order to use this method, you need to add
``https://www.googleapis.com/auth/drive`` to your oAuth scope.
Example::
scope = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive'
]
Otherwise you will get an ``Insufficient Permission`` error
when you try to create a new spreadsheet. | f1319:c0:m8 |
def copy(self, file_id, title=None, copy_permissions=False): | url = '<STR_LIT>'.format(<EOL>DRIVE_FILES_API_V2_URL,<EOL>file_id<EOL>)<EOL>payload = {<EOL>'<STR_LIT:title>': title,<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>r = self.request(<EOL>'<STR_LIT>',<EOL>url,<EOL>json=payload<EOL>)<EOL>spreadsheet_id = r.json()['<STR_LIT:id>']<EOL>new_spreadsheet = self.open_by_key(spreadsheet_id)<EOL>if copy_permissions:<EOL><INDENT>original = self.open_by_key(file_id)<EOL>permissions = original.list_permissions()<EOL>for p in permissions:<EOL><INDENT>if p.get('<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>new_spreadsheet.share(<EOL>value=p['<STR_LIT>'],<EOL>perm_type=p['<STR_LIT:type>'],<EOL>role=p['<STR_LIT>'],<EOL>notify=False<EOL>)<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>return new_spreadsheet<EOL> | Copies a spreadsheet.
:param file_id: A key of a spreadsheet to copy.
:type title: str
:param title: (optional) A title for the new spreadsheet.
:type title: str
:param copy_permissions: (optional) If True, copy permissions from
original spreadsheet to new spreadsheet.
:type copy_permissions: bool
:returns: a :class:`~gspread.models.Spreadsheet` instance.
.. versionadded:: 3.1.0
.. note::
In order to use this method, you need to add
``https://www.googleapis.com/auth/drive`` to your oAuth scope.
Example::
scope = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive'
]
Otherwise you will get an ``Insufficient Permission`` error
when you try to copy a spreadsheet. | f1319:c0:m9 |
def del_spreadsheet(self, file_id): | url = '<STR_LIT>'.format(<EOL>DRIVE_FILES_API_V2_URL,<EOL>file_id<EOL>)<EOL>self.request('<STR_LIT>', url)<EOL> | Deletes a spreadsheet.
:param file_id: a spreadsheet ID (aka file ID.)
:type file_id: str | f1319:c0:m10 |
def import_csv(self, file_id, data): | headers = {'<STR_LIT:Content-Type>': '<STR_LIT>'}<EOL>url = '<STR_LIT>'.format(DRIVE_FILES_UPLOAD_API_V2_URL, file_id)<EOL>self.request(<EOL>'<STR_LIT>',<EOL>url,<EOL>data=data,<EOL>params={<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': True<EOL>},<EOL>headers=headers<EOL>)<EOL> | Imports data into the first page of the spreadsheet.
:param str data: A CSV string of data.
Example:
.. code::
# Read CSV file contents
content = open('file_to_import.csv', 'r').read()
gc.import_csv(spreadsheet.id, content)
.. note::
This method removes all other worksheets and then entirely
replaces the contents of the first worksheet. | f1319:c0:m11 |
def list_permissions(self, file_id): | url = '<STR_LIT>'.format(DRIVE_FILES_API_V2_URL, file_id)<EOL>r = self.request('<STR_LIT>', url)<EOL>return r.json()['<STR_LIT>']<EOL> | Retrieve a list of permissions for a file.
:param file_id: a spreadsheet ID (aka file ID.)
:type file_id: str | f1319:c0:m12 |
def insert_permission(<EOL>self,<EOL>file_id,<EOL>value,<EOL>perm_type,<EOL>role,<EOL>notify=True,<EOL>email_message=None,<EOL>with_link=False<EOL>): | url = '<STR_LIT>'.format(DRIVE_FILES_API_V2_URL, file_id)<EOL>payload = {<EOL>'<STR_LIT:value>': value,<EOL>'<STR_LIT:type>': perm_type,<EOL>'<STR_LIT>': role,<EOL>'<STR_LIT>': with_link<EOL>}<EOL>params = {<EOL>'<STR_LIT>': notify,<EOL>'<STR_LIT>': email_message<EOL>}<EOL>self.request(<EOL>'<STR_LIT>',<EOL>url,<EOL>json=payload,<EOL>params=params<EOL>)<EOL> | Creates a new permission for a file.
:param file_id: a spreadsheet ID (aka file ID.)
:type file_id: str
:param value: user or group e-mail address, domain name
or None for 'default' type.
:type value: str, None
:param perm_type: (optional) The account type.
Allowed values are: ``user``, ``group``, ``domain``,
``anyone``
:type perm_type: str
:param role: (optional) The primary role for this user.
Allowed values are: ``owner``, ``writer``, ``reader``
:type str:
:param notify: (optional) Whether to send an email to the target user/domain.
:type notify: str
:param email_message: (optional) An email message to be sent if notify=True.
:type email_message: str
:param with_link: (optional) Whether the link is required for this permission to be active.
:type with_link: bool
Examples::
# Give write permissions to otto@example.com
gc.insert_permission(
'0BmgG6nO_6dprnRRUWl1UFE',
'otto@example.org',
perm_type='user',
role='writer'
)
# Make the spreadsheet publicly readable
gc.insert_permission(
'0BmgG6nO_6dprnRRUWl1UFE',
None,
perm_type='anyone',
role='reader'
) | f1319:c0:m13 |
def remove_permission(self, file_id, permission_id): | url = '<STR_LIT>'.format(<EOL>DRIVE_FILES_API_V2_URL,<EOL>file_id,<EOL>permission_id<EOL>)<EOL>self.request('<STR_LIT>', url)<EOL> | Deletes a permission from a file.
:param file_id: a spreadsheet ID (aka file ID.)
:type file_id: str
:param permission_id: an ID for the permission.
:type permission_id: str | f1319:c0:m14 |
def authorize(credentials, client_class=Client): | client = client_class(auth=credentials)<EOL>client.login()<EOL>return client<EOL> | Login to Google API using OAuth2 credentials.
This is a shortcut function which
instantiates :class:`gspread.client.Client`
and performs login right away.
:returns: :class:`gspread.Client` instance. | f1320:m0 |
def finditem(func, seq): | return next((item for item in seq if func(item)))<EOL> | Finds and returns first item in iterable for which func(item) is True. | f1322:m0 |
def numericise(value, empty2zero=False, default_blank="<STR_LIT>", allow_underscores_in_numeric_literals=False): | if value is not None:<EOL><INDENT>if "<STR_LIT:_>" in value and not allow_underscores_in_numeric_literals:<EOL><INDENT>return value<EOL><DEDENT>try:<EOL><INDENT>value = int(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>try:<EOL><INDENT>value = float(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>if value == "<STR_LIT>":<EOL><INDENT>if empty2zero:<EOL><INDENT>value = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>value = default_blank<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return value<EOL> | Returns a value that depends on the input string:
- Float if input can be converted to Float
- Integer if input can be converted to integer
- Zero if the input string is empty and empty2zero flag is set
- The same input string, empty or not, otherwise.
Executable examples:
>>> numericise("faa")
'faa'
>>> numericise("3")
3
>>> numericise("3_2", allow_underscores_in_numeric_literals=False)
'3_2'
>>> numericise("3_2", allow_underscores_in_numeric_literals=True)
'32'
>>> numericise("3.1")
3.1
>>> numericise("", empty2zero=True)
0
>>> numericise("", empty2zero=False)
''
>>> numericise("", default_blank=None)
>>>
>>> numericise("", default_blank="foo")
'foo'
>>> numericise("")
''
>>> numericise(None)
>>> | f1322:m1 |
def numericise_all(input, empty2zero=False, default_blank="<STR_LIT>", allow_underscores_in_numeric_literals=False): | return [numericise(s, empty2zero, default_blank, allow_underscores_in_numeric_literals) for s in input]<EOL> | Returns a list of numericised values from strings | f1322:m2 |
def rowcol_to_a1(row, col): | row = int(row)<EOL>col = int(col)<EOL>if row < <NUM_LIT:1> or col < <NUM_LIT:1>:<EOL><INDENT>raise IncorrectCellLabel('<STR_LIT>' % (row, col))<EOL><DEDENT>div = col<EOL>column_label = '<STR_LIT>'<EOL>while div:<EOL><INDENT>(div, mod) = divmod(div, <NUM_LIT>)<EOL>if mod == <NUM_LIT:0>:<EOL><INDENT>mod = <NUM_LIT><EOL>div -= <NUM_LIT:1><EOL><DEDENT>column_label = chr(mod + MAGIC_NUMBER) + column_label<EOL><DEDENT>label = '<STR_LIT>' % (column_label, row)<EOL>return label<EOL> | Translates a row and column cell address to A1 notation.
:param row: The row of the cell to be converted.
Rows start at index 1.
:type row: int, str
:param col: The column of the cell to be converted.
Columns start at index 1.
:type row: int, str
:returns: a string containing the cell's coordinates in A1 notation.
Example:
>>> rowcol_to_a1(1, 1)
A1 | f1322:m3 |
def a1_to_rowcol(label): | m = CELL_ADDR_RE.match(label)<EOL>if m:<EOL><INDENT>column_label = m.group(<NUM_LIT:1>).upper()<EOL>row = int(m.group(<NUM_LIT:2>))<EOL>col = <NUM_LIT:0><EOL>for i, c in enumerate(reversed(column_label)):<EOL><INDENT>col += (ord(c) - MAGIC_NUMBER) * (<NUM_LIT> ** i)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise IncorrectCellLabel(label)<EOL><DEDENT>return (row, col)<EOL> | Translates a cell's address in A1 notation to a tuple of integers.
:param label: A cell label in A1 notation, e.g. 'B1'.
Letter case is ignored.
:type label: str
:returns: a tuple containing `row` and `column` numbers. Both indexed
from 1 (one).
Example:
>>> a1_to_rowcol('A1')
(1, 1) | f1322:m4 |
def cast_to_a1_notation(method): | @wraps(method)<EOL>def wrapper(self, *args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>if len(args):<EOL><INDENT>int(args[<NUM_LIT:0>])<EOL><DEDENT>range_start = rowcol_to_a1(*args[:<NUM_LIT:2>])<EOL>range_end = rowcol_to_a1(*args[-<NUM_LIT:2>:])<EOL>range_name = '<STR_LIT::>'.join((range_start, range_end))<EOL>args = (range_name,) + args[<NUM_LIT:4>:]<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>return method(self, *args, **kwargs)<EOL><DEDENT>return wrapper<EOL> | Decorator function casts wrapped arguments to A1 notation
in range method calls. | f1322:m5 |
def wid_to_gid(wid): | widval = wid[<NUM_LIT:1>:] if len(wid) > <NUM_LIT:3> else wid<EOL>xorval = <NUM_LIT> if len(wid) > <NUM_LIT:3> else <NUM_LIT><EOL>return str(int(widval, <NUM_LIT>) ^ xorval)<EOL> | Calculate gid of a worksheet from its wid. | f1322:m7 |
@property<EOL><INDENT>def id(self):<DEDENT> | return self._properties['<STR_LIT:id>']<EOL> | Spreadsheet ID. | f1323:c0:m1 |
@property<EOL><INDENT>def title(self):<DEDENT> | try:<EOL><INDENT>return self._properties['<STR_LIT:title>']<EOL><DEDENT>except KeyError:<EOL><INDENT>metadata = self.fetch_sheet_metadata()<EOL>self._properties.update(metadata['<STR_LIT>'])<EOL>return self._properties['<STR_LIT:title>']<EOL><DEDENT> | Spreadsheet title. | f1323:c0:m2 |
@property<EOL><INDENT>def updated(self):<DEDENT> | import warnings<EOL>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>DeprecationWarning,<EOL>stacklevel=<NUM_LIT:2><EOL>)<EOL> | .. deprecated:: 2.0
This feature is not supported in Sheets API v4. | f1323:c0:m3 |
@property<EOL><INDENT>def sheet1(self):<DEDENT> | return self.get_worksheet(<NUM_LIT:0>)<EOL> | Shortcut property for getting the first worksheet. | f1323:c0:m4 |
def batch_update(self, body): | r = self.client.request(<EOL>'<STR_LIT>',<EOL>SPREADSHEET_BATCH_UPDATE_URL % self.id,<EOL>json=body<EOL>)<EOL>return r.json()<EOL> | Lower-level method that directly calls `spreadsheets.batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate>`_.
:param dict body: `Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#request-body>`_.
:returns: `Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#response-body>`_.
:rtype: dict
.. versionadded:: 3.0 | f1323:c0:m7 |
def values_append(self, range, params, body): | url = SPREADSHEET_VALUES_APPEND_URL % (self.id, quote(range))<EOL>r = self.client.request('<STR_LIT>', url, params=params, json=body)<EOL>return r.json()<EOL> | Lower-level method that directly calls `spreadsheets.values.append <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append>`_.
:param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_
of a range to search for a logical table of data. Values will be appended after the last row of the table.
:param dict params: `Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#query-parameters>`_.
:param dict body: `Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#request-body>`_.
:returns: `Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#response-body>`_.
:rtype: dict
.. versionadded:: 3.0 | f1323:c0:m8 |
def values_clear(self, range): | url = SPREADSHEET_VALUES_CLEAR_URL % (self.id, quote(range))<EOL>r = self.client.request('<STR_LIT>', url)<EOL>return r.json()<EOL> | Lower-level method that directly calls `spreadsheets.values.clear <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear>`_.
:param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to clear.
:returns: `Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear#response-body>`_.
:rtype: dict
.. versionadded:: 3.0 | f1323:c0:m9 |
def values_get(self, range, params=None): | url = SPREADSHEET_VALUES_URL % (self.id, quote(range))<EOL>r = self.client.request('<STR_LIT>', url, params=params)<EOL>return r.json()<EOL> | Lower-level method that directly calls `spreadsheets.values.get <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get>`_.
:param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to retrieve.
:param dict params: (optional) `Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#query-parameters>`_.
:returns: `Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get#response-body>`_.
:rtype: dict
.. versionadded:: 3.0 | f1323:c0:m10 |
def values_update(self, range, params=None, body=None): | url = SPREADSHEET_VALUES_URL % (self.id, quote(range))<EOL>r = self.client.request('<STR_LIT>', url, params=params, json=body)<EOL>return r.json()<EOL> | Lower-level method that directly calls `spreadsheets.values.update <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update>`_.
:param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to update.
:param dict params: (optional) `Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#query-parameters>`_.
:param dict body: (optional) `Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#request-body>`_.
:returns: `Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#response-body>`_.
:rtype: dict
Example::
sh.values_update(
'Sheet1!A2',
params={
'valueInputOption': 'USER_ENTERED'
},
body={
'values': [[1, 2, 3]]
}
)
.. versionadded:: 3.0 | f1323:c0:m11 |
def get_worksheet(self, index): | sheet_data = self.fetch_sheet_metadata()<EOL>try:<EOL><INDENT>properties = sheet_data['<STR_LIT>'][index]['<STR_LIT>']<EOL>return Worksheet(self, properties)<EOL><DEDENT>except (KeyError, IndexError):<EOL><INDENT>return None<EOL><DEDENT> | Returns a worksheet with specified `index`.
:param index: An index of a worksheet. Indexes start from zero.
:type index: int
:returns: an instance of :class:`gsperad.models.Worksheet`
or `None` if the worksheet is not found.
Example. To get first worksheet of a spreadsheet:
>>> sht = client.open('My fancy spreadsheet')
>>> worksheet = sht.get_worksheet(0) | f1323:c0:m13 |
def worksheets(self): | sheet_data = self.fetch_sheet_metadata()<EOL>return [Worksheet(self, x['<STR_LIT>']) for x in sheet_data['<STR_LIT>']]<EOL> | Returns a list of all :class:`worksheets <gsperad.models.Worksheet>`
in a spreadsheet. | f1323:c0:m14 |
def worksheet(self, title): | sheet_data = self.fetch_sheet_metadata()<EOL>try:<EOL><INDENT>item = finditem(<EOL>lambda x: x['<STR_LIT>']['<STR_LIT:title>'] == title,<EOL>sheet_data['<STR_LIT>']<EOL>)<EOL>return Worksheet(self, item['<STR_LIT>'])<EOL><DEDENT>except (StopIteration, KeyError):<EOL><INDENT>raise WorksheetNotFound(title)<EOL><DEDENT> | Returns a worksheet with specified `title`.
:param title: A title of a worksheet. If there're multiple
worksheets with the same title, first one will
be returned.
:type title: int
:returns: an instance of :class:`gsperad.models.Worksheet`.
Example. Getting worksheet named 'Annual bonuses'
>>> sht = client.open('Sample one')
>>> worksheet = sht.worksheet('Annual bonuses') | f1323:c0:m15 |
def add_worksheet(self, title, rows, cols): | body = {<EOL>'<STR_LIT>': [{<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': {<EOL>'<STR_LIT:title>': title,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': rows,<EOL>'<STR_LIT>': cols<EOL>}<EOL>}<EOL>}<EOL>}]<EOL>}<EOL>data = self.batch_update(body)<EOL>properties = data['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>']['<STR_LIT>']<EOL>worksheet = Worksheet(self, properties)<EOL>return worksheet<EOL> | Adds a new worksheet to a spreadsheet.
:param title: A title of a new worksheet.
:type title: str
:param rows: Number of rows.
:type rows: int
:param cols: Number of columns.
:type cols: int
:returns: a newly created :class:`worksheets <gsperad.models.Worksheet>`. | f1323:c0:m16 |
def duplicate_sheet(<EOL>self,<EOL>source_sheet_id,<EOL>insert_sheet_index=None,<EOL>new_sheet_id=None,<EOL>new_sheet_name=None<EOL>): | body = {<EOL>'<STR_LIT>': [{<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': source_sheet_id,<EOL>'<STR_LIT>': insert_sheet_index,<EOL>'<STR_LIT>': new_sheet_id,<EOL>'<STR_LIT>': new_sheet_name<EOL>}<EOL>}]<EOL>}<EOL>data = self.batch_update(body)<EOL>properties = data['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>']['<STR_LIT>']<EOL>worksheet = Worksheet(self, properties)<EOL>return worksheet<EOL> | Duplicates the contents of a sheet.
:param int source_sheet_id: The sheet ID to duplicate.
:param int insert_sheet_index: (optional) The zero-based index
where the new sheet should be inserted.
The index of all sheets after this are
incremented.
:param int new_sheet_id: (optional) The ID of the new sheet.
If not set, an ID is chosen. If set, the ID
must not conflict with any existing sheet ID.
If set, it must be non-negative.
:param str new_sheet_name: (optional) The name of the new sheet.
If empty, a new name is chosen for you.
:returns: a newly created :class:`<gspread.models.Worksheet>`.
.. versionadded:: 3.1.0 | f1323:c0:m17 |
def del_worksheet(self, worksheet): | body = {<EOL>'<STR_LIT>': [{<EOL>'<STR_LIT>': {'<STR_LIT>': worksheet._properties['<STR_LIT>']}<EOL>}]<EOL>}<EOL>return self.batch_update(body)<EOL> | Deletes a worksheet from a spreadsheet.
:param worksheet: The worksheet to be deleted.
:type worksheet: :class:`~gspread.Worksheet` | f1323:c0:m18 |
def share(self, value, perm_type, role, notify=True, email_message=None, with_link=False): | self.client.insert_permission(<EOL>self.id,<EOL>value=value,<EOL>perm_type=perm_type,<EOL>role=role,<EOL>notify=notify,<EOL>email_message=email_message,<EOL>with_link=with_link<EOL>)<EOL> | Share the spreadsheet with other accounts.
:param value: user or group e-mail address, domain name
or None for 'default' type.
:type value: str, None
:param perm_type: The account type.
Allowed values are: ``user``, ``group``, ``domain``,
``anyone``.
:type perm_type: str
:param role: The primary role for this user.
Allowed values are: ``owner``, ``writer``, ``reader``.
:type role: str
:param notify: (optional) Whether to send an email to the target user/domain.
:type notify: str
:param email_message: (optional) The email to be sent if notify=True
:type email_message: str
:param with_link: (optional) Whether the link is required for this permission
:type with_link: bool
Example::
# Give Otto a write permission on this spreadsheet
sh.share('otto@example.com', perm_type='user', role='writer')
# Transfer ownership to Otto
sh.share('otto@example.com', perm_type='user', role='owner') | f1323:c0:m19 |
def list_permissions(self): | return self.client.list_permissions(self.id)<EOL> | Lists the spreadsheet's permissions. | f1323:c0:m20 |
def remove_permissions(self, value, role='<STR_LIT>'): | permission_list = self.client.list_permissions(self.id)<EOL>key = '<STR_LIT>' if '<STR_LIT:@>' in value else '<STR_LIT>'<EOL>filtered_id_list = [<EOL>p['<STR_LIT:id>'] for p in permission_list<EOL>if p[key] == value and (p['<STR_LIT>'] == role or role == '<STR_LIT>')<EOL>]<EOL>for permission_id in filtered_id_list:<EOL><INDENT>self.client.remove_permission(self.id, permission_id)<EOL><DEDENT>return filtered_id_list<EOL> | Remove permissions from a user or domain.
:param value: User or domain to remove permissions from
:type value: str
:param role: (optional) Permission to remove. Defaults to all
permissions.
:type role: str
Example::
# Remove Otto's write permission for this spreadsheet
sh.remove_permissions('otto@example.com', role='writer')
# Remove all Otto's permissions for this spreadsheet
sh.remove_permissions('otto@example.com') | f1323:c0:m21 |
@property<EOL><INDENT>def id(self):<DEDENT> | return self._properties['<STR_LIT>']<EOL> | Worksheet ID. | f1323:c1:m2 |
@property<EOL><INDENT>def title(self):<DEDENT> | return self._properties['<STR_LIT:title>']<EOL> | Worksheet title. | f1323:c1:m3 |
@property<EOL><INDENT>def updated(self):<DEDENT> | import warnings<EOL>warnings.warn(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>DeprecationWarning,<EOL>stacklevel=<NUM_LIT:2><EOL>)<EOL> | .. deprecated:: 2.0
This feature is not supported in Sheets API v4. | f1323:c1:m4 |
@property<EOL><INDENT>def row_count(self):<DEDENT> | return self._properties['<STR_LIT>']['<STR_LIT>']<EOL> | Number of rows. | f1323:c1:m5 |
@property<EOL><INDENT>def col_count(self):<DEDENT> | return self._properties['<STR_LIT>']['<STR_LIT>']<EOL> | Number of columns. | f1323:c1:m6 |
def acell(self, label, value_render_option='<STR_LIT>'): | return self.cell(<EOL>*(a1_to_rowcol(label)),<EOL>value_render_option=value_render_option<EOL>)<EOL> | Returns an instance of a :class:`gspread.models.Cell`.
:param label: Cell label in A1 notation
Letter case is ignored.
:type label: str
:param value_render_option: (optional) Determines how values should be
rendered in the the output. See
`ValueRenderOption`_ in the Sheets API.
:type value_render_option: str
.. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption
Example:
>>> worksheet.acell('A1')
<Cell R1C1 "I'm cell A1"> | f1323:c1:m7 |
def cell(self, row, col, value_render_option='<STR_LIT>'): | range_label = '<STR_LIT>' % (self.title, rowcol_to_a1(row, col))<EOL>data = self.spreadsheet.values_get(<EOL>range_label,<EOL>params={'<STR_LIT>': value_render_option}<EOL>)<EOL>try:<EOL><INDENT>value = data['<STR_LIT>'][<NUM_LIT:0>][<NUM_LIT:0>]<EOL><DEDENT>except KeyError:<EOL><INDENT>value = '<STR_LIT>'<EOL><DEDENT>return Cell(row, col, value)<EOL> | Returns an instance of a :class:`gspread.models.Cell` located at
`row` and `col` column.
:param row: Row number.
:type row: int
:param col: Column number.
:type col: int
:param value_render_option: (optional) Determines how values should be
rendered in the the output. See
`ValueRenderOption`_ in the Sheets API.
:type value_render_option: str
.. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption
Example:
>>> worksheet.cell(1, 1)
<Cell R1C1 "I'm cell A1"> | f1323:c1:m8 |
@cast_to_a1_notation<EOL><INDENT>def range(self, name):<DEDENT> | range_label = '<STR_LIT>' % (self.title, name)<EOL>data = self.spreadsheet.values_get(range_label)<EOL>start, end = name.split('<STR_LIT::>')<EOL>(row_offset, column_offset) = a1_to_rowcol(start)<EOL>(last_row, last_column) = a1_to_rowcol(end)<EOL>values = data.get('<STR_LIT>', [])<EOL>rect_values = fill_gaps(<EOL>values,<EOL>rows=last_row - row_offset + <NUM_LIT:1>,<EOL>cols=last_column - column_offset + <NUM_LIT:1><EOL>)<EOL>return [<EOL>Cell(row=i + row_offset, col=j + column_offset, value=value)<EOL>for i, row in enumerate(rect_values)<EOL>for j, value in enumerate(row)<EOL>]<EOL> | Returns a list of :class:`Cell` objects from a specified range.
:param name: A string with range value in A1 notation, e.g. 'A1:A5'.
:type name: str
Alternatively, you may specify numeric boundaries. All values
index from 1 (one):
:param first_row: Row number
:type first_row: int
:param first_col: Row number
:type first_col: int
:param last_row: Row number
:type last_row: int
:param last_col: Row number
:type last_col: int
Example::
>>> # Using A1 notation
>>> worksheet.range('A1:B7')
[<Cell R1C1 "42">, ...]
>>> # Same with numeric boundaries
>>> worksheet.range(1, 1, 7, 2)
[<Cell R1C1 "42">, ...] | f1323:c1:m9 |
def get_all_values(self): | data = self.spreadsheet.values_get(self.title)<EOL>try:<EOL><INDENT>return fill_gaps(data['<STR_LIT>'])<EOL><DEDENT>except KeyError:<EOL><INDENT>return []<EOL><DEDENT> | Returns a list of lists containing all cells' values as strings.
.. note::
Empty trailing rows and columns will not be included. | f1323:c1:m10 |
def get_all_records(<EOL>self,<EOL>empty2zero=False,<EOL>head=<NUM_LIT:1>,<EOL>default_blank="<STR_LIT>",<EOL>allow_underscores_in_numeric_literals=False,<EOL>): | idx = head - <NUM_LIT:1><EOL>data = self.get_all_values()<EOL>if len(data) <= idx:<EOL><INDENT>return []<EOL><DEDENT>keys = data[idx]<EOL>values = [<EOL>numericise_all(<EOL>row,<EOL>empty2zero,<EOL>default_blank,<EOL>allow_underscores_in_numeric_literals,<EOL>)<EOL>for row in data[idx + <NUM_LIT:1>:]<EOL>]<EOL>return [dict(zip(keys, row)) for row in values]<EOL> | Returns a list of dictionaries, all of them having the contents
of the spreadsheet with the head row as keys and each of these
dictionaries holding the contents of subsequent rows of cells
as values.
Cell values are numericised (strings that can be read as ints
or floats are converted).
:param empty2zero: (optional) Determines whether empty cells are
converted to zeros.
:type empty2zero: bool
:param head: (optional) Determines wich row to use as keys, starting
from 1 following the numeration of the spreadsheet.
:type head: int
:param default_blank: (optional) Determines whether empty cells are
converted to something else except empty string
or zero.
:type default_blank: str
:param allow_underscores_in_numeric_literals: (optional) Allow underscores
in numeric literals,
as introduced in PEP 515
:type allow_underscores_in_numeric_literals: bool | f1323:c1:m11 |
def row_values(self, row, value_render_option='<STR_LIT>'): | range_label = '<STR_LIT>' % (self.title, row, row)<EOL>data = self.spreadsheet.values_get(<EOL>range_label,<EOL>params={'<STR_LIT>': value_render_option}<EOL>)<EOL>try:<EOL><INDENT>return data['<STR_LIT>'][<NUM_LIT:0>]<EOL><DEDENT>except KeyError:<EOL><INDENT>return []<EOL><DEDENT> | Returns a list of all values in a `row`.
Empty cells in this list will be rendered as :const:`None`.
:param row: Row number.
:type row: int
:param value_render_option: (optional) Determines how values should be
rendered in the the output. See
`ValueRenderOption`_ in the Sheets API.
:type value_render_option: str
.. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption | f1323:c1:m12 |
def col_values(self, col, value_render_option='<STR_LIT>'): | start_label = rowcol_to_a1(<NUM_LIT:1>, col)<EOL>range_label = '<STR_LIT>' % (self.title, start_label, start_label[:-<NUM_LIT:1>])<EOL>data = self.spreadsheet.values_get(<EOL>range_label,<EOL>params={<EOL>'<STR_LIT>': value_render_option,<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>)<EOL>try:<EOL><INDENT>return data['<STR_LIT>'][<NUM_LIT:0>]<EOL><DEDENT>except KeyError:<EOL><INDENT>return []<EOL><DEDENT> | Returns a list of all values in column `col`.
Empty cells in this list will be rendered as :const:`None`.
:param col: Column number.
:type col: int
:param value_render_option: (optional) Determines how values should be
rendered in the the output. See
`ValueRenderOption`_ in the Sheets API.
:type value_render_option: str
.. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption | f1323:c1:m13 |
def update_acell(self, label, value): | return self.update_cell(*(a1_to_rowcol(label)), value=value)<EOL> | Updates the value of a cell.
:param label: Cell label in A1 notation.
Letter case is ignored.
:type label: str
:param value: New value.
Example::
worksheet.update_acell('A1', '42') | f1323:c1:m14 |
def update_cell(self, row, col, value): | range_label = '<STR_LIT>' % (self.title, rowcol_to_a1(row, col))<EOL>data = self.spreadsheet.values_update(<EOL>range_label,<EOL>params={<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>},<EOL>body={<EOL>'<STR_LIT>': [[value]]<EOL>}<EOL>)<EOL>return data<EOL> | Updates the value of a cell.
:param row: Row number.
:type row: int
:param col: Column number.
:type col: int
:param value: New value.
Example::
worksheet.update_cell(1, 1, '42') | f1323:c1:m15 |
def update_cells(self, cell_list, value_input_option='<STR_LIT>'): | values_rect = cell_list_to_rect(cell_list)<EOL>start = rowcol_to_a1(min(c.row for c in cell_list), min(c.col for c in cell_list))<EOL>end = rowcol_to_a1(max(c.row for c in cell_list), max(c.col for c in cell_list))<EOL>range_label = '<STR_LIT>' % (self.title, start, end)<EOL>data = self.spreadsheet.values_update(<EOL>range_label,<EOL>params={<EOL>'<STR_LIT>': value_input_option<EOL>},<EOL>body={<EOL>'<STR_LIT>': values_rect<EOL>}<EOL>)<EOL>return data<EOL> | Updates many cells at once.
:param cell_list: List of :class:`Cell` objects to update.
:param value_input_option: (optional) Determines how input data should
be interpreted. See `ValueInputOption`_ in
the Sheets API.
:type value_input_option: str
.. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption
Example::
# Select a range
cell_list = worksheet.range('A1:C7')
for cell in cell_list:
cell.value = 'O_o'
# Update in batch
worksheet.update_cells(cell_list) | f1323:c1:m16 |
def resize(self, rows=None, cols=None): | grid_properties = {}<EOL>if rows is not None:<EOL><INDENT>grid_properties['<STR_LIT>'] = rows<EOL><DEDENT>if cols is not None:<EOL><INDENT>grid_properties['<STR_LIT>'] = cols<EOL><DEDENT>if not grid_properties:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>fields = '<STR_LIT:U+002C>'.join(<EOL>'<STR_LIT>' % p for p in grid_properties.keys()<EOL>)<EOL>body = {<EOL>'<STR_LIT>': [{<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': self.id,<EOL>'<STR_LIT>': grid_properties<EOL>},<EOL>'<STR_LIT>': fields<EOL>}<EOL>}]<EOL>}<EOL>return self.spreadsheet.batch_update(body)<EOL> | Resizes the worksheet. Specify one of ``rows`` or ``cols``.
:param rows: (optional) New number of rows.
:type rows: int
:param cols: (optional) New number columns.
:type cols: int | f1323:c1:m17 |
def update_title(self, title): | body = {<EOL>'<STR_LIT>': [{<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': self.id,<EOL>'<STR_LIT:title>': title<EOL>},<EOL>'<STR_LIT>': '<STR_LIT:title>'<EOL>}<EOL>}]<EOL>}<EOL>response = self.spreadsheet.batch_update(body)<EOL>self._properties['<STR_LIT:title>'] = title<EOL>return response<EOL> | Renames the worksheet.
:param title: A new title.
:type title: str | f1323:c1:m18 |
def add_rows(self, rows): | self.resize(rows=self.row_count + rows)<EOL> | Adds rows to worksheet.
:param rows: Number of new rows to add.
:type rows: int | f1323:c1:m19 |
def add_cols(self, cols): | self.resize(cols=self.col_count + cols)<EOL> | Adds colums to worksheet.
:param cols: Number of new columns to add.
:type cols: int | f1323:c1:m20 |
def append_row(self, values, value_input_option='<STR_LIT>'): | params = {<EOL>'<STR_LIT>': value_input_option<EOL>}<EOL>body = {<EOL>'<STR_LIT>': [values]<EOL>}<EOL>return self.spreadsheet.values_append(self.title, params, body)<EOL> | Adds a row to the worksheet and populates it with values.
Widens the worksheet if there are more values than columns.
:param values: List of values for the new row.
:param value_input_option: (optional) Determines how input data should
be interpreted. See `ValueInputOption`_ in
the Sheets API.
:type value_input_option: str
.. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption | f1323:c1:m21 |
def insert_row(<EOL>self,<EOL>values,<EOL>index=<NUM_LIT:1>,<EOL>value_input_option='<STR_LIT>'<EOL>): | body = {<EOL>"<STR_LIT>": [{<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": self.id,<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": index - <NUM_LIT:1>,<EOL>"<STR_LIT>": index<EOL>}<EOL>}<EOL>}]<EOL>}<EOL>self.spreadsheet.batch_update(body)<EOL>range_label = '<STR_LIT>' % (self.title, '<STR_LIT>' % index)<EOL>data = self.spreadsheet.values_update(<EOL>range_label,<EOL>params={<EOL>'<STR_LIT>': value_input_option<EOL>},<EOL>body={<EOL>'<STR_LIT>': [values]<EOL>}<EOL>)<EOL>return data<EOL> | Adds a row to the worksheet at the specified index
and populates it with values.
Widens the worksheet if there are more values than columns.
:param values: List of values for the new row.
:param index: (optional) Offset for the newly inserted row.
:type index: int
:param value_input_option: (optional) Determines how input data should
be interpreted. See `ValueInputOption`_ in
the Sheets API.
:type value_input_option: str
.. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption | f1323:c1:m22 |
def delete_row(self, index): | body = {<EOL>"<STR_LIT>": [{<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": self.id,<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": index - <NUM_LIT:1>,<EOL>"<STR_LIT>": index<EOL>}<EOL>}<EOL>}]<EOL>}<EOL>return self.spreadsheet.batch_update(body)<EOL> | Deletes the row from the worksheet at the specified index.
:param index: Index of a row for deletion.
:type index: int | f1323:c1:m23 |
def clear(self): | return self.spreadsheet.values_clear(self.title)<EOL> | Clears all cells in the worksheet. | f1323:c1:m24 |
def find(self, query): | try:<EOL><INDENT>return self._finder(finditem, query)<EOL><DEDENT>except StopIteration:<EOL><INDENT>raise CellNotFound(query)<EOL><DEDENT> | Finds the first cell matching the query.
:param query: A literal string to match or compiled regular expression.
:type query: str, :py:class:`re.RegexObject` | f1323:c1:m26 |