本文整理汇总了Python中new.classobj函数的典型用法代码示例。如果您正苦于以下问题:Python classobj函数的具体用法?Python classobj怎么用?Python classobj使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了classobj函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: GenClass_new_class
def GenClass_new_class(attributes, myglobals):
classname = attributes[SELF][NAME]
if attributes[SELF][TYPE] != LIST:
raise AttributeError
if ANONYMOUS in attributes[SELF][FLAGS]:
listtype = GenClassAList
attributes[SELF]['install_func'] = GenClassAList_get_install_funcs
else:
listtype = GenClassList
attributes[SELF]['install_func'] = GenClassList_get_install_funcs
def GenClass_init_func(self, list=None, parent=None):
if hasattr(self.__class__, "_ListClass"):
self.__class__._ListClass.__init__(self, list, parent)
def GenClass_newClass_func(self, classname, list=None, parent=None):
klass = self.__class__._Globals[classname]
if klass:
return klass(list, parent)
else: return None
newclass = new.classobj(classname + '_base', (listtype,),
{'Attributes' : attributes,
'__init__' : GenClass_init_func,
'_ListClass' : listtype,
'_Globals' : myglobals,
'newClass' : GenClass_newClass_func})
_install_funcs(newclass)
implclass = new.classobj(classname, (newclass,),
{})
return (newclass, implclass)
示例2: __init__
def __init__(self, element):
self.__element = element
self.__tags = {}
for child in element.getchildren():
ns, tag = denamespace(child.tag)
if tag in self.__tags:
self.__tags[tag].append(child)
else:
self.__tags[tag] = child
if hasattr(self, tag):
spot = getattr(self, tag)
if type(spot) != list:
spot = [spot]
#spot.append(objectify(child))
if len(child.getchildren()):
spot.append(
new.classobj(tag, (ElementWrapper, ), {})(child))
else:
spot.append(child.text)
setattr(self, tag, spot)
setattr(self, '__islist__', True)
elif len(child.getchildren()):
setattr(self, tag,
new.classobj(tag, (ElementWrapper, ), {})(child))
else:
# marshall the type here!
setattr(self, denamespace(child.tag)[1], child.text)
示例3: loadINIPackage
def loadINIPackage(self, inifile):
"""
Load INI file containing macro definitions
Arguments:
inifile -- filename of INI formatted file
"""
ini = ConfigParser.RawConfigParser()
if not isinstance(inifile, (list,tuple)):
inifile = [inifile]
for f in inifile:
ini.read(f)
macros = {}
for section in ini.sections():
try: baseclass = self[section]
except KeyError:
log.warning('Could not find macro %s' % section)
continue
for name in ini.options(section):
value = ini.get(section,name)
m = re.match(r'^unicode\(\s*(?:(\'|\")(?P<string>.+)(?:\1)|(?P<number>\d+))\s*\)$',value)
if m:
data = m.groupdict()
if data['number'] is not None:
value = unichr(int(data['number']))
else:
value = unicode(data['string'])
macros[name] = new.classobj(name, (baseclass,),
{'unicode': value})
continue
macros[name] = new.classobj(name, (baseclass,),
{'args': value})
self.importMacros(macros)
示例4: _preferences_pages_default
def _preferences_pages_default(self):
from apptools.help.help_plugin.preferences_pages import \
DocumentsPreferencesPage, DemosPreferencesPage, \
ExamplesPreferencesPage, HelpDocPreferencesPage, \
HelpDemoPreferencesPage, HelpExamplePreferencesPage
pages = []
if len(self.help_docs) > 0:
pages.append(DocumentsPreferencesPage)
pages.extend(
[ new.classobj(doc.preferences_path + 'PreferencesPage',
(HelpDocPreferencesPage,),
{'preferences_path': doc.preferences_path},
) for doc in self.help_docs
])
if len(self.help_demos) > 0:
pages.append(DemosPreferencesPage)
pages.extend(
[ new.classobj(demo.preferences_path + 'PreferencesPage',
(HelpDemoPreferencesPage,),
{'preferences_path': demo.preferences_path},
) for demo in self.help_demos
])
if len(self.help_examples) > 0:
pages.append(ExamplesPreferencesPage)
pages.extend(
[ new.classobj(example.preferences_path + 'PreferencesPage',
(HelpExamplePreferencesPage,),
{'preferences_path': example.preferences_path},
) for example in self.help_examples
])
return pages
示例5: __init__
def __init__(self, entity=None, base=None, **kw):
""" """
self.get_table_args()
if entity:
self._dao = entity
else:
if len(self.__slots__) == 0:
if base:
self.__decl_base = base
self._dao = \
base._decl_class_registry[self.__class__.__name__]()\
if self.__class__.__name__ in base._decl_class_registry\
else classobj(
self.__class__.__name__,
(self.__clz_proxy__,base,),
self.get_table_args() or {}
)() # instantiate
else:
self._dao = classobj(
self.__class__.__name__,
(self.__clz_proxy__,(object,),),
self.get_table_args() or {}
)() # instantiate
self.__class__.__decl_class__ = self._dao.__class__
for k,v in kw.items():
setattr(self, k, v)
if hasattr(self, 'mixin'):
if 'entity_mixes' in self.__pyaella_args__:
for em in self.__pyaella_args__['entity_mixes']:
self.mixin(em)
示例6: suite
def suite():
suite = unittest.TestSuite()
if has_svn:
tests = [(NormalTests, ''),
(ScopedTests, u'/tête'),
(RecentPathScopedTests, u'/tête/dir1'),
(NonSelfContainedScopedTests, '/tags/v1'),
(AnotherNonSelfContainedScopedTests, '/branches'),
]
skipped = {
'SvnCachedRepositoryNormalTests': [
'test_changeset_repos_creation',
],
'SvnCachedRepositoryScopedTests': [
'test_changeset_repos_creation',
'test_rev_navigation',
],
}
for test, scope in tests:
tc = new.classobj('SubversionRepository' + test.__name__,
(SubversionRepositoryTestCase, test),
{'path': REPOS_PATH + scope})
suite.addTest(unittest.makeSuite(
tc, 'test', suiteClass=SubversionRepositoryTestSetup))
tc = new.classobj('SvnCachedRepository' + test.__name__,
(SvnCachedRepositoryTestCase, test),
{'path': REPOS_PATH + scope})
for skip in skipped.get(tc.__name__, []):
setattr(tc, skip, lambda self: None) # no skip, so we cheat...
suite.addTest(unittest.makeSuite(
tc, 'test', suiteClass=SubversionRepositoryTestSetup))
else:
print "SKIP: versioncontrol/tests/svn_fs.py (no svn bindings)"
return suite
示例7: __init__
def __init__(self):
self.host = "localhost"
self.port = 2663
self.isSessionRunning = False
self.timeline = ""
self.waitStr = None
self.waitFlag = threading.Event()
self.PlayState = -1
self.lastMessage = {}
self.lastSubtitleNum = 0
self.lastSubtitlesEnabled = False
self.lastAudioTrackNum = 0
group = self.AddGroup('Requests')
for className, scancode, descr in ttRequests:
clsAttributes = dict(name=descr, value=scancode)
cls = new.classobj(className, (stdAction,), clsAttributes)
group.AddAction(cls)
group = self.AddGroup('Commands')
for className, scancode, descr, ParamDescr in ttCommands:
clsAttributes = dict(name=descr, value=scancode)
if ParamDescr == "":
if className[0:3] == "IP_":
cls = new.classobj(className, (stdAction,), clsAttributes)
else:
cls = new.classobj(className, (wmAction,), clsAttributes)
else:
cls = new.classobj(className, (stdActionWithStringParameter,), clsAttributes)
cls.parameterDescription = ParamDescr
group.AddAction(cls)
示例8: validate_on_load
def validate_on_load(cls):
for e in cls.errors:
exception = classobj(str(e.error_type), (Exception,), {})
raise exception, e.error_message
for e in cls.other_errors:
exception = classobj(str(e.error_type), (Exception,), {})
raise exception, e.error_message
示例9: invoke
def invoke(self, tex):
self.parse(tex)
attrs = self.attributes
name = attrs['name']
counter = attrs['counter']
caption = attrs['caption']
within = attrs['within']
if not counter and not attrs['*modifier*']:
counter = name
if within:
self.ownerDocument.context.newcounter(counter,initial=0,resetby=within, format='${the%s}.${%s}' % (within, name))
else:
self.ownerDocument.context.newcounter(counter,initial=0)
deflog.debug('newtheorem %s', name)
# The nodeName key below ensure all theorem type will call the same
# rendering method, the type of theorem being retained in the thmName
# attribute
if attrs['*modifier*']:
newclass = new.classobj(str(name), (Environment,),
{'caption': caption, 'nodeName': 'thmenv', 'thmName': name,
'args': '[title]'})
else:
newclass = new.classobj(str(name), (Environment,),
{'caption': caption, 'nodeName': 'thmenv', 'thmName': name,
'counter': counter, 'args': '[title]'})
self.ownerDocument.context.addGlobal(name, newclass)
示例10: setup
def setup(**kwargs):
"""
A drop in replacement for distutils.core.setup which
integrates nicely with kiwi.environ
:param packagename: the name of the main package to be used when it
differs from the 'name' argument
fallback to 'name' if not provided
"""
packagename = kwargs.pop('packagename', None)
# FIXME: This is for kiwi to allow setting datadir to kiwi instead of
# kiwi-gtk when uploading to pip. Is there a better way of doing this?
_VariableExtender.packagename = packagename
def run_install(self):
domain = packagename or kwargs.get('name')
if domain:
datadir = domain if 'bdist_egg' in self.distribution.commands else None
self.data_files.extend(compile_po_files(domain, datadir=datadir))
KiwiInstallData.run(self)
# distutils uses old style classes
InstallData = new.classobj('InstallData', (KiwiInstallData,),
dict(run=run_install))
InstallLib = new.classobj('InstallLib', (KiwiInstallLib,),
dict())
cmdclass = dict(install_data=InstallData, install_lib=InstallLib,
clean=KiwiClean)
kwargs.setdefault('cmdclass', cmdclass).update(cmdclass)
DS_setup(**kwargs)
示例11: newif
def newif(self, name, initial=False):
"""
Create a new \\if (and accompanying) commands
This method corresponds to TeX's \\newif command.
Required Arguments:
name -- name of the 'if' command. This name should always
start with the letters 'if'.
Keyword Arguments:
initial -- initial value of the 'if' command
"""
name = str(name)
# \if already exists
if self.has_key(name):
macrolog.debug('if %s already defined', name)
return
# Generate new 'if' class
macrolog.debug('creating if %s', name)
ifclass = new.classobj(name, (plasTeX.NewIf,), {'state':initial})
self.addGlobal(name, ifclass)
# Create \iftrue macro
truename = name[2:]+'true'
newclass = new.classobj(truename, (plasTeX.IfTrue,), {'ifclass':ifclass})
self.addGlobal(truename, newclass)
# Create \iffalse macro
falsename = name[2:]+'false'
newclass = new.classobj(falsename, (plasTeX.IfFalse,), {'ifclass':ifclass})
self.addGlobal(falsename, newclass)
示例12: setup
def setup(**kwargs):
"""
A drop in replacement for distutils.core.setup which
integrates nicely with kiwi.environ
:attribute resources:
:attribute global_resources:
:attribute templates: List of templates to install
"""
resources = {}
global_resources = {}
templates = []
if 'resources' in kwargs:
resources = kwargs.pop('resources')
if 'global_resources' in kwargs:
global_resources = kwargs.pop('global_resources')
if 'templates' in kwargs:
templates = kwargs.pop('templates')
def run_install(self):
name = kwargs.get('name')
if name:
self.data_files.extend(compile_po_files(name))
KiwiInstallData.run(self)
varext = _VariableExtender(self.distribution)
for path, files in templates:
# Skip templates inside eggs for now
if 'bdist_egg' in self.distribution.commands:
continue
install = self.distribution.get_command_obj('install')
target = os.path.join(install.prefix, path)
if install.root:
if target[0] == '/':
target = target[1:]
target = os.path.join(install.root, target)
if not os.path.exists(target):
info("creating %s" % target)
os.makedirs(target)
for filename in files:
data = open(filename).read()
data = varext.extend(data)
target_file = os.path.join(target, os.path.basename(filename))
info('installing template %s' % target_file)
open(target_file, 'w').write(data)
# distutils uses old style classes
InstallData = new.classobj('InstallData', (KiwiInstallData,),
dict(run=run_install))
InstallLib = new.classobj('InstallLib', (KiwiInstallLib,),
dict(resources=resources,
global_resources=global_resources))
cmdclass = dict(install_data=InstallData, install_lib=InstallLib,
clean=KiwiClean)
kwargs.setdefault('cmdclass', cmdclass).update(cmdclass)
DS_setup(**kwargs)
示例13: newenvironment
def newenvironment(self, name, nargs=0, definition=None, opt=None):
"""
Create a \\newenvironment
Required Arguments:
name -- name of the macro to create
nargs -- integer number of arguments that the macro has
definition -- two-element tuple containing the LaTeX definition.
Each element should be a string. The first element
corresponds to the beginning of the environment, and the
second element is the end of the environment.
opt -- string containing the LaTeX code to use in the
optional argument
Examples::
c.newenvironment('mylist', 0, (r'\\begin{itemize}', r'\\end{itemize}'))
"""
name = str(name)
# Macro already exists
if self.has_key(name):
if not issubclass(self[name], (plasTeX.NewCommand,
plasTeX.Definition)):
return
macrolog.debug('redefining environment "%s"', name)
if nargs is None:
nargs = 0
assert isinstance(nargs, int), 'nargs must be an integer'
if definition is not None:
assert isinstance(definition, (tuple,list)), \
'definition must be a list or tuple'
assert len(definition) == 2, 'definition must have 2 elements'
if isinstance(definition[0], basestring):
definition[0] = [x for x in Tokenizer(definition[0], self)]
if isinstance(definition[1], basestring):
definition[1] = [x for x in Tokenizer(definition[1], self)]
if isinstance(opt, basestring):
opt = [x for x in Tokenizer(opt, self)]
macrolog.debug('creating newenvironment %s', name)
# Begin portion
newclass = new.classobj(name, (plasTeX.NewCommand,),
{'nargs':nargs,'opt':opt,'definition':definition[0]})
self.addGlobal(name, newclass)
# End portion
newclass = new.classobj('end'+name, (plasTeX.NewCommand,),
{'nargs':0,'opt':None,'definition':definition[1]})
self.addGlobal('end' + name, newclass)
示例14: get_class
def get_class(self, name, inuse=False):
"""
return a ClassSerializer named name, if the class hasn't previously
been request create a new class, otherwise return the cached class.
"""
try:
klass = self.ctypes["{%s}%s" % (self.tns, name)]
except:
typeklass = new.classobj("types", (), {})
klass = new.classobj(name, (ClassSerializer, object), {"types": typeklass, "__name__": name})
self.ctypes["{%s}%s" % (self.tns, name)] = klass
if not getattr(klass, "inuse", False):
klass.inuse = inuse
return klass
示例15: get_app
def get_app(config, config_vars, profiler=None, ctx_mixins=None, **kwargs):
app_bases = [HandleExceptionMixin]
if ctx_mixins:
ctx_bases = list(ctx_mixins)
else:
ctx_bases = []
if profiler:
app_bases.append(ProfilerMixin)
if config.session_server:
try:
sess_serv_host, sess_serv_port = config.session_server.split(':')
except ValueError:
sess_serv_host, sess_serv_port = config.session_server, 34343
else:
try:
sess_serv_port = int(sess_serv_port)
except ValueError:
sys.exit('bad session server port specification: %s' %
sess_serv_port)
kwargs['session_appid'] = config.appname
kwargs['session_server'] = sess_serv_host
kwargs['server_port'] = sess_serv_port
if config.session_timeout:
kwargs['session_age'] = int(config.session_timeout)
else:
kwargs['session_age'] = 600
app_bases.append(ModularSessionApp)
if have_branching_session:
ctx_bases.append(BranchingSessionContext)
else:
ctx_bases.append(SessionAppContext)
else:
app_bases.append(ModularApp)
ctx_bases.append(SimpleAppContext)
ctx_bases.append(CommonAppContext)
kwargs['secret'] = config.session_secret
# This is a *little* gross... create a class on the fly
ctx_cls = new.classobj('AlbaCtx', tuple(ctx_bases),
dict(__init__=call_all('__init__')))
def create_context(self):
return ctx_cls(self)
app_cls = new.classobj('AlbaApp', tuple(app_bases),
dict(create_context=create_context))
app = app_cls(**kwargs)
if profiler:
app.profiler = profiler
app.config = config
app.config_vars = config_vars
return app