Using Cairo Regions in python with gi.repository - python-3.x

I can't seem to get cairo regions working in within
using the gintrospection.
For example
from gi.repository import cairo
reg = cairo.Region()
will give me
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError
and trying to get a region from Gdk.get_clip_region() will give me
return info.invoke(*args)
TypeError: Couldn't find conversion for foreign struct 'cairo.Region'
What obvious thing am I missing? I can't find a way to iniatilize the library, and can't imagine you would need to for regions which seem like a simple struct. I don't know why gdk can't find the cairo types, and am not aware if I"m supposed to show it the way somehow.

Apparently you need to use the regular cairo bindings, even when you use introspection for everything else.
So just import cairo.
(I'm not sure why gi.repository.cairo exists...)
And the "Couldn't find conversion" error will go away when you have all the necessary libraries (e.g. on Ubuntu you need the python-gi-cairo package in addition to python-cairo (or the equivalent python3 packages)).

Related

ValueError: Comments are not supported by the python backend

The ijson module has a documented option allow_comments=True, but when I include it,
an error message is produced:
ValueError: Comments are not supported by the python backend
Below is a transcript using the file test.py:
import ijson
for o in ijson.items(open(0), 'item'):
print(o)
Please note that I have no problem with a similar documented option, multiple_values=True.
Transcript
$ python3 --version
Python 3.10.9
$ python3 test.py <<< [1,2]
1
2
# Now change the call to: ijson.items(open(0), 'item', allow_comments=True)
$ python3 test.py <<< [1,2]
Traceback (most recent call last):
File "/Users/user/test.py", line 5, in <module>
for o in ijson.items(open(0), 'item', allow_comments=True):
File "/usr/local/lib/python3.10/site-packages/ijson/utils.py", line 51, in coros2gen
f = chain(events, *coro_pipeline)
File "/usr/local/lib/python3.10/site-packages/ijson/utils.py", line 29, in chain
f = coro_func(f, *coro_args, **coro_kwargs)
File "/usr/local/lib/python3.10/site-packages/ijson/backends/python.py", line 284, in basic_parse_basecoro
raise ValueError("Comments are not supported by the python backend")
ValueError: Comments are not supported by the python backend
$
Take a look at the Backends section of the documentation, which says:
Ijson provides several implementations of the actual parsing in the form of backends located in ijson/backends:
yajl2_c: a C extension using YAJL 2.x. This is the fastest, but might require a compiler and the YAJL development files to be present when installing this package. Binary wheel distributions exist for major platforms/architectures to spare users from having to compile the package.
yajl2_cffi: wrapper around YAJL 2.x using CFFI.
yajl2: wrapper around YAJL 2.x using ctypes, for when you can’t use CFFI for some reason.
yajl: deprecated YAJL 1.x + ctypes wrapper, for even older systems.
python: pure Python parser, good to use with PyPy
And later on in the FAQ it says:
Q: Are there any differences between the backends?
...
The python backend doesn’t support allow_comments=True It also internally works with str objects, not bytes, but this is an internal detail that users shouldn’t need to worry about, and might change in the future.
If you want support for allow_comments=True, you need to be using one of the yajl based backends. According to the docs:
Importing the top level library as import ijson uses the first available backend in the same order of the list above, and its name is recorded under ijson.backend. If the IJSON_BACKEND environment variable is set its value takes precedence and is used to select the default backend.
You'll need the necessary libraries, etc, installed on your system in order for this to work.

Does Python define formal behavior for platform functions "Availability"

I'm creating cross-platform Python application, so I need to pay attention to the official disclaimers related to platform availability. For example:
os.getlogin()
...
Availability: Unix, Windows, not Emscripten, not WASI.
Unfortunatly I couldn't figure it out what "Unavailable" is in program behavior for wide spectr of functins (not only getlogin()).
Is there some standard exception to distinguish "Unavailable" case?
Is it enough to always wrap invocation with try...except StandardError to provide failover?
Do I need hide import with try as well or it is enough for function invocation? In other words:
try:
import os
os.getlogin()
...
except StandardError: # platform doesn't support user recognition
...
VS
import os
try:
os.getlogin()
...
except StandardError: # platform doesn't support user recognition
...
You will simply get an AttributeError. For example, on MacOS (set_handle_inheritable is only available on Windows):
>>> os.get_handle_inheritable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'os' has no attribute 'get_handle_inheritable'
So you can either:
Just import os and check the OS before every usage
Try to import the individual methods and catch ImportError
Try to call the functions and catch AttributeError

IAC-protocol interface error on python 3

I would like to work with excell sheets (.xls likely per .ods conversion) via python while maintaining all of the sheet's original content. Unlike xlutils (http://www.python-excel.org/) the iac-protocol (http://pythonhosted.org/iac-protocol/index.html) seems to me to be more fit/elegant tool to maintain sheet's style,formulas,dropboxes etc. One of the steps to launch iac's server or interpreter (iacs/iaci) is to initialize the interface which consists among others of this command:
import iac.app.libreoffice.calc as localc
While import iac.app.libreoffice works fine
moving to calc level
import iac.app.libreoffice.calc
throws following error
import iac.app.libreoffice.calc
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.4/site-packages/iac/app/libreoffice/calc.py", line 11, in
from uno import getComponentContext
ImportError: cannot import name 'getComponentContext'
From what I've learned so far on this forum it might be linked to method name duplicity between two modules. This is where I am stuck. How do I learn which other module has such name of a method and how to fix it? Both iac-protocol and unotools are modules downloaded via pip3. I did not created method of such name in any script.
Thank you in advance for any advice!
Python3.4 on Scientific Linux release 7.3 (Nitrogen) LibreOffice 5.0.6.2 00(Build:2)
Some questions to narrow down the problem:
Did you start libreoffice listening on a socket first?
Did you import anything else before import iac.app.libreoffice.calc?
What happens when you start python in a terminal and enter from uno import getComponentContext?
I installed iac-protocol on Linux Mint and was able to import iac.app.libreoffice.calc and then use it. The installation process was complex, so I wouldn't be surprised if there is some problem with how your packages were installed, or possibly it does not work on RHEL-based systems. For one thing, it required me to install gnumeric.
The Calc "Hello World" code that worked for me is as follows.
libreoffice "--accept=socket,host=localhost,port=18100;urp;StarOffice.ServiceManager" --norestore --nofirststartwizard --nologo --calc &
python3
>>> import iac.app.libreoffice.calc as localc
>>> doc = localc.Interface.current_document()
>>> sheet = doc.getSheets().getByIndex(0)
>>> cell = sheet.getCellByPosition(0,0)
>>> cell.setString("Hello, World!")
One more thought: Have you considered using straight PyUNO starting from import uno instead of a wrapper library? That would avoid dependency on some of the extra libraries which may be causing the problem. Also there is better documentation for straight PyUNO.

pickle a zipfile.ZipFile with python >= 3.6

I came across some code that would not work anymore in python 3.6, but did good in all versions before. I found out the problem is actually a field containing a ZipFile somewhere in a class. Here is a short program which raises the error:
from pickle import dumps
import io
import zipfile
raw = b""
foo = zipfile.ZipFile(io.BytesIO(raw), mode="w")
dumps(foo)
I get this error:
Traceback (most recent call last):
File "bla.py", line 8, in <module>
dumps(foo)
TypeError: can't pickle _thread.RLock objects
So the test program can be even shorter:
from pickle import dumps
import threading
dumps(threading.RLock())
I diffed both the python 3.5 and 3.6 zipfile.py but can not spot any difference in respect to the _lock field in ZipFile, so it seems that there are changes in the threading module - but in threading.py there are also no obvious changes between the versions.
Why is it not pickable anymore? Do I need to do something before I can pickle a ZipFile?
Edit: ok after searching now for a while, I stumbled across this python bug tracker entry: https://bugs.python.org/msg284751
So that a ZipFile is pickable in python <3.6 is actually the bug...
I think I need to change a lot of code now...
Just to give an answer to this question: That ZipFile objects are pickable is actually a bug: https://bugs.python.org/msg284751 which has been fixed in py 3.6.

Import parent directory for brief tests

I have searched this site top to bottom yet have not found a single way to actually accomplish what I want in Python3x. This is a simple toy app so I figured I could write some simple test cases in asserts and call it a day. It does generate reports and such so I would like to make sure my code doesn't do anything wonky upon changes.
My current directory structure is: (only relevant parts included)
project
-model
__init__.py
my_file.py
-test
my_file_test.py
I am having a hell of a time getting my_file_test.py to import my_file.py.
Like I've said. I've searched this site top to bottom and no solution has worked. My version of Python is 3.2.3 running on Fedora 17.
Previously tried attempts:
https://stackoverflow.com/questions/5078590/dynamic-imports-relative-imports-in-python-3
Importing modules from parent folder
Can anyone explain python's relative imports?
How to accomplish relative import in python
In virtually every attempt I get an error to the effect of:
ImportError: No module named *
OR
ValueError: Attempted relative import in non-package
What is going on here. I have tried every accepted answer on SO as well as all over the interwebs. Not doing anything that fancy here but as a .NET/Java/Ruby programmer this is proving to be the absolute definition of intuitiveness.
EDIT: If it matters I tried loading the class that I am trying to import in the REPL and I get the following:
>>> import datafileclass
>>> datafileclass.methods
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
>>> x = datafileclass('sample_data/sample_input.csv')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
If it matters...I know the functionality in the class works but I can't import it which in the now is causing an inability to test. In the future will certainly cause integration issues. (names changed to protect the innocent)
getting within a couple of weeks of desired functionality for this iteration of the library...any help could be useful. Would have done it in Ruby but the client wants the Python as a learning experience,
Structure your code like this:
project
-model
__init__.py
my_file.py
-tests
__init__.py
test_my_file.py
Importantly, your tests directory should also be a module directory (have an empty __init__.py file in it).
Then in test_my_file.py use from model import my_file, and from the top directory run python -m tests.test_my_file. This is invoking test_my_file as a module, which results in Python setting up its import path to include your top level.
Even better, you can use pytest or nose, and running py.test will pick up the tests automatically.
I realise this doesn't answer your question, but it's going to be a lot easier for you to work with Python standard practices rather than against them. That means structuring your project with tests in their own top-level directory.

Resources