Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | # |
| 3 | # Copyright 2010 Google Inc. |
| 4 | # |
| 5 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | # you may not use this file except in compliance with the License. |
| 7 | # You may obtain a copy of the License at |
| 8 | # |
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | # |
| 11 | # Unless required by applicable law or agreed to in writing, software |
| 12 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | # See the License for the specific language governing permissions and |
| 15 | # limitations under the License. |
| 16 | # |
| 17 | |
| 18 | """Common utility library.""" |
| 19 | |
| 20 | __author__ = ['rafek@google.com (Rafe Kaplan)', |
| 21 | 'guido@google.com (Guido van Rossum)', |
| 22 | ] |
| 23 | __all__ = [ |
| 24 | 'positional', |
| 25 | ] |
| 26 | |
| 27 | import gflags |
| 28 | import inspect |
| 29 | import logging |
Joe Gregorio | 5cf5d12 | 2012-11-16 16:36:12 -0500 | [diff] [blame] | 30 | import types |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 31 | |
| 32 | logger = logging.getLogger(__name__) |
| 33 | |
| 34 | FLAGS = gflags.FLAGS |
| 35 | |
| 36 | gflags.DEFINE_enum('positional_parameters_enforcement', 'WARNING', |
| 37 | ['EXCEPTION', 'WARNING', 'IGNORE'], |
| 38 | 'The action when an oauth2client.util.positional declaration is violated.') |
| 39 | |
| 40 | |
| 41 | def positional(max_positional_args): |
| 42 | """A decorator to declare that only the first N arguments my be positional. |
| 43 | |
| 44 | This decorator makes it easy to support Python 3 style key-word only |
Joe Gregorio | e2233cd | 2013-01-24 15:46:23 -0500 | [diff] [blame^] | 45 | parameters. For example, in Python 3 it is possible to write: |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 46 | |
| 47 | def fn(pos1, *, kwonly1=None, kwonly1=None): |
| 48 | ... |
| 49 | |
| 50 | All named parameters after * must be a keyword: |
| 51 | |
| 52 | fn(10, 'kw1', 'kw2') # Raises exception. |
| 53 | fn(10, kwonly1='kw1') # Ok. |
| 54 | |
| 55 | Example: |
| 56 | To define a function like above, do: |
| 57 | |
| 58 | @positional(1) |
| 59 | def fn(pos1, kwonly1=None, kwonly2=None): |
| 60 | ... |
| 61 | |
| 62 | If no default value is provided to a keyword argument, it becomes a required |
| 63 | keyword argument: |
| 64 | |
| 65 | @positional(0) |
| 66 | def fn(required_kw): |
| 67 | ... |
| 68 | |
| 69 | This must be called with the keyword parameter: |
| 70 | |
| 71 | fn() # Raises exception. |
| 72 | fn(10) # Raises exception. |
| 73 | fn(required_kw=10) # Ok. |
| 74 | |
| 75 | When defining instance or class methods always remember to account for |
| 76 | 'self' and 'cls': |
| 77 | |
| 78 | class MyClass(object): |
| 79 | |
| 80 | @positional(2) |
| 81 | def my_method(self, pos1, kwonly1=None): |
| 82 | ... |
| 83 | |
| 84 | @classmethod |
| 85 | @positional(2) |
| 86 | def my_method(cls, pos1, kwonly1=None): |
| 87 | ... |
| 88 | |
| 89 | The positional decorator behavior is controlled by the |
| 90 | --positional_parameters_enforcement flag. The flag may be set to 'EXCEPTION', |
| 91 | 'WARNING' or 'IGNORE' to raise an exception, log a warning, or do nothing, |
| 92 | respectively, if a declaration is violated. |
| 93 | |
| 94 | Args: |
Joe Gregorio | e2233cd | 2013-01-24 15:46:23 -0500 | [diff] [blame^] | 95 | max_positional_arguments: Maximum number of positional arguments. All |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 96 | parameters after the this index must be keyword only. |
| 97 | |
| 98 | Returns: |
| 99 | A decorator that prevents using arguments after max_positional_args from |
| 100 | being used as positional parameters. |
| 101 | |
| 102 | Raises: |
| 103 | TypeError if a key-word only argument is provided as a positional parameter, |
| 104 | but only if the --positional_parameters_enforcement flag is set to |
| 105 | 'EXCEPTION'. |
| 106 | """ |
| 107 | def positional_decorator(wrapped): |
| 108 | def positional_wrapper(*args, **kwargs): |
| 109 | if len(args) > max_positional_args: |
| 110 | plural_s = '' |
| 111 | if max_positional_args != 1: |
| 112 | plural_s = 's' |
| 113 | message = '%s() takes at most %d positional argument%s (%d given)' % ( |
| 114 | wrapped.__name__, max_positional_args, plural_s, len(args)) |
| 115 | if FLAGS.positional_parameters_enforcement == 'EXCEPTION': |
| 116 | raise TypeError(message) |
| 117 | elif FLAGS.positional_parameters_enforcement == 'WARNING': |
| 118 | logger.warning(message) |
| 119 | else: # IGNORE |
| 120 | pass |
| 121 | return wrapped(*args, **kwargs) |
| 122 | return positional_wrapper |
| 123 | |
| 124 | if isinstance(max_positional_args, (int, long)): |
| 125 | return positional_decorator |
| 126 | else: |
| 127 | args, _, _, defaults = inspect.getargspec(max_positional_args) |
| 128 | return positional(len(args) - len(defaults))(max_positional_args) |
Joe Gregorio | 5cf5d12 | 2012-11-16 16:36:12 -0500 | [diff] [blame] | 129 | |
| 130 | |
| 131 | def scopes_to_string(scopes): |
| 132 | """Converts scope value to a string. |
| 133 | |
| 134 | If scopes is a string then it is simply passed through. If scopes is an |
| 135 | iterable then a string is returned that is all the individual scopes |
| 136 | concatenated with spaces. |
| 137 | |
| 138 | Args: |
| 139 | scopes: string or iterable of strings, the scopes. |
| 140 | |
| 141 | Returns: |
| 142 | The scopes formatted as a single string. |
| 143 | """ |
| 144 | if isinstance(scopes, types.StringTypes): |
| 145 | return scopes |
| 146 | else: |
| 147 | return ' '.join(scopes) |
Joe Gregorio | e2233cd | 2013-01-24 15:46:23 -0500 | [diff] [blame^] | 148 | |
| 149 | |
| 150 | def dict_to_tuple_key(dictionary): |
| 151 | """Converts a dictionary to a tuple that can be used as an immutable key. |
| 152 | |
| 153 | The resulting key is always sorted so that logically equivalent dictionaries |
| 154 | always produce an identical tuple for a key. |
| 155 | |
| 156 | Args: |
| 157 | dictionary: the dictionary to use as the key. |
| 158 | |
| 159 | Returns: |
| 160 | A tuple representing the dictionary in it's naturally sorted ordering. |
| 161 | """ |
| 162 | return tuple(sorted(dictionary.items())) |