introspection

Find module name of the originating exception in Python

可紊 提交于 2019-11-29 18:44:55
问题 Example: >>> try: ... myapp.foo.doSomething() ... except Exception, e: ... print 'Thrown from:', modname(e) Thrown from: myapp.util.url In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the __name__ of that module? My intention is to use this in logging.getLogger function. 回答1: This should work: import inspect try: some_bad_code() except Exception, e: frm = inspect.trace()[-1] mod = inspect.getmodule(frm[0]) print 'Thrown from', mod._

Ruby String#to_class

夙愿已清 提交于 2019-11-29 15:43:47
Taken from a previous post with some modifications to respond to sepp2k 's comment about namespaces, I have implemented String#to_class method. I'm sharing the code here and I do believe that it could be refactored someway specially the "i" counter. Your comments are appreciated. class String def to_class chain = self.split "::" i=0 res = chain.inject(Module) do |ans,obj| break if ans.nil? i+=1 klass = ans.const_get(obj) # Make sure the current obj is a valid class # Or it's a module but not the last element, # as the last element should be a class klass.is_a?(Class) || (klass.is_a?(Module)

Obj-C introspection: How can a method reference its own selector?

半城伤御伤魂 提交于 2019-11-29 15:22:48
I wish to write a macro, to be used within any method, which references the method's selector. I do not wish to pass the literal name of the method. For example: #define RERUN [self performSelector:{something} withObject:nil afterDelay: 0.0] where the "{something}" in the above would resolve to the selector of whatever method the macro was used in. Is there some way to do this? _cmd represents the selector of the current method -- it is a hidden argument (like self ). if you never need arguments, or nil is suitable for your purpose - all you need to do is write: #define RERUN [self

Get PHP class namespace dynamically

十年热恋 提交于 2019-11-29 13:22:29
How can I retrieve a class namespace automatically? The magic var __NAMESPACE__ is unreliable since in subclasses it's not correctly defined. Example: class Foo\bar\A -> __NAMESPACE__ === Foo\bar class Ping\pong\B extends Foo\bar\A -> __NAMESPACE__ === Foo\bar (it should be Ping\pong) ps: I noticed the same wrong behavior using __CLASS__ , but I solved using get_called_class() ... is there something like get_called_class_namespace() ? How can I implement such function? UPDATE: I think the solution is in my own question, since I realized get_called_class() returns the fully qualified class name

Get source code of user-defined class and functions?

风流意气都作罢 提交于 2019-11-29 11:01:43
Is there a method for getting the source code of a class or method? I'm looking at the ReflectionClass , but I don't see one. Best I could come up with: $class = new ReflectionClass($c); $fileName = $class->getFileName(); $startLine = $class->getStartLine()-1; // getStartLine() seems to start after the {, we want to include the signature $endLine = $class->getEndLine(); $numLines = $endLine - $startLine; if(!empty($fileName)) { $fileContents = file_get_contents($fileName); $classSource = trim(implode('',array_slice(file($fileName),$startLine,$numLines))); // not perfect; if the class starts or

How to access properties of Python super classes e.g. via __class__.__dict__?

谁都会走 提交于 2019-11-29 10:23:36
How can I get all property names of a python class including those properties inherited from super classes ? class A(object): def getX(self): return "X" x = property(getX) a = A() a.x 'X' class B(A): y = 10 b = B() b.x 'X' a.__class__.__dict__.items() [('__module__', '__main__'), ('getX', <function getX at 0xf05500>), ('__dict__', <attribute '__dict__' of 'A' objects>), ('x', <property object at 0x114bba8>), ('__weakref__', <attribute '__weakref__' of 'A' objects>), ('__doc__', None)] b.__class__.__dict__.items() [('y', 10), ('__module__', '__main__'), ('__doc__', None)] How can I access

Get the name (string) of a generic type in Swift

天大地大妈咪最大 提交于 2019-11-29 05:29:53
I have a generic class of type T and I would like to get the name of the type that passed into the class when instantiated. Here is an example. class MyClass<T> { func genericName() -> String { // Return the name of T. } } I have been looking around for hours and I can't seem to find any way to do this. Has anyone tried this yet? Any help is greatly appreciated. Thanks Antonio A pure swift way to achieve that is not possible. A possible workaround is: class MyClass<T: AnyObject> { func genericName() -> String { let fullName: String = NSStringFromClass(T.self) let range = fullName.rangeOfString

Accessing a method in a super class when it's not exposed

时间秒杀一切 提交于 2019-11-29 03:11:43
In a subclass, I'm overriding a method that is not exposed in the super class. I know that I have the correct signature as it is successfully overriding the superclass implementation. However, as part of the the new implementation, I need to call the superclass's implementation from the subclass's implementation. Because it's not exposed I have to invoke the method via a call to performSelector : SEL superClassSelector = NSSelectorFromString(@"methodToInvoke"); [super performSelector:superClassSelector]; However, in my application this results in an infinite recursive loop where the subclass's

How to introspect a function defined in a Cython C extension module

坚强是说给别人听的谎言 提交于 2019-11-29 02:32:42
Python's inspect module doesn't seem to be able to inspect the signatures of "built-in" functions, which include functions defined in C extension modules, like those defined by Cython. Is there any way to get the signature of a Python function you have defined in such a module, and specifically in Cython? I am looking to be able to find the available keyword arguments. MWE: # mwe.pyx def example(a, b=None): pass and import pyximport; pyximport.install() import mwe import inspect inspect.signature(mwe.example) yields: Traceback (most recent call last): File "mwe_py.py", line 5, in <module>

Calling a selector with unknown number of arguments using reflection / introspection

北城余情 提交于 2019-11-29 02:30:55
Lately I wrote an application in java (for android) which used reflection to invoke methods of some objects. The argument number and type was unknown, meaning, I had a unified mechanism that received an object name, method name and array of parameters (using JSON) and invoked the specified method on the specified object with an array of the arguments (Object[] filled with arguments of the required types). Now I need to implement the same for iOS, I was able to invoke a selector when I knew the number of parameters the selector expected for like this: SEL selector = NSSelectorFromString(@