Wrapper around inspect.getsource. This can be modified by other projects to provide customized source extraction. Parameters ---------- obj : object an object whose source code we will attempt to extract oname : str (optional) a name under which the object i
(obj, oname='')
| 133 | |
| 134 | |
| 135 | def getsource(obj, oname='') -> Union[str,None]: |
| 136 | """Wrapper around inspect.getsource. |
| 137 | |
| 138 | This can be modified by other projects to provide customized source |
| 139 | extraction. |
| 140 | |
| 141 | Parameters |
| 142 | ---------- |
| 143 | obj : object |
| 144 | an object whose source code we will attempt to extract |
| 145 | oname : str |
| 146 | (optional) a name under which the object is known |
| 147 | |
| 148 | Returns |
| 149 | ------- |
| 150 | src : unicode or None |
| 151 | |
| 152 | """ |
| 153 | |
| 154 | if isinstance(obj, property): |
| 155 | sources = [] |
| 156 | for attrname in ['fget', 'fset', 'fdel']: |
| 157 | fn = getattr(obj, attrname) |
| 158 | if fn is not None: |
| 159 | encoding = get_encoding(fn) |
| 160 | oname_prefix = ('%s.' % oname) if oname else '' |
| 161 | sources.append(''.join(('# ', oname_prefix, attrname))) |
| 162 | if inspect.isfunction(fn): |
| 163 | sources.append(dedent(getsource(fn))) |
| 164 | else: |
| 165 | # Default str/repr only prints function name, |
| 166 | # pretty.pretty prints module name too. |
| 167 | sources.append( |
| 168 | '%s%s = %s\n' % (oname_prefix, attrname, pretty(fn)) |
| 169 | ) |
| 170 | if sources: |
| 171 | return '\n'.join(sources) |
| 172 | else: |
| 173 | return None |
| 174 | |
| 175 | else: |
| 176 | # Get source for non-property objects. |
| 177 | |
| 178 | obj = _get_wrapped(obj) |
| 179 | |
| 180 | try: |
| 181 | src = inspect.getsource(obj) |
| 182 | except TypeError: |
| 183 | # The object itself provided no meaningful source, try looking for |
| 184 | # its class definition instead. |
| 185 | if hasattr(obj, '__class__'): |
| 186 | try: |
| 187 | src = inspect.getsource(obj.__class__) |
| 188 | except TypeError: |
| 189 | return None |
| 190 | |
| 191 | return src |
| 192 |
no test coverage detected