mypyc: Implementing a proxy object - python

Is there a way to implement a proxy object with mypyc?
For example, consider the following code which works fine with Python but not mypyc:
import typing
class Thing:
def __getattr__(self, name: str) -> typing.Any:
return 5
t = Thing()
print(t.lol)
Python output:
5
mypyc compiled output:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "blah.py", line 9, in <module>
print(t.lol)
AttributeError: 'Thing' object has no attribute 'lol'

Related

Python Package addict force error if not existing

The package addict allows you to use dicts through attribute setting:
Example from the website:
from addict import Dict
body = Dict()
body.query.filtered.query.match.description = 'addictive'
body.query.filtered.filter.term.created_by = 'Mats'
Now when when I use for example a = body.B and I haven't included B yet it does not throw an error, but just returns nothing. How can I make it throw an error when the attribute was net yet set?
addict.Dict implements the __missing__ method to generate a value for any missing key(/attribute); the current implementation generates a new Dict instance. If you don't want this behaviour, you'll have to override it:
class MyDict(Dict):
def __missing__(self, name):
raise KeyError(name)
Note that this will throw a KeyError for attribute access, which may be confusing; you could also override __getattr__ if you want to throw an AttributeError instead. In use:
>>> body = MyDict()
>>> body.B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "path/to/addict.py", line 62, in __getattr__
return self.__getitem__(item)
File "<stdin>", line 3, in __missing__
KeyError: 'B'
>>> body.B = "hello"
>>> body.B
'hello'
Note also that this will break the other examples you showed as well, as e.g. foo.bar.baz = qux calls __getattr__ on foo before calling __setattr__ on foo.bar (if successful):
>>> body.query.filtered.query.match.description = 'addictive'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "path/to/addict.py", line 62, in __getattr__
return self.__getitem__(item)
File "<stdin>", line 3, in __missing__
KeyError: 'query'

Callable function not really callable?

I am using ParaView-5.4.1 under Ubuntu 16.04LTS.
I have an object r of class PVDReader (in pvpython, but this is likely irrelevant).
For the method TimestepValues of that class
>>> callable(r.TimestepValues)
True
>>> type(r.TimestepValues)
<class 'paraview.servermanager.VectorProperty'>
>>> r.TimestepValues
[0.0, 0.002]
>>> r.TimestepValues()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/res/apps/ParaView-5.4.1-Qt5-OpenGL2-MPI-Linux-64bit/lib/python2.7/site-packages/paraview/servermanager.py", line 681, in __call__
raise RuntimeError ("Cannot invoke this property")
RuntimeError: Cannot invoke this property
>>> import inspect
>>> inspect.getargspec(r.TimestepValues)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/santiago/apps/ParaView-5.4.1-Qt5-OpenGL2-MPI-Linux-64bit/lib/python2.7/inspect.py", line 816, in getargspec
raise TypeError('{!r} is not a Python function'.format(func))
TypeError: [0.0, 0.002] is not a Python function
So, on one hand, it is callable.
On the other hand, it behaves as if it were not.
How can this be understood?
Is this a bug?
tl;dr PS: Other more generic methods behave similarly (but not the same). E.g., compare with __class__:
>>> callable(r.__class__)
True
>>> type(fluid_pr_reader.__class__)
<type 'type'> <-- Rather obvious, just for completitude of the comparison with above
>>> r.__class__
<class 'paraview.servermanager.PVDReader'>
>>> r.__class__()
<paraview.servermanager.PVDReader object at 0x7f57ed56fd10> <-- No error here
>>> inspect.getargspec(r.__class__)
Traceback (most recent call last): <-- Same error here
File "<stdin>", line 1, in <module>
File "/home/res/apps/ParaView-5.4.1-Qt5-OpenGL2-MPI-Linux-64bit/lib/python2.7/inspect.py", line 816, in getargspec
raise TypeError('{!r} is not a Python function'.format(func))
TypeError: <class 'paraview.servermanager.PVDReader'> is not a Python function
EDIT: The result is the same if I do not access it as a straight property prior to accessing it as a callable
>>> callable(r.TimestepValues)
True
>>> r.TimestepValues()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/res/apps/ParaView-5.4.1-Qt5-OpenGL2-MPI-Linux-64bit/lib/python2.7/site-packages/paraview/servermanager.py", line 681, in __call__
raise RuntimeError ("Cannot invoke this property")
RuntimeError: Cannot invoke this property

AttributeError: 'module' object has no attribute 'TestSequenceFunctions'

I'm working on unittest in python.
I'm working on a Ububtu machine from "/home/jamy/PycharmProjects/xcxzc/UnitTesting.py" directory and trying to run this following code:
import unittest
class LearningCase(unittest.TestCase):
def test_starting_out(self):
self.assertEqual(1, 1)
def main():
unittest.main()
if __name__ == "__main__":
main()
But I am getting this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "unitTesting.py", line 1, in <module>
import unittest
File "/home/jamy/PycharmProjects/xcxzc/unittest.py", line 4, in <module>
AttributeError: 'module' object has no attribute 'TestSequenceFunctions'
How can I fix this?
By naming your script unittest.py you are shadowing the built-in unittest module.

Pydoc not working in Python 3.3 in Windows

I am trying to generate the help text at runtime and i am not able to use the pydoc command in Windows. When i type
>>> pydoc(atexit)
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'pydoc' is not defined
I have already set up the environment variables for pydoc.py file. C:\Python33\Lib\pydoc.py.
This also not works like it works for >>help('atexit')
>>> pydoc('atexit')
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'pydoc' is not defined
Whats the possible reason for it.
Updates:
>>> import pydoc
>>> pydoc(sys)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'module' object is not callable
>>> pydoc('sys')
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'module' object is not callable
Like any library in Python, you need to import it before you can use it.
Edit What exactly are you trying to achieve? Modules are indeed not callable. pydoc.help is the function you want, although I don't really know why you need it, since as you note the standalone help function does the same thing already.

"argument 1 has unexpected type 'str'"

I'm trying to use PyKDE, PyKDE.kdecore.KStandardDirs to be precise. This method is called with two strings according to the documentation and according to the PyQt4 documentation, I can use standard Python strs instead of QString.
This doesn't work:
>> KStandardDirs.locate()("socket", "foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: KStandardDirs.locate(): not enough arguments
>>> KStandardDirs.locate("socket", "foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: KStandardDirs.locate(): argument 1 has unexpected type 'str'
I can't use QString either because it doesn't seem to exist:
>>> from PyQt4.QtCore import QString
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name QString
>>> from PyQt4.QtCore import *
>>> QString
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'QString' is not defined
What am I doing wrong?
I suspect that PyKDE is not yet Python 3 ready, at least as far as that error message is concerned; try passing in a bytestring instead:
KStandardDirs.locate(b"socket", "foo")

Categories