code
stringlengths
1
18.2k
still set to the default if self._canExecute and self._taskParsObj: # default _canExecute=True self._canExecute = self._taskParsObj.canExecute() self._showExecuteButton = self._canExecute # check on the help string - just to see if it is HTML # (could use HTMLParser here if need be, be quick and simple tho) hhh = self....
elif hhh.startswith('http:') or hhh.startswith('https:'): self._knowTaskHelpIsHtml = True elif hhh.startswith('file:') and \ (hhh.endswith('.htm') or hhh.endswith('.html')): self._knowTaskHelpIsHtml = True
def _doActualSave(self, fname, comment, set_ro=False, overwriteRO=False): """ Override this so we can handle case of file not writable, as well as to make our _lastSavedState copy. """ self.debug('Saving, file name given: '+str(fname)+', set_ro: '+\ str(set_ro)+', overwriteRO: '+str(overwriteRO)) cantWrite = False inIn...
may be installed but not read-only inInstArea = cantWrite = True else: # in case of save-as, allow overwrite of read-only file if overwriteRO and os.path.exists(fname): setWritePrivs(fname, True, True) # try make writable # do the save rv=self._taskParsObj.saveParList(filename=fname,comment=comment) except IOError: can...
that. if cantWrite: fname = self._taskParsObj.getDefaultSaveFilename() # Tell them the context is changing, and where we are saving msg = 'Read-only config file for task "' if inInstArea: msg = 'Installed config file for task "' msg += self._taskParsObj.getName()+'" is not to be overwritten.'+\ ' Values will be saved t...
# Treat like a save-as (update title for ALL save ops) self._saveAsPostSave_Hook(fname) # Limit write privs if requested (only if not in the rc dir) if set_ro and os.path.dirname(os.path.abspath(fname)) != \ os.path.abspath(self._rcDir): cfgpars.checkSetReadOnly(fname) # Before returning, make a copy so we know what wa...
def hasUnsavedChanges(self): """ Determine if there are any edits in the GUI that have not yet been saved (e.g. to a file). """ # Sanity check - this case shouldn't occur assert self._lastSavedState is not None, \ "BUG: Please report this as it should never occur." # Force the current GUI values into our model in memor...
to file, don't even convert bad # values to their previous state in the gui. Note that this can # leave the GUI in a half-saved state, but since we are about to exit # this is OK. We only want prompting to occur if they decide to save. badList = self.checkSetSaveEntries(doSave=False, fleeOnBadVals=True, allowGuiChanges...
the last known saved state. MAKE SURE # the LHS is the actual dict (and not 'self') to invoke the dict # comparison only. return self._lastSavedState != self._taskParsObj
def _defineEditedCallbackObjectFor(self, parScope, parName): """ Override to allow us to use an edited callback. """ # We know that the _taskParsObj is a ConfigObjPars triggerStrs = self._taskParsObj.getTriggerStrings(parScope, parName) # Some items will have a trigger, but likely most won't if triggerStrs and len(trig...
def updateTitle(self, atitle): """ Override so we can append read-only status. """ if atitle and os.path.exists(atitle): if _isInstalled(atitle): atitle += ' [installed]' elif not os.access(atitle, os.W_OK): atitle += ' [read only]' super(ConfigObjEparDialog, self).updateTitle(atitle)
def edited(self, scope, name, lastSavedVal, newVal, action): """ This is the callback function invoked when an item is edited. This is only called for those items which were previously specified to use this mechanism. We do not turn this on for all items because the performance might be prohibitive. This kicks off any ...
this par triggers triggerNamesTup = self._taskParsObj.getTriggerStrings(scope, name) assert triggerNamesTup is not None and len(triggerNamesTup) > 0, \ 'Empty trigger name for: "'+name+'", consult the .cfgspc file.' # Loop through all trigger names - each one is a trigger to kick off - # in the order that they appear i...
in the tuple. for triggerName in triggerNamesTup: # First handle the known/canned trigger names # print (scope, name, newVal, action, triggerName) # DBG: debug line # _section_switch_ if triggerName == '_section_switch_': # Try to uniformly handle all possible par types here, not # just boolean (e.g. str, int, float, e...
(name,)) continue # _2_section_switch_ (see notes above in _section_switch_) if triggerName == '_2_section_switch_': state = newVal not in self.FALSEVALS # toggle most of 1st section (as usual) and ALL of next section self._toggleSectionActiveState(scope, state, (name,)) # get first par of next section (fpons) - is a t...
with embedded code (eg. triggerName=='_rule1_') if '_RULES_' in self._taskParsObj and \ triggerName in self._taskParsObj['_RULES_'].configspec: # Get codeStr to execute it, but before we do so, check 'when' - # make sure this is an action that is allowed to cause a trigger ruleSig = self._taskParsObj['_RULES_'].configs...
didn't specify greenlight = False # do we have a green light to eval the rule? if when2run is None: greenlight = True # means run rule for any possible action else: # 'when' was set to something so we need to check action # check value of action (poor man's enum) assert action in editpar.GROUP_ACTIONS, \ "Unknown actio...
\ str(editpar.GROUP_ACTIONS) # check value of 'when' (allow them to use comma-sep'd str) # (readers be aware that values must be those possible for # 'action', and 'always' is also allowed) whenlist = when2run.split(',') # warn for invalid values for w in whenlist: if not w in editpar.GROUP_ACTIONS and w != 'always': p...
# finally, do the correlation greenlight = 'always' in whenlist or action in whenlist # SECURITY NOTE: because this part executes arbitrary code, that # code string must always be found only in the configspec file, # which is intended to only ever be root-installed w/ the pkg. if codeStr: if not greenlight: continue # ...
...') #dont keep self.top.update_idletasks() #allow msg to draw prior to exec # execute it and retrieve the outcome try: outval = execEmbCode(scope, name, newVal, self, codeStr) except Exception as ex: outval = 'ERROR in '+triggerName+': '+str(ex) print(outval) msg = outval+':\n'+('-'*99)+'\n'+traceback.format_exc() ms...
stroutval = str(outval) if len(stroutval) < 30: msg += ' --> "'+stroutval+'"' self.showStatus(msg, keep=0) # Now that we have triggerName evaluated to outval, we need # to look through all the parameters and see if there are # any items to be affected by triggerName (e.g. '_rule1_') self._applyTriggerValue(triggerName,...
"'+name+'", named: "'+ \ str(triggerName)+'". Please consult the .cfgspc file.')
def findNextSection(self, scope, name): """ Starts with given par (scope+name) and looks further down the list of parameters until one of a different non-null scope is found. Upon success, returns the (scope, name) tuple, otherwise (None, None). """ # first find index of starting point plist = self._taskParsObj.getParL...
= i break else: print('WARNING: could not find starting par: '+scope+'.'+name) return (None, None) # now find first different (non-null) scope in a par, after start for i in range(start, len(plist)): if len(plist[i].scope) > 0 and plist[i].scope != scope: return (plist[i].scope, plist[i].name) # else didn't find it ret...
def _setTaskParsObj(self, theTask): """ Overridden version for ConfigObj. theTask can be either a .cfg file name or a ConfigObjPars object. """ # Create the ConfigObjPars obj self._taskParsObj = cfgpars.getObjectFromTaskArg(theTask, self._strict, False) # Tell it that we can be used for catching debug lines self._taskP...
keyvals. self._lastSavedState = self._taskParsObj.dict()
def _getSaveAsFilter(self): """ Return a string to be used as the filter arg to the save file dialog during Save-As. """ # figure the dir to use, start with the one from the file absRcDir = os.path.abspath(self._rcDir) thedir = os.path.abspath(os.path.dirname(self._taskParsObj.filename)) # skip if not writeable, or if ...
string filt = thedir+'/*.cfg' envVarName = APP_NAME.upper()+'_CFG' if envVarName in os.environ: upx = os.environ[envVarName] if len(upx) > 0: filt = upx+"/*.cfg" # done return filt
def _getOpenChoices(self): """ Go through all possible sites to find applicable .cfg files. Return as an iterable. """ tsk = self._taskParsObj.getName() taskFiles = set() dirsSoFar = [] # this helps speed this up (skip unneeded globs) # last dir aDir = os.path.dirname(self._taskParsObj.filename) if len(aDir) < 1: aDir ...
taskFiles.update(cfgpars.getCfgFilesInDirForTask(aDir, tsk)) # task's python pkg dir (if tsk == python pkg name) try: x, pkgf = cfgpars.findCfgFileForPkg(tsk, '.cfg', taskName=tsk, pkgObj=self._taskParsObj.getAssocPkg()) taskFiles.update( (pkgf,) ) except cfgpars.NoCfgFileError: pass # no big deal - maybe there is no p...
var aDir = dirsSoFar[0] # flag to skip this if no env var found envVarName = APP_NAME.upper()+'_CFG' if envVarName in os.environ: aDir = os.environ[envVarName] if aDir not in dirsSoFar: dirsSoFar.append(aDir) taskFiles.update(cfgpars.getCfgFilesInDirForTask(aDir, tsk)) # At the very end, add an option which we will lat...
end of seq taskFiles.sort() taskFiles.append("Other ...") return taskFiles
def pfopen(self, event=None): """ Load the parameter settings from a user-specified file. """ # Get the selected file name fname = self._openMenuChoice.get() # Also allow them to simply find any file - do not check _task_name_... # (could use tkinter's FileDialog, but this one is prettier) if fname[-3:] == '...': if ca...
= filedlg.PersistLoadFileDialog(self.top, "Load Config File", self._getSaveAsFilter()) if fd.Show() != 1: fd.DialogCleanup() return fname = fd.GetFileName() fd.DialogCleanup() if not fname: return # canceled self.debug('Loading from: '+fname) # load it into a tmp object (use associatedPkg if we have one) try: tmpObj = ...
it is a match if not self._taskParsObj.isSameTaskAs(tmpObj): msg = 'The current task is "'+self._taskParsObj.getName()+ \ '", but the selected file is for task "'+ \ str(tmpObj.getName())+'". This file was not loaded.' showerror(message=msg, title="Error in "+os.path.basename(fname)) self.debug(msg) self.debug(tracebac...
it will take longer, # we need it updated for the copy of the dict we make below except editpar.UnfoundParamError as pe: showwarning(message=str(pe), title="Error in "+os.path.basename(fname)) # trip any triggers self.checkAllTriggers('fopen') # This new fname is our current context self.updateTitle(fname) self._taskPa...
have made no changes yet), make # a copy so we know what the last state was. # The dict() method returns a deep-copy dict of the keyvals. self._lastSavedState = self._taskParsObj.dict()
def _handleParListMismatch(self, probStr, extra=False): """ Override to include ConfigObj filename and specific errors. Note that this only handles "missing" pars and "extra" pars, not wrong-type pars. So it isn't that big of a deal. """ # keep down the duplicate errors if extra: return True # the base class is already...
that to the generic message errmsg = 'Warning: ' if self._strict: errmsg = 'ERROR: ' errmsg = errmsg+'mismatch between default and current par lists ' + \ 'for task "'+self.taskName+'".' if probStr: errmsg += '\n\t'+probStr errmsg += '\nTry editing/deleting: "' + \ self._taskParsObj.filename+'" (or, if in PyRAF: "unlea...
def _setToDefaults(self): """ Load the default parameter settings into the GUI. """ # Create an empty object, where every item is set to it's default value try: tmpObj = cfgpars.ConfigObjPars(self._taskParsObj.filename, associatedPkg=\ self._taskParsObj.getAssocPkg(), setAllToDefaults=self.taskName, strict=False) excep...
= '' # name it later newParList = tmpObj.getParList() try: self.setAllEntriesFromParList(newParList) # needn't updateModel yet self.checkAllTriggers('defaults') self.updateTitle('') self.showStatus("Loaded default "+self.taskName+" values via: "+ \ os.path.basename(tmpObj._original_configspec), keep=1) except editpar.U...
def getDict(self): """ Retrieve the current parameter settings from the GUI.""" # We are going to have to return the dict so let's # first make sure all of our models are up to date with the values in # the GUI right now. badList = self.checkSetSaveEntries(doSave=False) if badList: self.processBadEntries(badList, self....
def loadDict(self, theDict): """ Load the parameter settings from a given dict into the GUI. """ # We are going to have to merge this info into ourselves so let's # first make sure all of our models are up to date with the values in # the GUI right now. badList = self.checkSetSaveEntries(doSave=False) if badList: if no...
is up-to-date # So now we update _taskParsObj with the input dict cfgpars.mergeConfigObj(self._taskParsObj, theDict) # now sync the _taskParsObj dict with its par list model # '\n'.join([str(jj) for jj in self._taskParsObj.getParList()]) self._taskParsObj.syncParamList(False) # Set the GUI entries to these values (let ...
showerror(message=ex.message, title="Error Setting to Loaded Values")
def _getGuiSettings(self): """ Return a dict (ConfigObj) of all user settings found in rcFile. """ # Put the settings into a ConfigObj dict (don't use a config-spec) rcFile = self._rcDir+os.sep+APP_NAME.lower()+'.cfg' if os.path.exists(rcFile): try: return configobj.ConfigObj(rcFile) except: raise RuntimeError('Error p...
def _saveGuiSettings(self): """ The base class doesn't implement this, so we will - save settings (only GUI stuff, not task related) to a file. """ # Put the settings into a ConfigObj dict (don't use a config-spec) rcFile = self._rcDir+os.sep+APP_NAME.lower()+'.cfg' # if os.path.exists(rcFile): os.remove(rcFile) co = c...
= self._flagNonDefaultVals co['frameColor'] = self._frmeColor co['taskBoxColor'] = self._taskColor co['buttonBoxColor'] = self._bboxColor co['entriesColor'] = self._entsColor co['flaggedColor'] = self._flagColor co.initial_comment = ['Automatically generated by '+\ APP_NAME+'. All edits will eventually be overwritten.'...
def _applyTriggerValue(self, triggerName, outval): """ Here we look through the entire .cfgspc to see if any parameters are affected by this trigger. For those that are, we apply the action to the GUI widget. The action is specified by depType. """ # First find which items are dependent upon this trigger (cached) # e.g...
= self._taskParsObj.getParsWhoDependOn(triggerName) if not depParsDict: return if 0: print("Dependent parameters:\n"+str(depParsDict)+"\n") # Get model data, the list of pars theParamList = self._taskParsObj.getParList() # Then go through the dependent pars and apply the trigger to them settingMsg = '' for absName in d...
# diff from makeFullName!! if absName == scopedName: # a match was found depType = depParsDict[absName] if depType == 'active_if': self.entryNo[i].setActiveState(outval) elif depType == 'inactive_if': self.entryNo[i].setActiveState(not outval) elif depType == 'is_set_by': self.entryNo[i].forceValue(outval, noteEdited=T...
depType == 'set_no_if': newval = 'no' self.entryNo[i].forceValue(newval, noteEdited=True) # WARNING! noteEdited=True may start recursion! if len(settingMsg) > 0: settingMsg += ", " settingMsg += '"'+theParamList[i].name+'" to "'+\ newval+'"' else: if len(settingMsg) > 0: settingMsg += ", " settingMsg += '"'+theParamLis...
activate whole section or change # any values, only activate this one self.entryNo[i].setActiveState(True) else: # for off, set the bool par AND grey WHOLE section self.entryNo[i].forceValue(outval, noteEdited=True) self.entryNo[i].setActiveState(False) # we'd need this if the par had no _section_switch_ # self._toggle...
'" for par: "'+scopedName+'"') used = True break # Or maybe it is a whole section if absName.endswith('._section_'): scope = absName[:-10] depType = depParsDict[absName] if depType == 'active_if': self._toggleSectionActiveState(scope, outval, None) elif depType == 'inactive_if': self._toggleSectionActiveState(scope, no...
why ?! self.freshenFocus() self.showStatus('Automatically set '+settingMsg, keep=1)
def readASNTable(fname, output=None, prodonly=False): """ Given a fits filename repesenting an association table reads in the table as a dictionary which can be used by pydrizzle and multidrizzle. An association table is a FITS binary table with 2 required columns: 'MEMNAME', 'MEMTYPE'. It checks 'MEMPRSNT' column and ...
table output : str name of output product - if not specified by the user, the first PROD-DTH name is used if present, if not, the first PROD-RPT name is used if present, if not, the rootname of the input association table is used. prodonly : bool what files should be considered as input if True - select only MEMTYPE=PR...
- select only MEMTYPE=EXP as input Returns ------- asndict : dict A dictionary-like object with all the association information. Examples -------- An association table can be read from a file using the following commands:: >>> from stsci.tools import asnutil >>> asntab = asnutil.readASNTable('j8bt06010_shifts_asn.fits'...
images defined by the association table. """ try: f = fits.open(fu.osfn(fname)) except: raise IOError("Can't open file %s\n" % fname) colnames = f[1].data.names try: colunits = f[1].data.units except AttributeError: pass hdr = f[0].header if 'MEMNAME' not in colnames or 'MEMTYPE' not in colnames: msg = 'Association tab...
= d['MEMPRSNT'].copy() memtype = d['MEMTYPE'].copy() prod_dth = (memtype.find('PROD-DTH')==0).nonzero()[0] prod_rpt = (memtype.find('PROD-RPT')==0).nonzero()[0] prod_crj = (memtype.find('PROD-CRJ')==0).nonzero()[0] # set output name if output is None: if prod_dth: output = d['MEMNAME'][prod_dth[0]] elif prod_rpt: outpu...
d[k][valid_input] infiles = list(d['MEMNAME'].lower()) if not infiles: print("No valid input specified") return None if ('XOFFSET' in colnames and d['XOFFSET'].any()) or ('YOFFSET' in colnames and d['YOFFSET'].any()): abshift = True dshift = False try: units=colunits[colnames.index('XOFFSET')] except: units='pixels' xs...
= list(d['XDELTA']) yshifts = list(d['YDELTA']) else: abshift = False dshift = False members = {} if not abshift and not dshift: asndict = ASNTable(infiles,output=output) asndict.create() return asndict else: try: refimage = hdr['refimage'] except KeyError: refimage = None try: frame = hdr['shframe'] except KeyError: f...
row = r xshift = xshifts[r] yshift = yshifts[r] if rots: rot = rots[r] if scales: scale = scales[r] members[infiles[r]] = ASNMember(row=row, dshift=dshift, abshift=abshift, rot=rot, xshift=xshift, yshift=yshift, scale=scale, refimage=refimage, shift_frame=frame, shift_units=units) asndict= ASNTable(infiles, output=outp...
def write(self, output=None): """ Write association table to a file. """ if not output: outfile = self['output']+'_asn.fits' output = self['output'] else: outfile = output # Delete the file if it exists. if os.path.exists(outfile): warningmsg = "\n#########################################\n" warningmsg += "# #\n" warni...
is being replaced. #\n" warningmsg += "# #\n" warningmsg += "#########################################\n\n" fasn = fits.HDUList() # Compute maximum length of MEMNAME for table column definition _maxlen = 0 for _fname in self['order']: if len(_fname) > _maxlen: _maxlen = len(_fname) # Enforce a mimimum size of 24 if _ma...
for l in self['order']] mtype.append('PROD-DTH') mprsn = [True for l in self['order']] mprsn.append(False) xoff = [self['members'][l]['xoff'] for l in self['order']] xoff.append(0.0) yoff = [self['members'][l]['yoff'] for l in self['order']] yoff.append(0.0) xsh = [self['members'][l]['xshift'] for l in self['order']] x...
memtype = fits.Column(name='MEMTYPE',format='14A',array=N.char.array(mtype)) memprsn = fits.Column(name='MEMPRSNT', format='L', array=N.array(mprsn).astype(N.uint8)) xoffset = fits.Column(name='XOFFSET', format='E', array=N.array(xoff)) yoffset = fits.Column(name='YOFFSET', format='E', array=N.array(yoff)) xdelta = fit...
whdu = wcsutil.WCSObject(refimg) whdu.createReferenceWCS(outfile,overwrite=False) ftab = fits.open(outfile) ftab['primary'].header['refimage'] = outfile+"[wcs]" ftab.close() del whdu
def readShiftFile(self, filename): """ Reads a shift file from disk and populates a dictionary. """ order = [] fshift = open(filename,'r') flines = fshift.readlines() fshift.close() common = [f.strip('#').strip() for f in flines if f.startswith('#')] c=[line.split(': ') for line in common] # Remove any line comments in...
in c: if l[0] not in ['frame', 'refimage', 'form', 'units']: c.remove(l) for line in c: line[1]=line[1].strip() self.update(c) files = [f.strip().split(' ',1) for f in flines if not (f.startswith('#') or f.strip() == '')] for f in files: order.append(f[0]) self['order'] = order for f in files: # Check to see if filenam...
If not, try to convert given rootname into # a valid filename based on available files. This may or may not # define the correct filename, which is why it prints out what it is # doing, so that the user can verify and edit the shiftfile if needed. #NOTE: # Supporting the specification of only rootnames in the shiftfile...
expansion is NOT to be documented, but provided solely as # an undocumented, dangerous and not fully supported helper function for # some backwards compatibility. if not os.path.exists(f[0]): f[0] = fu.buildRootname(f[0]) print('Defining filename in shiftfile as: ', f[0]) f[1] = f[1].split() try: f[1] = [float(s) for s...
a float number' raise ValueError(msg) msg = "At least 2 and at most 4 shift values should be provided in a shiftfile" if len(f[1]) < 2: raise ValueError(msg) elif len(f[1]) == 3: f[1].append(1.0) elif len(f[1]) == 2: f[1].extend([0.0, 1.0]) elif len(f[1]) > 4: raise ValueError(msg) fdict = dict(files) self.update(fdict...
def writeShiftFile(self, filename="shifts.txt"): """ Writes a shift file object to a file on disk using the convention for shift file format. """ lines = ['# frame: ', self['frame'], '\n', '# refimage: ', self['refimage'], '\n', '# form: ', self['form'], '\n', '# units: ', self['units'], '\n'] for o in self['order']: s...
str(o) + ss + "\n" lines.append(line) fshifts= open(filename, 'w') fshifts.writelines(lines) fshifts.close()
def weave(target, aspects, **options): """ Send a message to a recipient Args: target (string, class, instance, function or builtin): The object to weave. aspects (:py:obj:`aspectlib.Aspect`, function decorator or list of): The aspects to apply to the object. subclasses (bool): If ``True``, subclasses of target are wea...
target's ``__init__`` method is patched, the rest of the methods are patched after ``__init__`` is called. *Only available for classes*. methods (list or regex or string): Methods from target to patch. *Only available for classes* Returns: aspectlib.Rollback: An object that can rollback the patches. Raises: TypeError: ...
.. versionchanged:: 0.4.0 Replaced `only_methods`, `skip_methods`, `skip_magicmethods` options with `methods`. Renamed `on_init` option to `lazy`. Added `aliases` option. Replaced `skip_subclasses` option with `subclasses`. """ if not callable(aspects): if not hasattr(aspects, '__iter__'): raise ExpectedAdvice('%s must...
obj) assert target, "Can't weave falsy value %r." % target logdebug("weave (target=%s, aspects=%s, **options=%s)", target, aspects, options) bag = options.setdefault('bag', ObjectBag()) if isinstance(target, (list, tuple)): return Rollback([ weave(item, aspects, **options) for item in target ]) elif isinstance(target, ...
try: owner = _import_module(owner) except ImportError: continue else: break else: raise ImportError("Could not import %r. Last try was for %s" % (target, owner)) if '.' in name: path, name = name.rsplit('.', 1) path = deque(path.split('.')) while path: owner = getattr(owner, path.popleft()) logdebug("@ patching %s from...
return weave_class( obj, aspects, owner=owner, name=name, **options ) elif callable(obj): # or isinstance(obj, FunctionType) ?? logdebug(" .. as a callable %r.", obj) if bag.has(obj): return Nothing return patch_module_function(owner, obj, aspects, force_name=name, **options) else: return weave(obj, aspects, **options)...
bag.has(target): return Nothing inst = target.__self__ name = target.__name__ logdebug("@ patching %r (%s) as instance method.", target, name) func = target.__func__ setattr(inst, name, _checked_apply(aspects, func).__get__(inst, type(inst))) return Rollback(lambda: delattr(inst, name)) elif PY3 and isfunction(target):...
owner.__dict__[name] return patch_module(owner, name, _checked_apply(aspects, func), func, **options) elif PY2 and isfunction(target): if bag.has(target): return Nothing return patch_module_function(_import_module(target.__module__), target, aspects, **options) elif PY2 and ismethod(target): if target.im_self: if bag.h...
target.__name__ return weave(klass, aspects, methods='%s$' % name, **options) elif isclass(target): return weave_class(target, aspects, **options) elif ismodule(target): return weave_module(target, aspects, **options) elif type(target).__module__ not in ('builtins', '__builtin__') or InstanceType and isinstance(target,...
def weave_instance(instance, aspect, methods=NORMAL_METHODS, lazy=False, bag=BrokenBag, **options): """ Low-level weaver for instances. .. warning:: You should not use this directly. :returns: An :obj:`aspectlib.Rollback` object. """ if bag.has(instance): return Nothing entanglement = Rollback() method_matches = make_m...
attr in dir(instance): func = getattr(instance, attr) if method_matches(attr): if ismethod(func): if hasattr(func, '__func__'): realfunc = func.__func__ else: realfunc = func.im_func entanglement.merge( patch_module(instance, attr, _checked_apply(fixed_aspect, realfunc, module=None), **options) ) return entanglement
def weave_module(module, aspect, methods=NORMAL_METHODS, lazy=False, bag=BrokenBag, **options): """ Low-level weaver for "whole module weaving". .. warning:: You should not use this directly. :returns: An :obj:`aspectlib.Rollback` object. """ if bag.has(module): return Nothing entanglement = Rollback() method_matches =...
**options)) elif isclass(func): entanglement.merge( weave_class(func, aspect, owner=module, name=attr, methods=methods, lazy=lazy, bag=bag, **options), # it's not consistent with the other ways of weaving a class (it's never weaved as a routine). # therefore it's disabled until it's considered useful. # #patch_module_f...
def weave_class(klass, aspect, methods=NORMAL_METHODS, subclasses=True, lazy=False, owner=None, name=None, aliases=True, bases=True, bag=BrokenBag): """ Low-level weaver for classes. .. warning:: You should not use this directly. """ assert isclass(klass), "Can't weave %r. Must be a class." % klass if bag.has(klass): r...
subclasses and hasattr(klass, '__subclasses__'): sub_targets = klass.__subclasses__() if sub_targets: logdebug("~ weaving subclasses: %s", sub_targets) for sub_class in sub_targets: if not issubclass(sub_class, Fabric): entanglement.merge(weave_class(sub_class, aspect, methods=methods, subclasses=subclasses, lazy=lazy,...
_checked_apply(aspect, __init__) if method_matches('__init__') else __init__ } for attr, func in klass.__dict__.items(): if method_matches(attr): if ismethoddescriptor(func): wrappers[attr] = _rewrap_method(func, klass, aspect) logdebug(" * creating subclass with attributes %r", wrappers) name = name or klass.__name__ ...
if isroutine(func): logdebug("@ patching attribute %r (original: %r).", attr, func) setattr(klass, attr, _rewrap_method(func, klass, aspect)) else: continue original[attr] = func entanglement.merge(lambda: deque(( setattr(klass, attr, func) for attr, func in original.items() ), maxlen=0)) if bases: super_original = set...
isroutine(func): logdebug("@ patching attribute %r (from superclass: %s, original: %r).", attr, sklass.__name__, func) setattr(klass, attr, _rewrap_method(func, sklass, aspect)) else: continue super_original.add(attr) entanglement.merge(lambda: deque(( delattr(klass, attr) for attr in super_original ), maxlen=0)) retur...
def patch_module(module, name, replacement, original=UNSPECIFIED, aliases=True, location=None, **_bogus_options): """ Low-level attribute patcher. :param module module: Object to patch. :param str name: Attribute to patch :param replacement: The replacement value. :param original: The original value (in case the object...
object. """ rollback = Rollback() seen = False original = getattr(module, name) if original is UNSPECIFIED else original location = module.__name__ if hasattr(module, '__name__') else type(module).__module__ target = module.__name__ if hasattr(module, '__name__') else type(module).__name__ try: replacement.__module__ =...
original) if obj is original: if aliases or alias == name: logdebug("= saving %s on %s.%s ...", replacement, target, alias) setattr(module, alias, replacement) rollback.merge(lambda alias=alias: setattr(module, alias, original)) if alias == name: seen = True elif alias == name: if ismethod(obj): logdebug("= saving %s o...
= %s is not %s." % (module, alias, obj, original)) if not seen: warnings.warn('Setting %s.%s to %s. There was no previous definition, probably patching the wrong module.' % ( target, name, replacement )) logdebug("= saving %s on %s.%s ...", replacement, target, name) setattr(module, name, replacement) rollback.merge(la...
def patch_module_function(module, target, aspect, force_name=None, bag=BrokenBag, **options): """ Low-level patcher for one function from a specified module. .. warning:: You should not use this directly. :returns: An :obj:`aspectlib.Rollback` object. """ logdebug("patch_module_function (module=%s, target=%s, aspect=%s...
def unframe(packet): """ Strip leading DLE and trailing DLE/ETX from packet. :param packet: TSIP packet with leading DLE and trailing DLE/ETX. :type packet: Binary string. :return: TSIP packet with leading DLE and trailing DLE/ETX removed. :raise: ``ValueError`` if `packet` does not start with DLE and end in DLE/ETX. "...
def stuff(packet): """ Add byte stuffing to TSIP packet. :param packet: TSIP packet with byte stuffing. The packet must already have been stripped or `ValueError` will be raised. :type packet: Binary string. :return: Packet with byte stuffing. """ if is_framed(packet): raise ValueError('packet contains leading DLE and ...