repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
chrislim2888/IP2Location-Python
IP2Location.py
IP2Location.get_elevation
def get_elevation(self, ip): ''' Get elevation ''' rec = self.get_all(ip) return rec and rec.elevation
python
def get_elevation(self, ip): ''' Get elevation ''' rec = self.get_all(ip) return rec and rec.elevation
Get elevation
https://github.com/chrislim2888/IP2Location-Python/blob/6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621/IP2Location.py#L201-L204
chrislim2888/IP2Location-Python
IP2Location.py
IP2Location.get_usage_type
def get_usage_type(self, ip): ''' Get usage_type ''' rec = self.get_all(ip) return rec and rec.usage_type
python
def get_usage_type(self, ip): ''' Get usage_type ''' rec = self.get_all(ip) return rec and rec.usage_type
Get usage_type
https://github.com/chrislim2888/IP2Location-Python/blob/6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621/IP2Location.py#L205-L208
chrislim2888/IP2Location-Python
IP2Location.py
IP2Location._parse_addr
def _parse_addr(self, addr): ''' Parses address and returns IP version. Raises exception on invalid argument ''' ipv = 0 try: socket.inet_pton(socket.AF_INET6, addr) # Convert ::FFFF:x.y.z.y to IPv4 if addr.lower().startswith('::ffff:'): try: ...
python
def _parse_addr(self, addr): ''' Parses address and returns IP version. Raises exception on invalid argument ''' ipv = 0 try: socket.inet_pton(socket.AF_INET6, addr) # Convert ::FFFF:x.y.z.y to IPv4 if addr.lower().startswith('::ffff:'): try: ...
Parses address and returns IP version. Raises exception on invalid argument
https://github.com/chrislim2888/IP2Location-Python/blob/6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621/IP2Location.py#L342-L359
taxjar/taxjar-python
taxjar/client.py
Client.rates_for_location
def rates_for_location(self, postal_code, location_deets=None): """Shows the sales tax rates for a given location.""" request = self._get("rates/" + postal_code, location_deets) return self.responder(request)
python
def rates_for_location(self, postal_code, location_deets=None): """Shows the sales tax rates for a given location.""" request = self._get("rates/" + postal_code, location_deets) return self.responder(request)
Shows the sales tax rates for a given location.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L31-L34
taxjar/taxjar-python
taxjar/client.py
Client.tax_for_order
def tax_for_order(self, order_deets): """Shows the sales tax that should be collected for a given order.""" request = self._post('taxes', order_deets) return self.responder(request)
python
def tax_for_order(self, order_deets): """Shows the sales tax that should be collected for a given order.""" request = self._post('taxes', order_deets) return self.responder(request)
Shows the sales tax that should be collected for a given order.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L36-L39
taxjar/taxjar-python
taxjar/client.py
Client.list_orders
def list_orders(self, params=None): """Lists existing order transactions.""" request = self._get('transactions/orders', params) return self.responder(request)
python
def list_orders(self, params=None): """Lists existing order transactions.""" request = self._get('transactions/orders', params) return self.responder(request)
Lists existing order transactions.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L41-L44
taxjar/taxjar-python
taxjar/client.py
Client.show_order
def show_order(self, order_id): """Shows an existing order transaction.""" request = self._get('transactions/orders/' + str(order_id)) return self.responder(request)
python
def show_order(self, order_id): """Shows an existing order transaction.""" request = self._get('transactions/orders/' + str(order_id)) return self.responder(request)
Shows an existing order transaction.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L46-L49
taxjar/taxjar-python
taxjar/client.py
Client.create_order
def create_order(self, order_deets): """Creates a new order transaction.""" request = self._post('transactions/orders', order_deets) return self.responder(request)
python
def create_order(self, order_deets): """Creates a new order transaction.""" request = self._post('transactions/orders', order_deets) return self.responder(request)
Creates a new order transaction.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L51-L54
taxjar/taxjar-python
taxjar/client.py
Client.update_order
def update_order(self, order_id, order_deets): """Updates an existing order transaction.""" request = self._put("transactions/orders/" + str(order_id), order_deets) return self.responder(request)
python
def update_order(self, order_id, order_deets): """Updates an existing order transaction.""" request = self._put("transactions/orders/" + str(order_id), order_deets) return self.responder(request)
Updates an existing order transaction.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L56-L59
taxjar/taxjar-python
taxjar/client.py
Client.delete_order
def delete_order(self, order_id): """Deletes an existing order transaction.""" request = self._delete("transactions/orders/" + str(order_id)) return self.responder(request)
python
def delete_order(self, order_id): """Deletes an existing order transaction.""" request = self._delete("transactions/orders/" + str(order_id)) return self.responder(request)
Deletes an existing order transaction.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L61-L64
taxjar/taxjar-python
taxjar/client.py
Client.list_refunds
def list_refunds(self, params=None): """Lists existing refund transactions.""" request = self._get('transactions/refunds', params) return self.responder(request)
python
def list_refunds(self, params=None): """Lists existing refund transactions.""" request = self._get('transactions/refunds', params) return self.responder(request)
Lists existing refund transactions.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L66-L69
taxjar/taxjar-python
taxjar/client.py
Client.show_refund
def show_refund(self, refund_id): """Shows an existing refund transaction.""" request = self._get('transactions/refunds/' + str(refund_id)) return self.responder(request)
python
def show_refund(self, refund_id): """Shows an existing refund transaction.""" request = self._get('transactions/refunds/' + str(refund_id)) return self.responder(request)
Shows an existing refund transaction.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L71-L74
taxjar/taxjar-python
taxjar/client.py
Client.create_refund
def create_refund(self, refund_deets): """Creates a new refund transaction.""" request = self._post('transactions/refunds', refund_deets) return self.responder(request)
python
def create_refund(self, refund_deets): """Creates a new refund transaction.""" request = self._post('transactions/refunds', refund_deets) return self.responder(request)
Creates a new refund transaction.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L76-L79
taxjar/taxjar-python
taxjar/client.py
Client.update_refund
def update_refund(self, refund_id, refund_deets): """Updates an existing refund transaction.""" request = self._put('transactions/refunds/' + str(refund_id), refund_deets) return self.responder(request)
python
def update_refund(self, refund_id, refund_deets): """Updates an existing refund transaction.""" request = self._put('transactions/refunds/' + str(refund_id), refund_deets) return self.responder(request)
Updates an existing refund transaction.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L81-L84
taxjar/taxjar-python
taxjar/client.py
Client.delete_refund
def delete_refund(self, refund_id): """Deletes an existing refund transaction.""" request = self._delete('transactions/refunds/' + str(refund_id)) return self.responder(request)
python
def delete_refund(self, refund_id): """Deletes an existing refund transaction.""" request = self._delete('transactions/refunds/' + str(refund_id)) return self.responder(request)
Deletes an existing refund transaction.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L86-L89
taxjar/taxjar-python
taxjar/client.py
Client.list_customers
def list_customers(self, params=None): """Lists existing customers.""" request = self._get('customers', params) return self.responder(request)
python
def list_customers(self, params=None): """Lists existing customers.""" request = self._get('customers', params) return self.responder(request)
Lists existing customers.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L91-L94
taxjar/taxjar-python
taxjar/client.py
Client.show_customer
def show_customer(self, customer_id): """Shows an existing customer.""" request = self._get('customers/' + str(customer_id)) return self.responder(request)
python
def show_customer(self, customer_id): """Shows an existing customer.""" request = self._get('customers/' + str(customer_id)) return self.responder(request)
Shows an existing customer.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L96-L99
taxjar/taxjar-python
taxjar/client.py
Client.create_customer
def create_customer(self, customer_deets): """Creates a new customer.""" request = self._post('customers', customer_deets) return self.responder(request)
python
def create_customer(self, customer_deets): """Creates a new customer.""" request = self._post('customers', customer_deets) return self.responder(request)
Creates a new customer.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L101-L104
taxjar/taxjar-python
taxjar/client.py
Client.update_customer
def update_customer(self, customer_id, customer_deets): """Updates an existing customer.""" request = self._put("customers/" + str(customer_id), customer_deets) return self.responder(request)
python
def update_customer(self, customer_id, customer_deets): """Updates an existing customer.""" request = self._put("customers/" + str(customer_id), customer_deets) return self.responder(request)
Updates an existing customer.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L106-L109
taxjar/taxjar-python
taxjar/client.py
Client.delete_customer
def delete_customer(self, customer_id): """Deletes an existing customer.""" request = self._delete("customers/" + str(customer_id)) return self.responder(request)
python
def delete_customer(self, customer_id): """Deletes an existing customer.""" request = self._delete("customers/" + str(customer_id)) return self.responder(request)
Deletes an existing customer.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L111-L114
taxjar/taxjar-python
taxjar/client.py
Client.validate_address
def validate_address(self, address_deets): """Validates a customer address and returns back a collection of address matches.""" request = self._post('addresses/validate', address_deets) return self.responder(request)
python
def validate_address(self, address_deets): """Validates a customer address and returns back a collection of address matches.""" request = self._post('addresses/validate', address_deets) return self.responder(request)
Validates a customer address and returns back a collection of address matches.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L121-L124
taxjar/taxjar-python
taxjar/client.py
Client.validate
def validate(self, vat_deets): """Validates an existing VAT identification number against VIES.""" request = self._get('validation', vat_deets) return self.responder(request)
python
def validate(self, vat_deets): """Validates an existing VAT identification number against VIES.""" request = self._get('validation', vat_deets) return self.responder(request)
Validates an existing VAT identification number against VIES.
https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L126-L129
hanzhichao2000/pysentiment
pysentiment/base.py
BaseDict.get_score
def get_score(self, terms): """Get score for a list of terms. :type terms: list :param terms: A list of terms to be analyzed. :returns: dict """ assert isinstance(terms, list) or isinstance(terms, tuple) score_li = np.asarray([self._get_score(t) ...
python
def get_score(self, terms): """Get score for a list of terms. :type terms: list :param terms: A list of terms to be analyzed. :returns: dict """ assert isinstance(terms, list) or isinstance(terms, tuple) score_li = np.asarray([self._get_score(t) ...
Get score for a list of terms. :type terms: list :param terms: A list of terms to be analyzed. :returns: dict
https://github.com/hanzhichao2000/pysentiment/blob/ea2ac15f38ee2f68f0ef2bbb48b89acdd9c7f766/pysentiment/base.py#L101-L121
last-partizan/pytils
pytils/templatetags/pytils_numeral.py
choose_plural
def choose_plural(amount, variants): """ Choose proper form for plural. Value is a amount, parameters are forms of noun. Forms are variants for 1, 2, 5 nouns. It may be tuple of elements, or string where variants separates each other by comma. Examples:: {{ some_int|choose_plural:"...
python
def choose_plural(amount, variants): """ Choose proper form for plural. Value is a amount, parameters are forms of noun. Forms are variants for 1, 2, 5 nouns. It may be tuple of elements, or string where variants separates each other by comma. Examples:: {{ some_int|choose_plural:"...
Choose proper form for plural. Value is a amount, parameters are forms of noun. Forms are variants for 1, 2, 5 nouns. It may be tuple of elements, or string where variants separates each other by comma. Examples:: {{ some_int|choose_plural:"пример,примера,примеров" }}
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_numeral.py#L29-L54
last-partizan/pytils
pytils/templatetags/pytils_numeral.py
rubles
def rubles(amount, zero_for_kopeck=False): """Converts float value to in-words representation (for money)""" try: res = numeral.rubles(amount, zero_for_kopeck) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': str(amount)} r...
python
def rubles(amount, zero_for_kopeck=False): """Converts float value to in-words representation (for money)""" try: res = numeral.rubles(amount, zero_for_kopeck) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': str(amount)} r...
Converts float value to in-words representation (for money)
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_numeral.py#L83-L90
last-partizan/pytils
pytils/templatetags/pytils_numeral.py
in_words
def in_words(amount, gender=None): """ In-words representation of amount. Parameter is a gender: MALE, FEMALE or NEUTER Examples:: {{ some_int|in_words }} {{ some_other_int|in_words:FEMALE }} """ try: res = numeral.in_words(amount, getattr(numeral, str(gender), None)) ...
python
def in_words(amount, gender=None): """ In-words representation of amount. Parameter is a gender: MALE, FEMALE or NEUTER Examples:: {{ some_int|in_words }} {{ some_other_int|in_words:FEMALE }} """ try: res = numeral.in_words(amount, getattr(numeral, str(gender), None)) ...
In-words representation of amount. Parameter is a gender: MALE, FEMALE or NEUTER Examples:: {{ some_int|in_words }} {{ some_other_int|in_words:FEMALE }}
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_numeral.py#L92-L107
last-partizan/pytils
pytils/templatetags/pytils_numeral.py
sum_string
def sum_string(amount, gender, items): """ in_words and choose_plural in a one flask Makes in-words representation of value with choosing correct form of noun. First parameter is an amount of objects. Second is a gender (MALE, FEMALE, NEUTER). Third is a variants of forms for object name. ...
python
def sum_string(amount, gender, items): """ in_words and choose_plural in a one flask Makes in-words representation of value with choosing correct form of noun. First parameter is an amount of objects. Second is a gender (MALE, FEMALE, NEUTER). Third is a variants of forms for object name. ...
in_words and choose_plural in a one flask Makes in-words representation of value with choosing correct form of noun. First parameter is an amount of objects. Second is a gender (MALE, FEMALE, NEUTER). Third is a variants of forms for object name. Examples:: {% sum_string some_int MALE ...
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_numeral.py#L118-L141
last-partizan/pytils
pytils/typo.py
_sub_patterns
def _sub_patterns(patterns, text): """ Apply re.sub to bunch of (pattern, repl) """ for pattern, repl in patterns: text = re.sub(pattern, repl, text) return text
python
def _sub_patterns(patterns, text): """ Apply re.sub to bunch of (pattern, repl) """ for pattern, repl in patterns: text = re.sub(pattern, repl, text) return text
Apply re.sub to bunch of (pattern, repl)
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/typo.py#L9-L15
last-partizan/pytils
pytils/typo.py
rl_cleanspaces
def rl_cleanspaces(x): """ Clean double spaces, trailing spaces, heading spaces, spaces before punctuations """ patterns = ( # arguments for re.sub: pattern and repl # удаляем пробел перед знаками препинания (r' +([\.,?!\)]+)', r'\1'), # добавляем пробел после знака п...
python
def rl_cleanspaces(x): """ Clean double spaces, trailing spaces, heading spaces, spaces before punctuations """ patterns = ( # arguments for re.sub: pattern and repl # удаляем пробел перед знаками препинания (r' +([\.,?!\)]+)', r'\1'), # добавляем пробел после знака п...
Clean double spaces, trailing spaces, heading spaces, spaces before punctuations
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/typo.py#L26-L44
last-partizan/pytils
pytils/typo.py
rl_ellipsis
def rl_ellipsis(x): """ Replace three dots to ellipsis """ patterns = ( # если больше трех точек, то не заменяем на троеточие # чтобы не было глупых .....->….. (r'([^\.]|^)\.\.\.([^\.]|$)', u'\\1\u2026\\2'), # если троеточие в начале строки или возле кавычки -- #...
python
def rl_ellipsis(x): """ Replace three dots to ellipsis """ patterns = ( # если больше трех точек, то не заменяем на троеточие # чтобы не было глупых .....->….. (r'([^\.]|^)\.\.\.([^\.]|$)', u'\\1\u2026\\2'), # если троеточие в начале строки или возле кавычки -- #...
Replace three dots to ellipsis
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/typo.py#L46-L61
last-partizan/pytils
pytils/typo.py
rl_initials
def rl_initials(x): """ Replace space between initials and surname by thin space """ return re.sub( re.compile(u'([А-Я])\\.\\s*([А-Я])\\.\\s*([А-Я][а-я]+)', re.UNICODE), u'\\1.\\2.\u2009\\3', x )
python
def rl_initials(x): """ Replace space between initials and surname by thin space """ return re.sub( re.compile(u'([А-Я])\\.\\s*([А-Я])\\.\\s*([А-Я][а-я]+)', re.UNICODE), u'\\1.\\2.\u2009\\3', x )
Replace space between initials and surname by thin space
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/typo.py#L63-L71
last-partizan/pytils
pytils/typo.py
rl_dashes
def rl_dashes(x): """ Replace dash to long/medium dashes """ patterns = ( # тире (re.compile(u'(^|(.\\s))\\-\\-?(([\\s\u202f].)|$)', re.MULTILINE|re.UNICODE), u'\\1\u2014\\3'), # диапазоны между цифрами - en dash (re.compile(u'(\\d[\\s\u2009]*)\\-([\\s\u2009]*\d)', re.MUL...
python
def rl_dashes(x): """ Replace dash to long/medium dashes """ patterns = ( # тире (re.compile(u'(^|(.\\s))\\-\\-?(([\\s\u202f].)|$)', re.MULTILINE|re.UNICODE), u'\\1\u2014\\3'), # диапазоны между цифрами - en dash (re.compile(u'(\\d[\\s\u2009]*)\\-([\\s\u2009]*\d)', re.MUL...
Replace dash to long/medium dashes
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/typo.py#L73-L84
last-partizan/pytils
pytils/typo.py
rl_wordglue
def rl_wordglue(x): """ Glue (set nonbreakable space) short words with word before/after """ patterns = ( # частицы склеиваем с предыдущим словом (re.compile(u'(\\s+)(же|ли|ль|бы|б|ж|ка)([\\.,!\\?:;]?\\s+)', re.UNICODE), u'\u202f\\2\\3'), # склеиваем короткие слова со следующим с...
python
def rl_wordglue(x): """ Glue (set nonbreakable space) short words with word before/after """ patterns = ( # частицы склеиваем с предыдущим словом (re.compile(u'(\\s+)(же|ли|ль|бы|б|ж|ка)([\\.,!\\?:;]?\\s+)', re.UNICODE), u'\u202f\\2\\3'), # склеиваем короткие слова со следующим с...
Glue (set nonbreakable space) short words with word before/after
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/typo.py#L86-L101
last-partizan/pytils
pytils/typo.py
rl_marks
def rl_marks(x): """ Replace +-, (c), (tm), (r), (p), etc by its typographic eqivalents """ # простые замены, можно без регулярок replacements = ( (u'(r)', u'\u00ae'), # ® (u'(R)', u'\u00ae'), # ® (u'(p)', u'\u00a7'), # § (u'(P)', u'\u00a7'), # § (u'(tm)', u'\...
python
def rl_marks(x): """ Replace +-, (c), (tm), (r), (p), etc by its typographic eqivalents """ # простые замены, можно без регулярок replacements = ( (u'(r)', u'\u00ae'), # ® (u'(R)', u'\u00ae'), # ® (u'(p)', u'\u00a7'), # § (u'(P)', u'\u00a7'), # § (u'(tm)', u'\...
Replace +-, (c), (tm), (r), (p), etc by its typographic eqivalents
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/typo.py#L103-L132
last-partizan/pytils
pytils/typo.py
rl_quotes
def rl_quotes(x): """ Replace quotes by typographic quotes """ patterns = ( # открывающие кавычки ставятся обычно вплотную к слову слева # а закрывающие -- вплотную справа # открывающие русские кавычки-ёлочки (re.compile(r'((?:^|\s))(")((?u))', re.UNICODE), u'\\1\xab...
python
def rl_quotes(x): """ Replace quotes by typographic quotes """ patterns = ( # открывающие кавычки ставятся обычно вплотную к слову слева # а закрывающие -- вплотную справа # открывающие русские кавычки-ёлочки (re.compile(r'((?:^|\s))(")((?u))', re.UNICODE), u'\\1\xab...
Replace quotes by typographic quotes
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/typo.py#L134-L151
last-partizan/pytils
pytils/templatetags/pytils_dt.py
distance_of_time
def distance_of_time(from_time, accuracy=1): """ Display distance of time from current time. Parameter is an accuracy level (deafult is 1). Value must be numeral (i.e. time.time() result) or datetime.datetime (i.e. datetime.datetime.now() result). Examples:: {{ some_time|distance_o...
python
def distance_of_time(from_time, accuracy=1): """ Display distance of time from current time. Parameter is an accuracy level (deafult is 1). Value must be numeral (i.e. time.time() result) or datetime.datetime (i.e. datetime.datetime.now() result). Examples:: {{ some_time|distance_o...
Display distance of time from current time. Parameter is an accuracy level (deafult is 1). Value must be numeral (i.e. time.time() result) or datetime.datetime (i.e. datetime.datetime.now() result). Examples:: {{ some_time|distance_of_time }} {{ some_dtime|distance_of_time:2 }}
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_dt.py#L20-L45
last-partizan/pytils
pytils/templatetags/pytils_dt.py
ru_strftime
def ru_strftime(date, format="%d.%m.%Y", inflected_day=False, preposition=False): """ Russian strftime, formats date with given format. Value is a date (supports datetime.date and datetime.datetime), parameter is a format (string). For explainings about format, see documentation for original strfti...
python
def ru_strftime(date, format="%d.%m.%Y", inflected_day=False, preposition=False): """ Russian strftime, formats date with given format. Value is a date (supports datetime.date and datetime.datetime), parameter is a format (string). For explainings about format, see documentation for original strfti...
Russian strftime, formats date with given format. Value is a date (supports datetime.date and datetime.datetime), parameter is a format (string). For explainings about format, see documentation for original strftime: http://docs.python.org/lib/module-time.html Examples:: {{ some_date|ru_st...
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_dt.py#L47-L72
last-partizan/pytils
pytils/dt.py
distance_of_time_in_words
def distance_of_time_in_words(from_time, accuracy=1, to_time=None): """ Represents distance of time in words @param from_time: source time (in seconds from epoch) @type from_time: C{int}, C{float} or C{datetime.datetime} @param accuracy: level of accuracy (1..3), default=1 @type accuracy: C{in...
python
def distance_of_time_in_words(from_time, accuracy=1, to_time=None): """ Represents distance of time in words @param from_time: source time (in seconds from epoch) @type from_time: C{int}, C{float} or C{datetime.datetime} @param accuracy: level of accuracy (1..3), default=1 @type accuracy: C{in...
Represents distance of time in words @param from_time: source time (in seconds from epoch) @type from_time: C{int}, C{float} or C{datetime.datetime} @param accuracy: level of accuracy (1..3), default=1 @type accuracy: C{int} @param to_time: target time (in seconds from epoch), default=Non...
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/dt.py#L65-L176
last-partizan/pytils
pytils/dt.py
ru_strftime
def ru_strftime(format=u"%d.%m.%Y", date=None, inflected=False, inflected_day=False, preposition=False): """ Russian strftime without locale @param format: strftime format, default=u'%d.%m.%Y' @type format: C{unicode} @param date: date value, default=None translates to today @t...
python
def ru_strftime(format=u"%d.%m.%Y", date=None, inflected=False, inflected_day=False, preposition=False): """ Russian strftime without locale @param format: strftime format, default=u'%d.%m.%Y' @type format: C{unicode} @param date: date value, default=None translates to today @t...
Russian strftime without locale @param format: strftime format, default=u'%d.%m.%Y' @type format: C{unicode} @param date: date value, default=None translates to today @type date: C{datetime.date} or C{datetime.datetime} @param inflected: is month inflected, default False @type inflected: C{bo...
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/dt.py#L179-L233
last-partizan/pytils
pytils/numeral.py
_get_float_remainder
def _get_float_remainder(fvalue, signs=9): """ Get remainder of float, i.e. 2.05 -> '05' @param fvalue: input value @type fvalue: C{integer types}, C{float} or C{Decimal} @param signs: maximum number of signs @type signs: C{integer types} @return: remainder @rtype: C{str} @raise ...
python
def _get_float_remainder(fvalue, signs=9): """ Get remainder of float, i.e. 2.05 -> '05' @param fvalue: input value @type fvalue: C{integer types}, C{float} or C{Decimal} @param signs: maximum number of signs @type signs: C{integer types} @return: remainder @rtype: C{str} @raise ...
Get remainder of float, i.e. 2.05 -> '05' @param fvalue: input value @type fvalue: C{integer types}, C{float} or C{Decimal} @param signs: maximum number of signs @type signs: C{integer types} @return: remainder @rtype: C{str} @raise ValueError: fvalue is negative @raise ValueError: s...
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L77-L123
last-partizan/pytils
pytils/numeral.py
choose_plural
def choose_plural(amount, variants): """ Choose proper case depending on amount @param amount: amount of objects @type amount: C{integer types} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects). @type variants: 3-element C{sequence} of C{unicode...
python
def choose_plural(amount, variants): """ Choose proper case depending on amount @param amount: amount of objects @type amount: C{integer types} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects). @type variants: 3-element C{sequence} of C{unicode...
Choose proper case depending on amount @param amount: amount of objects @type amount: C{integer types} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects). @type variants: 3-element C{sequence} of C{unicode} or C{unicode} (three variants with deli...
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L126-L157
last-partizan/pytils
pytils/numeral.py
get_plural
def get_plural(amount, variants, absence=None): """ Get proper case with value @param amount: amount of objects @type amount: C{integer types} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects). @type variants: 3-element C{sequence} of C{unicode}...
python
def get_plural(amount, variants, absence=None): """ Get proper case with value @param amount: amount of objects @type amount: C{integer types} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects). @type variants: 3-element C{sequence} of C{unicode}...
Get proper case with value @param amount: amount of objects @type amount: C{integer types} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects). @type variants: 3-element C{sequence} of C{unicode} or C{unicode} (three variants with delimeter ',') ...
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L160-L181
last-partizan/pytils
pytils/numeral.py
_get_plural_legacy
def _get_plural_legacy(amount, extra_variants): """ Get proper case with value (legacy variant, without absence) @param amount: amount of objects @type amount: C{integer types} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects, 0-object variant). ...
python
def _get_plural_legacy(amount, extra_variants): """ Get proper case with value (legacy variant, without absence) @param amount: amount of objects @type amount: C{integer types} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects, 0-object variant). ...
Get proper case with value (legacy variant, without absence) @param amount: amount of objects @type amount: C{integer types} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects, 0-object variant). 0-object variant is similar to C{absence} in C{get_plur...
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L184-L208
last-partizan/pytils
pytils/numeral.py
rubles
def rubles(amount, zero_for_kopeck=False): """ Get string for money @param amount: amount of money @type amount: C{integer types}, C{float} or C{Decimal} @param zero_for_kopeck: If false, then zero kopecks ignored @type zero_for_kopeck: C{bool} @return: in-words representation of money's ...
python
def rubles(amount, zero_for_kopeck=False): """ Get string for money @param amount: amount of money @type amount: C{integer types}, C{float} or C{Decimal} @param zero_for_kopeck: If false, then zero kopecks ignored @type zero_for_kopeck: C{bool} @return: in-words representation of money's ...
Get string for money @param amount: amount of money @type amount: C{integer types}, C{float} or C{Decimal} @param zero_for_kopeck: If false, then zero kopecks ignored @type zero_for_kopeck: C{bool} @return: in-words representation of money's amount @rtype: C{unicode} @raise ValueError: a...
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L211-L241
last-partizan/pytils
pytils/numeral.py
in_words_float
def in_words_float(amount, _gender=FEMALE): """ Float in words @param amount: float numeral @type amount: C{float} or C{Decimal} @return: in-words reprsentation of float numeral @rtype: C{unicode} @raise ValueError: when ammount is negative """ check_positive(amount) pts = []...
python
def in_words_float(amount, _gender=FEMALE): """ Float in words @param amount: float numeral @type amount: C{float} or C{Decimal} @return: in-words reprsentation of float numeral @rtype: C{unicode} @raise ValueError: when ammount is negative """ check_positive(amount) pts = []...
Float in words @param amount: float numeral @type amount: C{float} or C{Decimal} @return: in-words reprsentation of float numeral @rtype: C{unicode} @raise ValueError: when ammount is negative
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L263-L286
last-partizan/pytils
pytils/numeral.py
in_words
def in_words(amount, gender=None): """ Numeral in words @param amount: numeral @type amount: C{integer types}, C{float} or C{Decimal} @param gender: gender (MALE, FEMALE or NEUTER) @type gender: C{int} @return: in-words reprsentation of numeral @rtype: C{unicode} raise ValueError...
python
def in_words(amount, gender=None): """ Numeral in words @param amount: numeral @type amount: C{integer types}, C{float} or C{Decimal} @param gender: gender (MALE, FEMALE or NEUTER) @type gender: C{int} @return: in-words reprsentation of numeral @rtype: C{unicode} raise ValueError...
Numeral in words @param amount: numeral @type amount: C{integer types}, C{float} or C{Decimal} @param gender: gender (MALE, FEMALE or NEUTER) @type gender: C{int} @return: in-words reprsentation of numeral @rtype: C{unicode} raise ValueError: when amount is negative
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L289-L325
last-partizan/pytils
pytils/numeral.py
sum_string
def sum_string(amount, gender, items=None): """ Get sum in words @param amount: amount of objects @type amount: C{integer types} @param gender: gender of object (MALE, FEMALE or NEUTER) @type gender: C{int} @param items: variants of object in three forms: for one object, for two o...
python
def sum_string(amount, gender, items=None): """ Get sum in words @param amount: amount of objects @type amount: C{integer types} @param gender: gender of object (MALE, FEMALE or NEUTER) @type gender: C{int} @param items: variants of object in three forms: for one object, for two o...
Get sum in words @param amount: amount of objects @type amount: C{integer types} @param gender: gender of object (MALE, FEMALE or NEUTER) @type gender: C{int} @param items: variants of object in three forms: for one object, for two objects and for five objects @type items: 3-element C...
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L328-L385
last-partizan/pytils
pytils/numeral.py
_sum_string_fn
def _sum_string_fn(into, tmp_val, gender, items=None): """ Make in-words representation of single order @param into: in-words representation of lower orders @type into: C{unicode} @param tmp_val: temporary value without lower orders @type tmp_val: C{integer types} @param gender: gender (M...
python
def _sum_string_fn(into, tmp_val, gender, items=None): """ Make in-words representation of single order @param into: in-words representation of lower orders @type into: C{unicode} @param tmp_val: temporary value without lower orders @type tmp_val: C{integer types} @param gender: gender (M...
Make in-words representation of single order @param into: in-words representation of lower orders @type into: C{unicode} @param tmp_val: temporary value without lower orders @type tmp_val: C{integer types} @param gender: gender (MALE, FEMALE or NEUTER) @type gender: C{int} @param items: ...
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L388-L455
last-partizan/pytils
pytils/translit.py
translify
def translify(in_string, strict=True): """ Translify russian text @param in_string: input string @type in_string: C{unicode} @param strict: raise error if transliteration is incomplete. (True by default) @type strict: C{bool} @return: transliterated string @rtype: C{str} ...
python
def translify(in_string, strict=True): """ Translify russian text @param in_string: input string @type in_string: C{unicode} @param strict: raise error if transliteration is incomplete. (True by default) @type strict: C{bool} @return: transliterated string @rtype: C{str} ...
Translify russian text @param in_string: input string @type in_string: C{unicode} @param strict: raise error if transliteration is incomplete. (True by default) @type strict: C{bool} @return: transliterated string @rtype: C{str} @raise ValueError: when string doesn't transliterat...
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/translit.py#L136-L161
last-partizan/pytils
pytils/translit.py
detranslify
def detranslify(in_string): """ Detranslify @param in_string: input string @type in_string: C{basestring} @return: detransliterated string @rtype: C{unicode} @raise ValueError: if in_string is C{str}, but it isn't ascii """ try: russian = six.text_type(in_string) excep...
python
def detranslify(in_string): """ Detranslify @param in_string: input string @type in_string: C{basestring} @return: detransliterated string @rtype: C{unicode} @raise ValueError: if in_string is C{str}, but it isn't ascii """ try: russian = six.text_type(in_string) excep...
Detranslify @param in_string: input string @type in_string: C{basestring} @return: detransliterated string @rtype: C{unicode} @raise ValueError: if in_string is C{str}, but it isn't ascii
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/translit.py#L163-L188
last-partizan/pytils
pytils/translit.py
slugify
def slugify(in_string): """ Prepare string for slug (i.e. URL or file/dir name) @param in_string: input string @type in_string: C{basestring} @return: slug-string @rtype: C{str} @raise ValueError: if in_string is C{str}, but it isn't ascii """ try: u_in_string = six.text_t...
python
def slugify(in_string): """ Prepare string for slug (i.e. URL or file/dir name) @param in_string: input string @type in_string: C{basestring} @return: slug-string @rtype: C{str} @raise ValueError: if in_string is C{str}, but it isn't ascii """ try: u_in_string = six.text_t...
Prepare string for slug (i.e. URL or file/dir name) @param in_string: input string @type in_string: C{basestring} @return: slug-string @rtype: C{str} @raise ValueError: if in_string is C{str}, but it isn't ascii
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/translit.py#L190-L217
last-partizan/pytils
pytils/utils.py
check_length
def check_length(value, length): """ Checks length of value @param value: value to check @type value: C{str} @param length: length checking for @type length: C{int} @return: None when check successful @raise ValueError: check failed """ _length = len(value) if _length != ...
python
def check_length(value, length): """ Checks length of value @param value: value to check @type value: C{str} @param length: length checking for @type length: C{int} @return: None when check successful @raise ValueError: check failed """ _length = len(value) if _length != ...
Checks length of value @param value: value to check @type value: C{str} @param length: length checking for @type length: C{int} @return: None when check successful @raise ValueError: check failed
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/utils.py#L10-L27
last-partizan/pytils
pytils/utils.py
check_positive
def check_positive(value, strict=False): """ Checks if variable is positive @param value: value to check @type value: C{integer types}, C{float} or C{Decimal} @return: None when check successful @raise ValueError: check failed """ if not strict and value < 0: raise ValueError(...
python
def check_positive(value, strict=False): """ Checks if variable is positive @param value: value to check @type value: C{integer types}, C{float} or C{Decimal} @return: None when check successful @raise ValueError: check failed """ if not strict and value < 0: raise ValueError(...
Checks if variable is positive @param value: value to check @type value: C{integer types}, C{float} or C{Decimal} @return: None when check successful @raise ValueError: check failed
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/utils.py#L30-L44
last-partizan/pytils
pytils/utils.py
split_values
def split_values(ustring, sep=u','): """ Splits unicode string with separator C{sep}, but skips escaped separator. @param ustring: string to split @type ustring: C{unicode} @param sep: separator (default to u',') @type sep: C{unicode} @return: tuple of splitted elements ...
python
def split_values(ustring, sep=u','): """ Splits unicode string with separator C{sep}, but skips escaped separator. @param ustring: string to split @type ustring: C{unicode} @param sep: separator (default to u',') @type sep: C{unicode} @return: tuple of splitted elements ...
Splits unicode string with separator C{sep}, but skips escaped separator. @param ustring: string to split @type ustring: C{unicode} @param sep: separator (default to u',') @type sep: C{unicode} @return: tuple of splitted elements
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/utils.py#L47-L65
last-partizan/pytils
pytils/templatetags/pytils_translit.py
translify
def translify(text): """Translify russian text""" try: res = translit.translify(smart_text(text, encoding)) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': text} return res
python
def translify(text): """Translify russian text""" try: res = translit.translify(smart_text(text, encoding)) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': text} return res
Translify russian text
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_translit.py#L27-L34
last-partizan/pytils
pytils/templatetags/pytils_translit.py
detranslify
def detranslify(text): """Detranslify russian text""" try: res = translit.detranslify(text) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': text} return res
python
def detranslify(text): """Detranslify russian text""" try: res = translit.detranslify(text) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': text} return res
Detranslify russian text
https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_translit.py#L36-L43
larsyencken/csvdiff
csvdiff/patch.py
apply
def apply(diff, recs, strict=True): """ Transform the records with the patch. May fail if the records do not match those expected in the patch. """ index_columns = diff['_index'] indexed = records.index(copy.deepcopy(list(recs)), index_columns) _add_records(indexed, diff['added'], index_colu...
python
def apply(diff, recs, strict=True): """ Transform the records with the patch. May fail if the records do not match those expected in the patch. """ index_columns = diff['_index'] indexed = records.index(copy.deepcopy(list(recs)), index_columns) _add_records(indexed, diff['added'], index_colu...
Transform the records with the patch. May fail if the records do not match those expected in the patch.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L106-L116
larsyencken/csvdiff
csvdiff/patch.py
load
def load(istream, strict=True): "Deserialize a patch object." try: diff = json.load(istream) if strict: jsonschema.validate(diff, SCHEMA) except ValueError: raise InvalidPatchError('patch is not valid JSON') except jsonschema.exceptions.ValidationError as e: ...
python
def load(istream, strict=True): "Deserialize a patch object." try: diff = json.load(istream) if strict: jsonschema.validate(diff, SCHEMA) except ValueError: raise InvalidPatchError('patch is not valid JSON') except jsonschema.exceptions.ValidationError as e: ...
Deserialize a patch object.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L175-L187
larsyencken/csvdiff
csvdiff/patch.py
save
def save(diff, stream=sys.stdout, compact=False): "Serialize a patch object." flags = {'sort_keys': True} if not compact: flags['indent'] = 2 json.dump(diff, stream, **flags)
python
def save(diff, stream=sys.stdout, compact=False): "Serialize a patch object." flags = {'sort_keys': True} if not compact: flags['indent'] = 2 json.dump(diff, stream, **flags)
Serialize a patch object.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L190-L196
larsyencken/csvdiff
csvdiff/patch.py
create
def create(from_records, to_records, index_columns, ignore_columns=None): """ Diff two sets of records, using the index columns as the primary key for both datasets. """ from_indexed = records.index(from_records, index_columns) to_indexed = records.index(to_records, index_columns) if ignore...
python
def create(from_records, to_records, index_columns, ignore_columns=None): """ Diff two sets of records, using the index columns as the primary key for both datasets. """ from_indexed = records.index(from_records, index_columns) to_indexed = records.index(to_records, index_columns) if ignore...
Diff two sets of records, using the index columns as the primary key for both datasets.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L199-L211
larsyencken/csvdiff
csvdiff/patch.py
_compare_rows
def _compare_rows(from_recs, to_recs, keys): "Return the set of keys which have changed." return set( k for k in keys if sorted(from_recs[k].items()) != sorted(to_recs[k].items()) )
python
def _compare_rows(from_recs, to_recs, keys): "Return the set of keys which have changed." return set( k for k in keys if sorted(from_recs[k].items()) != sorted(to_recs[k].items()) )
Return the set of keys which have changed.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L236-L241
larsyencken/csvdiff
csvdiff/patch.py
record_diff
def record_diff(lhs, rhs): "Diff an individual row." delta = {} for k in set(lhs).union(rhs): from_ = lhs[k] to_ = rhs[k] if from_ != to_: delta[k] = {'from': from_, 'to': to_} return delta
python
def record_diff(lhs, rhs): "Diff an individual row." delta = {} for k in set(lhs).union(rhs): from_ = lhs[k] to_ = rhs[k] if from_ != to_: delta[k] = {'from': from_, 'to': to_} return delta
Diff an individual row.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L260-L269
larsyencken/csvdiff
csvdiff/patch.py
filter_significance
def filter_significance(diff, significance): """ Prune any changes in the patch which are due to numeric changes less than this level of significance. """ changed = diff['changed'] # remove individual field changes that are significant reduced = [{'key': delta['key'], 'field...
python
def filter_significance(diff, significance): """ Prune any changes in the patch which are due to numeric changes less than this level of significance. """ changed = diff['changed'] # remove individual field changes that are significant reduced = [{'key': delta['key'], 'field...
Prune any changes in the patch which are due to numeric changes less than this level of significance.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L304-L323
larsyencken/csvdiff
csvdiff/patch.py
_is_significant
def _is_significant(change, significance): """ Return True if a change is genuinely significant given our tolerance. """ try: a = float(change['from']) b = float(change['to']) except ValueError: return True return abs(a - b) > 10 ** (-significance)
python
def _is_significant(change, significance): """ Return True if a change is genuinely significant given our tolerance. """ try: a = float(change['from']) b = float(change['to']) except ValueError: return True return abs(a - b) > 10 ** (-significance)
Return True if a change is genuinely significant given our tolerance.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L326-L337
larsyencken/csvdiff
csvdiff/__init__.py
diff_files
def diff_files(from_file, to_file, index_columns, sep=',', ignored_columns=None): """ Diff two CSV files, returning the patch which transforms one into the other. """ with open(from_file) as from_stream: with open(to_file) as to_stream: from_records = records.load(from_stream, se...
python
def diff_files(from_file, to_file, index_columns, sep=',', ignored_columns=None): """ Diff two CSV files, returning the patch which transforms one into the other. """ with open(from_file) as from_stream: with open(to_file) as to_stream: from_records = records.load(from_stream, se...
Diff two CSV files, returning the patch which transforms one into the other.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L28-L38
larsyencken/csvdiff
csvdiff/__init__.py
patch_file
def patch_file(patch_stream: TextIO, fromcsv_stream: TextIO, tocsv_stream: TextIO, strict: bool = True, sep: str = ','): """ Apply the patch to the source CSV file, and save the result to the target file. """ diff = patch.load(patch_stream) from_records = records.load(fromcsv_str...
python
def patch_file(patch_stream: TextIO, fromcsv_stream: TextIO, tocsv_stream: TextIO, strict: bool = True, sep: str = ','): """ Apply the patch to the source CSV file, and save the result to the target file. """ diff = patch.load(patch_stream) from_records = records.load(fromcsv_str...
Apply the patch to the source CSV file, and save the result to the target file.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L49-L70
larsyencken/csvdiff
csvdiff/__init__.py
patch_records
def patch_records(diff, from_records, strict=True): """ Apply the patch to the sequence of records, returning the transformed records. """ return patch.apply(diff, from_records, strict=strict)
python
def patch_records(diff, from_records, strict=True): """ Apply the patch to the sequence of records, returning the transformed records. """ return patch.apply(diff, from_records, strict=strict)
Apply the patch to the sequence of records, returning the transformed records.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L73-L78
larsyencken/csvdiff
csvdiff/__init__.py
_nice_fieldnames
def _nice_fieldnames(all_columns, index_columns): "Indexes on the left, other fields in alphabetical order on the right." non_index_columns = set(all_columns).difference(index_columns) return index_columns + sorted(non_index_columns)
python
def _nice_fieldnames(all_columns, index_columns): "Indexes on the left, other fields in alphabetical order on the right." non_index_columns = set(all_columns).difference(index_columns) return index_columns + sorted(non_index_columns)
Indexes on the left, other fields in alphabetical order on the right.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L81-L84
larsyencken/csvdiff
csvdiff/__init__.py
csvdiff_cmd
def csvdiff_cmd(index_columns, from_csv, to_csv, style=None, output=None, sep=',', quiet=False, ignore_columns=None, significance=None): """ Compare two csv files to see what rows differ between them. The files are each expected to have a header row, and for each row to be uniquely ident...
python
def csvdiff_cmd(index_columns, from_csv, to_csv, style=None, output=None, sep=',', quiet=False, ignore_columns=None, significance=None): """ Compare two csv files to see what rows differ between them. The files are each expected to have a header row, and for each row to be uniquely ident...
Compare two csv files to see what rows differ between them. The files are each expected to have a header row, and for each row to be uniquely identified by one or more indexing columns.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L128-L160
larsyencken/csvdiff
csvdiff/__init__.py
_diff_and_summarize
def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout, sep=',', ignored_columns=None, significance=None): """ Print a summary of the difference between the two files. """ from_records = list(records.load(from_csv, sep=sep)) to_records = records.load(to_cs...
python
def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout, sep=',', ignored_columns=None, significance=None): """ Print a summary of the difference between the two files. """ from_records = list(records.load(from_csv, sep=sep)) to_records = records.load(to_cs...
Print a summary of the difference between the two files.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L178-L194
larsyencken/csvdiff
csvdiff/__init__.py
csvpatch_cmd
def csvpatch_cmd(input_csv, input=None, output=None, strict=True): """ Apply the changes from a csvdiff patch to an existing CSV file. """ patch_stream = (sys.stdin if input is None else open(input)) tocsv_stream = (sys.stdout if output is ...
python
def csvpatch_cmd(input_csv, input=None, output=None, strict=True): """ Apply the changes from a csvdiff patch to an existing CSV file. """ patch_stream = (sys.stdin if input is None else open(input)) tocsv_stream = (sys.stdout if output is ...
Apply the changes from a csvdiff patch to an existing CSV file.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L229-L250
larsyencken/csvdiff
csvdiff/records.py
sort
def sort(records: Sequence[Record]) -> List[Record]: "Sort records into a canonical order, suitable for comparison." return sorted(records, key=_record_key)
python
def sort(records: Sequence[Record]) -> List[Record]: "Sort records into a canonical order, suitable for comparison." return sorted(records, key=_record_key)
Sort records into a canonical order, suitable for comparison.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/records.py#L86-L88
larsyencken/csvdiff
csvdiff/records.py
_record_key
def _record_key(record: Record) -> List[Tuple[Column, str]]: "An orderable representation of this record." return sorted(record.items())
python
def _record_key(record: Record) -> List[Tuple[Column, str]]: "An orderable representation of this record." return sorted(record.items())
An orderable representation of this record.
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/records.py#L91-L93
Stewori/pytypes
pytypes/typecomment_parser.py
_outter_split
def _outter_split(inpt, delim, openers, closers=None, opener_lookup=None): """Splits only at delims that are at outter-most level regarding openers/closers pairs. Unchecked requirements: Only supports length-1 delim, openers and closers. delim must not be member of openers or closers. len(opener...
python
def _outter_split(inpt, delim, openers, closers=None, opener_lookup=None): """Splits only at delims that are at outter-most level regarding openers/closers pairs. Unchecked requirements: Only supports length-1 delim, openers and closers. delim must not be member of openers or closers. len(opener...
Splits only at delims that are at outter-most level regarding openers/closers pairs. Unchecked requirements: Only supports length-1 delim, openers and closers. delim must not be member of openers or closers. len(openers) == len(closers) or closers == None
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/typecomment_parser.py#L94-L120
Stewori/pytypes
pytypes/util.py
getargspecs
def getargspecs(func): """Bridges inspect.getargspec and inspect.getfullargspec. Automatically selects the proper one depending of current Python version. Automatically bypasses wrappers from typechecked- and override-decorators. """ if func is None: raise TypeError('None is not a Python fun...
python
def getargspecs(func): """Bridges inspect.getargspec and inspect.getfullargspec. Automatically selects the proper one depending of current Python version. Automatically bypasses wrappers from typechecked- and override-decorators. """ if func is None: raise TypeError('None is not a Python fun...
Bridges inspect.getargspec and inspect.getfullargspec. Automatically selects the proper one depending of current Python version. Automatically bypasses wrappers from typechecked- and override-decorators.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L94-L108
Stewori/pytypes
pytypes/util.py
get_required_kwonly_args
def get_required_kwonly_args(argspecs): """Determines whether given argspecs implies required keywords-only args and returns them as a list. Returns empty list if no such args exist. """ try: kwonly = argspecs.kwonlyargs if argspecs.kwonlydefaults is None: return kwonly ...
python
def get_required_kwonly_args(argspecs): """Determines whether given argspecs implies required keywords-only args and returns them as a list. Returns empty list if no such args exist. """ try: kwonly = argspecs.kwonlyargs if argspecs.kwonlydefaults is None: return kwonly ...
Determines whether given argspecs implies required keywords-only args and returns them as a list. Returns empty list if no such args exist.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L111-L125
Stewori/pytypes
pytypes/util.py
getargnames
def getargnames(argspecs, with_unbox=False): """Resembles list of arg-names as would be seen in a function signature, including var-args, var-keywords and keyword-only args. """ # todo: We can maybe make use of inspect.formatargspec args = argspecs.args vargs = argspecs.varargs try: ...
python
def getargnames(argspecs, with_unbox=False): """Resembles list of arg-names as would be seen in a function signature, including var-args, var-keywords and keyword-only args. """ # todo: We can maybe make use of inspect.formatargspec args = argspecs.args vargs = argspecs.varargs try: ...
Resembles list of arg-names as would be seen in a function signature, including var-args, var-keywords and keyword-only args.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L128-L152
Stewori/pytypes
pytypes/util.py
fromargskw
def fromargskw(argskw, argspecs, slf_or_clsm = False): """Turns a linearized list of args into (args, keywords) form according to given argspecs (like inspect module provides). """ res_args = argskw try: kwds = argspecs.keywords except AttributeError: kwds = argspecs.varkw if...
python
def fromargskw(argskw, argspecs, slf_or_clsm = False): """Turns a linearized list of args into (args, keywords) form according to given argspecs (like inspect module provides). """ res_args = argskw try: kwds = argspecs.keywords except AttributeError: kwds = argspecs.varkw if...
Turns a linearized list of args into (args, keywords) form according to given argspecs (like inspect module provides).
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L240-L274
Stewori/pytypes
pytypes/util.py
get_staticmethod_qualname
def get_staticmethod_qualname(staticmeth): """Determines the fully qualified name of a static method. Yields a result similar to what __qualname__ would contain, but is applicable to static methods and also works in Python 2.7. """ func = _actualfunc(staticmeth) module = sys.modules[func.__modul...
python
def get_staticmethod_qualname(staticmeth): """Determines the fully qualified name of a static method. Yields a result similar to what __qualname__ would contain, but is applicable to static methods and also works in Python 2.7. """ func = _actualfunc(staticmeth) module = sys.modules[func.__modul...
Determines the fully qualified name of a static method. Yields a result similar to what __qualname__ would contain, but is applicable to static methods and also works in Python 2.7.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L358-L367
Stewori/pytypes
pytypes/util.py
get_class_qualname
def get_class_qualname(cls): """Determines the fully qualified name of a class. Yields a result similar to what __qualname__ contains, but also works on Python 2.7. """ if hasattr(cls, '__qualname__'): return cls.__qualname__ module = sys.modules[cls.__module__] if cls.__module__ == ...
python
def get_class_qualname(cls): """Determines the fully qualified name of a class. Yields a result similar to what __qualname__ contains, but also works on Python 2.7. """ if hasattr(cls, '__qualname__'): return cls.__qualname__ module = sys.modules[cls.__module__] if cls.__module__ == ...
Determines the fully qualified name of a class. Yields a result similar to what __qualname__ contains, but also works on Python 2.7.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L370-L388
Stewori/pytypes
pytypes/util.py
search_class_module
def search_class_module(cls, deep_search=True): """E.g. if cls is a TypeVar, cls.__module__ won't contain the actual module that declares cls. This returns the actual module declaring cls. Can be used with any class (not only TypeVar), though usually cls.__module__ is the recommended way. If deep_se...
python
def search_class_module(cls, deep_search=True): """E.g. if cls is a TypeVar, cls.__module__ won't contain the actual module that declares cls. This returns the actual module declaring cls. Can be used with any class (not only TypeVar), though usually cls.__module__ is the recommended way. If deep_se...
E.g. if cls is a TypeVar, cls.__module__ won't contain the actual module that declares cls. This returns the actual module declaring cls. Can be used with any class (not only TypeVar), though usually cls.__module__ is the recommended way. If deep_search is True (default) this even finds the correct modu...
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L391-L412
Stewori/pytypes
pytypes/util.py
get_class_that_defined_method
def get_class_that_defined_method(meth): """Determines the class owning the given method. """ if is_classmethod(meth): return meth.__self__ if hasattr(meth, 'im_class'): return meth.im_class elif hasattr(meth, '__qualname__'): # Python 3 try: cls_names = m...
python
def get_class_that_defined_method(meth): """Determines the class owning the given method. """ if is_classmethod(meth): return meth.__self__ if hasattr(meth, 'im_class'): return meth.im_class elif hasattr(meth, '__qualname__'): # Python 3 try: cls_names = m...
Determines the class owning the given method.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L415-L437
Stewori/pytypes
pytypes/util.py
is_method
def is_method(func): """Detects if the given callable is a method. In context of pytypes this function is more reliable than plain inspect.ismethod, e.g. it automatically bypasses wrappers from typechecked and override decorators. """ func0 = _actualfunc(func) argNames = getargnames(getargspecs(...
python
def is_method(func): """Detects if the given callable is a method. In context of pytypes this function is more reliable than plain inspect.ismethod, e.g. it automatically bypasses wrappers from typechecked and override decorators. """ func0 = _actualfunc(func) argNames = getargnames(getargspecs(...
Detects if the given callable is a method. In context of pytypes this function is more reliable than plain inspect.ismethod, e.g. it automatically bypasses wrappers from typechecked and override decorators.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L440-L460
Stewori/pytypes
pytypes/util.py
is_classmethod
def is_classmethod(meth): """Detects if the given callable is a classmethod. """ if inspect.ismethoddescriptor(meth): return isinstance(meth, classmethod) if not inspect.ismethod(meth): return False if not inspect.isclass(meth.__self__): return False if not hasattr(meth._...
python
def is_classmethod(meth): """Detects if the given callable is a classmethod. """ if inspect.ismethoddescriptor(meth): return isinstance(meth, classmethod) if not inspect.ismethod(meth): return False if not inspect.isclass(meth.__self__): return False if not hasattr(meth._...
Detects if the given callable is a classmethod.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L463-L474
Stewori/pytypes
pytypes/util.py
get_current_args
def get_current_args(caller_level = 0, func = None, argNames = None): """Determines the args of current function call. Use caller_level > 0 to get args of even earlier function calls in current stack. """ if argNames is None: argNames = getargnames(getargspecs(func)) if func is None: ...
python
def get_current_args(caller_level = 0, func = None, argNames = None): """Determines the args of current function call. Use caller_level > 0 to get args of even earlier function calls in current stack. """ if argNames is None: argNames = getargnames(getargspecs(func)) if func is None: ...
Determines the args of current function call. Use caller_level > 0 to get args of even earlier function calls in current stack.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L531-L543
Stewori/pytypes
pytypes/util.py
getmodule
def getmodule(code): """More robust variant of inspect.getmodule. E.g. has less issues on Jython. """ try: md = inspect.getmodule(code, code.co_filename) except AttributeError: return inspect.getmodule(code) if md is None: # Jython-specific: # This is currently ju...
python
def getmodule(code): """More robust variant of inspect.getmodule. E.g. has less issues on Jython. """ try: md = inspect.getmodule(code, code.co_filename) except AttributeError: return inspect.getmodule(code) if md is None: # Jython-specific: # This is currently ju...
More robust variant of inspect.getmodule. E.g. has less issues on Jython.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L551-L568
Stewori/pytypes
pytypes/util.py
get_callable_fq_for_code
def get_callable_fq_for_code(code, locals_dict = None): """Determines the function belonging to a given code object in a fully qualified fashion. Returns a tuple consisting of - the callable - a list of classes and inner classes, locating the callable (like a fully qualified name) - a boolean indica...
python
def get_callable_fq_for_code(code, locals_dict = None): """Determines the function belonging to a given code object in a fully qualified fashion. Returns a tuple consisting of - the callable - a list of classes and inner classes, locating the callable (like a fully qualified name) - a boolean indica...
Determines the function belonging to a given code object in a fully qualified fashion. Returns a tuple consisting of - the callable - a list of classes and inner classes, locating the callable (like a fully qualified name) - a boolean indicating whether the callable is a method
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L582-L604
Stewori/pytypes
pytypes/util.py
_calc_traceback_limit
def _calc_traceback_limit(tb): """Calculates limit-parameter to strip away pytypes' internals when used with API from traceback module. """ limit = 1 tb2 = tb while not tb2.tb_next is None: try: maybe_pytypes = tb2.tb_next.tb_frame.f_code.co_filename.split(os.sep)[-2] ...
python
def _calc_traceback_limit(tb): """Calculates limit-parameter to strip away pytypes' internals when used with API from traceback module. """ limit = 1 tb2 = tb while not tb2.tb_next is None: try: maybe_pytypes = tb2.tb_next.tb_frame.f_code.co_filename.split(os.sep)[-2] ...
Calculates limit-parameter to strip away pytypes' internals when used with API from traceback module.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L758-L775
Stewori/pytypes
pytypes/util.py
_pytypes_excepthook
def _pytypes_excepthook(exctype, value, tb): """"An excepthook suitable for use as sys.excepthook, that strips away the part of the traceback belonging to pytypes' internals. Can be switched on and off via pytypes.clean_traceback or pytypes.set_clean_traceback. The latter automatically installs this...
python
def _pytypes_excepthook(exctype, value, tb): """"An excepthook suitable for use as sys.excepthook, that strips away the part of the traceback belonging to pytypes' internals. Can be switched on and off via pytypes.clean_traceback or pytypes.set_clean_traceback. The latter automatically installs this...
An excepthook suitable for use as sys.excepthook, that strips away the part of the traceback belonging to pytypes' internals. Can be switched on and off via pytypes.clean_traceback or pytypes.set_clean_traceback. The latter automatically installs this hook in sys.excepthook.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L817-L830
Stewori/pytypes
pytypes/type_util.py
get_generator_type
def get_generator_type(genr): """Obtains PEP 484 style type of a generator object, i.e. returns a typing.Generator object. """ if genr in _checked_generator_types: return _checked_generator_types[genr] if not genr.gi_frame is None and 'gen_type' in genr.gi_frame.f_locals: return genr...
python
def get_generator_type(genr): """Obtains PEP 484 style type of a generator object, i.e. returns a typing.Generator object. """ if genr in _checked_generator_types: return _checked_generator_types[genr] if not genr.gi_frame is None and 'gen_type' in genr.gi_frame.f_locals: return genr...
Obtains PEP 484 style type of a generator object, i.e. returns a typing.Generator object.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L109-L122
Stewori/pytypes
pytypes/type_util.py
get_iterable_itemtype
def get_iterable_itemtype(obj): """Attempts to get an iterable's itemtype without iterating over it, not even partly. Note that iterating over an iterable might modify its inner state, e.g. if it is an iterator. Note that obj is expected to be an iterable, not a typing.Iterable. This function levera...
python
def get_iterable_itemtype(obj): """Attempts to get an iterable's itemtype without iterating over it, not even partly. Note that iterating over an iterable might modify its inner state, e.g. if it is an iterator. Note that obj is expected to be an iterable, not a typing.Iterable. This function levera...
Attempts to get an iterable's itemtype without iterating over it, not even partly. Note that iterating over an iterable might modify its inner state, e.g. if it is an iterator. Note that obj is expected to be an iterable, not a typing.Iterable. This function leverages various alternative ways to obtain ...
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L125-L170
Stewori/pytypes
pytypes/type_util.py
get_Generic_itemtype
def get_Generic_itemtype(sq, simplify=True): """Retrieves the item type from a PEP 484 generic or subclass of such. sq must be a typing.Tuple or (subclass of) typing.Iterable or typing.Container. Consequently this also works with typing.List, typing.Set and typing.Dict. Note that for typing.Dict and map...
python
def get_Generic_itemtype(sq, simplify=True): """Retrieves the item type from a PEP 484 generic or subclass of such. sq must be a typing.Tuple or (subclass of) typing.Iterable or typing.Container. Consequently this also works with typing.List, typing.Set and typing.Dict. Note that for typing.Dict and map...
Retrieves the item type from a PEP 484 generic or subclass of such. sq must be a typing.Tuple or (subclass of) typing.Iterable or typing.Container. Consequently this also works with typing.List, typing.Set and typing.Dict. Note that for typing.Dict and mapping types in general, the key type is regarded as i...
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L173-L201
Stewori/pytypes
pytypes/type_util.py
get_Mapping_key_value
def get_Mapping_key_value(mp): """Retrieves the key and value types from a PEP 484 mapping or subclass of such. mp must be a (subclass of) typing.Mapping. """ try: res = _select_Generic_superclass_parameters(mp, typing.Mapping) except TypeError: res = None if res is None: ...
python
def get_Mapping_key_value(mp): """Retrieves the key and value types from a PEP 484 mapping or subclass of such. mp must be a (subclass of) typing.Mapping. """ try: res = _select_Generic_superclass_parameters(mp, typing.Mapping) except TypeError: res = None if res is None: ...
Retrieves the key and value types from a PEP 484 mapping or subclass of such. mp must be a (subclass of) typing.Mapping.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L204-L215
Stewori/pytypes
pytypes/type_util.py
get_Generic_parameters
def get_Generic_parameters(tp, generic_supertype): """tp must be a subclass of generic_supertype. Retrieves the type values from tp that correspond to parameters defined by generic_supertype. E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent to get_Mapping_key_value(tp) except for the e...
python
def get_Generic_parameters(tp, generic_supertype): """tp must be a subclass of generic_supertype. Retrieves the type values from tp that correspond to parameters defined by generic_supertype. E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent to get_Mapping_key_value(tp) except for the e...
tp must be a subclass of generic_supertype. Retrieves the type values from tp that correspond to parameters defined by generic_supertype. E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent to get_Mapping_key_value(tp) except for the error message. Note that get_Generic_itemtype(tp) is n...
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L218-L238
Stewori/pytypes
pytypes/type_util.py
get_Tuple_params
def get_Tuple_params(tpl): """Python version independent function to obtain the parameters of a typing.Tuple object. Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. """ try: return tpl.__tuple_params__ except...
python
def get_Tuple_params(tpl): """Python version independent function to obtain the parameters of a typing.Tuple object. Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. """ try: return tpl.__tuple_params__ except...
Python version independent function to obtain the parameters of a typing.Tuple object. Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L241-L262
Stewori/pytypes
pytypes/type_util.py
is_Tuple_ellipsis
def is_Tuple_ellipsis(tpl): """Python version independent function to check if a typing.Tuple object contains an ellipsis.""" try: return tpl.__tuple_use_ellipsis__ except AttributeError: try: if tpl.__args__ is None: return False # Python 3.6 ...
python
def is_Tuple_ellipsis(tpl): """Python version independent function to check if a typing.Tuple object contains an ellipsis.""" try: return tpl.__tuple_use_ellipsis__ except AttributeError: try: if tpl.__args__ is None: return False # Python 3.6 ...
Python version independent function to check if a typing.Tuple object contains an ellipsis.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L265-L279
Stewori/pytypes
pytypes/type_util.py
get_Callable_args_res
def get_Callable_args_res(clb): """Python version independent function to obtain the parameters of a typing.Callable object. Returns as tuple: args, result. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. """ try: return clb.__args__, clb.__result__ except AttributeError: # P...
python
def get_Callable_args_res(clb): """Python version independent function to obtain the parameters of a typing.Callable object. Returns as tuple: args, result. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. """ try: return clb.__args__, clb.__result__ except AttributeError: # P...
Python version independent function to obtain the parameters of a typing.Callable object. Returns as tuple: args, result. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L294-L303
Stewori/pytypes
pytypes/type_util.py
is_Type
def is_Type(tp): """Python version independent check if an object is a type. For Python 3.7 onwards(?) this is not equivalent to ``isinstance(tp, type)`` any more, as that call would return ``False`` for PEP 484 types. Tested with CPython 2.7, 3.5, 3.6, 3.7 and Jython 2.7.1. """ if isinstanc...
python
def is_Type(tp): """Python version independent check if an object is a type. For Python 3.7 onwards(?) this is not equivalent to ``isinstance(tp, type)`` any more, as that call would return ``False`` for PEP 484 types. Tested with CPython 2.7, 3.5, 3.6, 3.7 and Jython 2.7.1. """ if isinstanc...
Python version independent check if an object is a type. For Python 3.7 onwards(?) this is not equivalent to ``isinstance(tp, type)`` any more, as that call would return ``False`` for PEP 484 types. Tested with CPython 2.7, 3.5, 3.6, 3.7 and Jython 2.7.1.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L320-L333
Stewori/pytypes
pytypes/type_util.py
is_Union
def is_Union(tp): """Python version independent check if a type is typing.Union. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. """ if tp is Union: return True try: # Python 3.6 return tp.__origin__ is Union except AttributeError: try: return isin...
python
def is_Union(tp): """Python version independent check if a type is typing.Union. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. """ if tp is Union: return True try: # Python 3.6 return tp.__origin__ is Union except AttributeError: try: return isin...
Python version independent check if a type is typing.Union. Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L336-L349
Stewori/pytypes
pytypes/type_util.py
deep_type
def deep_type(obj, depth = None, max_sample = None, get_type = None): """Tries to construct a type for a given value. In contrast to type(...), deep_type does its best to fit structured types from typing as close as possible to the given value. E.g. deep_type((1, 2, 'a')) will return Tuple[int, int, str...
python
def deep_type(obj, depth = None, max_sample = None, get_type = None): """Tries to construct a type for a given value. In contrast to type(...), deep_type does its best to fit structured types from typing as close as possible to the given value. E.g. deep_type((1, 2, 'a')) will return Tuple[int, int, str...
Tries to construct a type for a given value. In contrast to type(...), deep_type does its best to fit structured types from typing as close as possible to the given value. E.g. deep_type((1, 2, 'a')) will return Tuple[int, int, str] rather than just tuple. Supports various types from typing, but not...
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L389-L405