def check_is_argument(arg, func): if not arg in getfullargspec(func).args: raise NameError('%r is not an argument of %s' % (arg, func))
def pandas_wrap(f, return_col=None): # Extract the signature arguments from this function. spec = getfullargspec(f) rtype = None return_sig = spec.annotations.get("return", None) if not (return_col or return_sig): raise ValueError( "Missing type information. It should either be provided as an argument to pandas_wrap," "or as a python typing hint") if return_col is not None: rtype = _to_stype(return_col) if return_sig is not None: rtype = _to_stype(return_sig) # Extract the input signatures, if any: sig_args = [] sig_kwargs = {} for key in spec.args: t = spec.annotations.get(key, None) if t is not None: dt = _to_stype(t) else: dt = _Unknown(None) sig_kwargs[key] = dt sig_args.append(dt) f.sig_return = rtype f.sig_args = sig_args f.sig_kwargs = sig_kwargs return decorate(f, make_fun)
def wrapped_f(*args, **kwargs): # Get a list of the names of the non-keyword arguments if "_user" in kwargs: _user = kwargs["_user"] else: # TODO: Add support for keyword arguments, can be convenient in cases where code is called from python _argument_specifications = getfullargspec(func) try: # Try and find _session_id user_idx = _argument_specifications.args.index("_user") except: raise Exception("Has right aspect for \"" + func.__name__ + "\": No _user parameter in function, internal error.") if user_idx > len(args) - 1: raise Exception( "Has right aspect for \"" + func.__name__ + "\": The _user parameter isn't supplied.") _user = args[user_idx] if isinstance(_rights, list): has_right(_rights, _user) elif callable(_rights): has_right(_rights(), _user) return func(*args, **kwargs)
def caller(f, *args, **kwargs): spec = getfullargspec(f) if arg not in spec.args + spec.kwonlyargs: raise ValueError("in_name arg %s not in spec %s" % (arg, spec.args + spec.kwonlyargs)) arg_pos = spec.args.index(arg) if arg in spec.args else None return __in_name(f, arg, arg_pos, name, shape, drop_names, optional, *args, **kwargs)
def get_ui_commands(self): for attr in dir(self): if not attr.startswith('ui_command_'): continue val = getattr(self, attr) argspec = getfullargspec(val) yield ( attr, dict( argspec=argspec, method=inspect.ismethod(val), function=inspect.isfunction(val), ) )
# # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. import ast import inspect from decorator import getfullargspec from openquake.baselib import sap from openquake.calculators.views import rst_table from openquake.commonlib import logs from openquake.server import dbserver from openquake.server.db import actions commands = {} for func in vars(actions).values(): if inspect.isfunction(func): # is really a function argspec = getfullargspec(func) if argspec.args[0] == 'db': # is a db action commands[func.__name__] = argspec.args[1:] def convert(strings): """ Convert strings into literal Python objects """ for s in strings: try: yield ast.literal_eval(s) except: yield s
from decorator import decorator, getfullargspec @decorator def logar(f, fmt='%H:%M:%S', *args, **kwargs): print(strftime(fmt)) return f(*args, **kwargs) @logar() def mochileiro(): return 42 @logar(fmt='%d/%m/%Y %H:%M:%S') def ola(nome): return f'Olá {nome}' if __name__ == '__main__': print(getfullargspec(ola)) print(getfullargspec(mochileiro)) print(mochileiro()) print(mochileiro.__name__) print(ola('Renzo')) print(ola.__name__) sleep(1) print(mochileiro()) print(ola('Luciano'))
def decorator(f): @wraps(f) def executar_com_tempo(*arg, **kwargs): print(strftime(fmt)) return f(*arg, **kwargs) return executar_com_tempo return decorator @logar def mochileiro(): return 42 @logar(fmt='%d-%m-%Y %H:%M:%S') def ola(nome): return f'Olá {nome}' if __name__ == '__main__': print(getfullargspec(ola)) print(mochileiro()) print(mochileiro.__name__) print(ola('André')) print(ola.__name__) sleep(1) print(mochileiro()) print(ola('Liciano'))
def _prepare_metaclass(cls, namespace, responsible_account): """Build a dataClay "MetaClass" for this class. :param str namespace: The namespace for this class' MetaClass. :param str responsible_account: Responsible account's username. :return: A MetaClass Container. """ try: class_extradata = cls.get_class_extradata() except AttributeError: raise ValueError( "MetaClass can only be prepared for correctly initialized DataClay Classes" ) logger.verbose("Preparing MetaClass container for class %s (%s)", class_extradata.classname, class_extradata.full_name) # The thing we are being asked (this method will keep populating it) current_python_info = PythonClassInfo(imports=list()) current_class = MetaClass( namespace=namespace, name=class_extradata.full_name, parentType=None, operations=list(), properties=list(), isAbstract=False, languageDepInfos={'LANG_PYTHON': current_python_info}) #################################################################### # OPERATIONS #################################################################### predicate = inspect.isfunction if six.PY3 else inspect.ismethod for name, dataclay_func in inspect.getmembers(cls, predicate): # Consider only functions with _dclay_method if not getattr(dataclay_func, "_dclay_method", False): logger.verbose( "Method `%s` doesn't have attribute `_dclay_method`", dataclay_func) continue original_func = dataclay_func._dclay_entrypoint logger.debug( "MetaClass container will contain method `%s`, preparing", name) # Skeleton for the operation current_operation = Operation( namespace=namespace, className=class_extradata.full_name, descriptor=str(), signature=str(), name=name, nameAndDescriptor=name, # TODO: add descriptor? params=dict(), paramsOrder=list(), returnType=Type.build_from_type(dataclay_func._dclay_ret), implementations=list(), isAbstract=False, isStaticConstructor=False) # Start with parameters ######################### # The actual order should be retrieved from the signature signature = getfullargspec(original_func) if signature.varargs or signature.varkw: raise NotImplementedError( "No support for varargs or varkw yet") current_operation.paramsOrder[:] = signature.args[ 1:] # hop over 'self' current_operation.params.update({ k: Type.build_from_type(v) for k, v in dataclay_func._dclay_args.items() }) if len(current_operation.paramsOrder) != len( current_operation.params): raise DataClayException("All the arguments are expected to be annotated, " \ "there is some error in %s::%s|%s" \ % (namespace, class_extradata.full_name, name)) # Follow by implementation ############################ current_implementation = PythonImplementation( responsibleAccountName=responsible_account, namespace=namespace, className=class_extradata.full_name, opNameAndDescriptor=name, # TODO: add descriptor? position=0, includes=list(), accessedProperties=list(), accessedImplementations=list(), requiredQuantitativeFeatures=dict(), requiredQualitativeFeatures=dict(), code=inspect.getsource(dataclay_func._dclay_entrypoint)) current_operation.implementations.append(current_implementation) # Finally, add the built operation container into the class ############################################################# current_class.operations.append(current_operation) #################################################################### # PROPERTIES #################################################################### for n, p in class_extradata.properties.items(): current_property = Property(namespace=namespace, className=class_extradata.full_name, name=n, position=p.position, type=p.type, beforeUpdate=p.beforeUpdate, afterUpdate=p.afterUpdate, inMaster=p.inMaster) current_class.properties.append(current_property) #################################################################### # IMPORTS #################################################################### current_python_info.imports.extend(class_extradata.imports) return current_class