Пример #1
0
def type2strepr(inst, strepr=str, **kwds):
    '''Represent a Python Type instance as L{str} or L{repr}.

       @param inst: Instance (C{any}).
       @keyword strepr: Representation function (C{repr} or C{str}).

       @return: Instance representation (C{str}).
    '''
    try:
        t = getattr(inst.NS, 'objc_classname', _NN_)  # PYCHOK expected
    except AttributeError:
        t = _NN_
    try:
        t += '[%s]' % (len(inst),)
    except TypeError:
        pass
    try:
        d = dict(name=repr(inst.name))
        d.update(kwds)
    except AttributeError:
        d = kwds
    d = tuple(_EQUALS_(n, v) for n, v in d.items())
    if t and d:
        t = _COMMASPACE_(strepr(t), *d)
    elif d:
        t = _COMMASPACE_.join(d)
    else:
        t = strepr(t)
    return '%s(%s)' % (inst.__class__.__name__, t)
Пример #2
0
def get_properties(clas_or_proto, *prefixes):
    '''Yield all properties of an ObjC class or protocol
       with a name starting with one of the given prefixes.

       @param clas_or_proto: The class or protocol (L{Class_t} or L{Protocol_t}).
       @param prefixes: No, one or more property names to match (C{str}-s).

       @return: For each property, yield a 3-tuple (I{name}, I{attributes},
                I{setter}, I{property}) where I{attributes} is a comma-separated
                list of the property attibutes, I{setter} is the name of the
                property setter method, provided the property is writable and
                I{property} is the C{Property} object.  For read-only properties,
                the I{setter} is an empty name "".

       @note: ObjC Property Attributes:

           - T<type>"name" = Type
           - & = Retain last value (retain)
           - C = Copy
           - D = Dynamic (@dynamic)
           - G<name> = Getter selector name
           - N = Non-atomic (nonatomic)
           - P = To be garbage collected
           - R = Read-only (readonly)
           - S<name> = Setter selector name
           - t<encoding> = Old-style type encoding
           - W = Weak reference (__weak)

       @see: U{Property Attributes<https://Developer.Apple.com/library/content/documentation/
             Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html>}.
    '''
    n = c_uint()
    if isinstance(clas_or_proto, Class_t):
        props = libobjc.class_copyPropertyList(clas_or_proto, byref(n))
        setters = set(_[0] for _ in get_methods(clas_or_proto, 'set'))
    elif isinstance(clas_or_proto, Protocol_t):
        props = libobjc.protocol_copyPropertyList(clas_or_proto, byref(n))
        setters = []
    else:
        raise TypeError('%s not a %s nor %s: %r' %
                        ('clas_or_proto', Class_t.__name__,
                         Protocol_t.__name__, clas_or_proto))

    for prop in props:
        name = bytes2str(libobjc.property_getName(prop))
        if name and name.startswith(prefixes or name):
            # XXX should yield name, ObjCProperty instance
            # attrs T@"type",&,C,D,G<name>,N,P,R,S<name>,W,t<encoding>,V<varname>
            attrs = bytes2str(libobjc.property_getAttributes(prop))
            attrs = '%s=(%s)' % (attrs,
                                 _COMMASPACE_.join(
                                     _PropertyAttributes.get(_[:1], _[:1]) +
                                     _[1:] for _ in attrs.split(',')))
            setter = _NN_
            if setters:
                set_ = _NN_('set', name.capitalize(), _COLON_)
                if set_ in setters:
                    setter = _NN_(_PropertyAttributes['S'], set_)
            yield name, attrs, setter, prop
Пример #3
0
def inst2strepr(inst, strepr, *attrs):
    '''Convert an instance's attributes, maintaining the order.

       @param inst: Instance (C{any}).
       @param strepr: Conversion (C{repr} or C{str}).
       @param attrs: Instance attribute names (I{all positional}).

       @return: Instance representation (C{str}).
    '''
    def _strepr(v):
        return repr(v) if isinstance(v, _ByteStrs) else strepr(v)

    t = ('%s=%s' % (a, _strepr(getattr(inst, a))) for a in attrs)
    return '%s(%s)' % (inst.__class__.__name__, _COMMASPACE_.join(t))
Пример #4
0
def _all_versionstr(libs=False, _file_=_NN_, _version_=_NN_):
    '''(INTERNAL) PyCocao, Python, macOS, etc. versions as C{str}.
    '''
    from pycocoa import oslibs, _pycocoa, version as _version

    t = (('version', _version_ or _version),  # PYCHOK shadow
         ('.isLazy',  str(isLazy)),
         ('Python',  _Python_, _platform.architecture()[0], machine()),
         ('macOS',   _macOSver()))
    if libs:
        t += ('oslibs', str(sorted(oslibs.get_libs().keys())).replace("'", _NN_)),

    m, _ = _dirbasename2(_file_ or _pycocoa)
    return _DOT_(m, _COMMASPACE_.join(_SPACE_.join(v) for v in t))
Пример #5
0
def _TypeError(name, inst, func, classes=()):
    '''(INTERNAL) Format a TypeError for func(inst, *classes).
    '''
    if classes:
        c = [getattr(c, '__name__', str(c)) for c in classes]
        c = _COMMASPACE_.join([_NN_] + c)
    else:
        c = _NN_

    if name:
        t = 'not %s(%s%s): %r' % (func.__name__, name, c, inst)
    else:
        t = 'invalid %s(%r, %s)' % (func.__name__, inst, c)
    return TypeError(t)
Пример #6
0
 def _all_in(alls, inns, m, n):
     t = tuple(a for a in alls if a not in inns)
     if t:
         t = _COMMASPACE_.join(t)
         raise NameError('missing %s: %s' % (_DOT_(m, n), t))
Пример #7
0
 def __str__(self):
     '''Return this C{Adict} as C{str}.
     '''
     return '{%s}' % (_COMMASPACE_.join('%s=%r' % t
                      for t in sorted(self.items())),)