Why does PySide still require QString for textChanged SIGNAL? - python

My previous understanding was that PySide does not require QString. Yet I found that PySide (I am using v1.2.1 with Python v2.7.5) appears to be inconsistent about this depending on how I wire up my Signals and Slots:
# This Way of wiring up signals and slots requires str
le = QLineEdit()
slotOnChanged = self.onChanged
le.textChanged[str].connect(slotOnChanged)
# But this Way requires QString
le = QLineEdit()
signalTextChanged = SIGNAL("textChanged(QString)")
slotOnChanged = self.onChanged
le.connect(signalTextChanged, slotOnChanged)

You are correct that PySide does not require the QString class, but are mistaken that there is any inconsistency.
PySide/PyQt are generally quite thin wrappers around Qt's C++ library. However, the signal and slot syntax is one of the few areas where there is a significant deviation from this. The syntax used by Qt (the second method in your examples), requires detailed knowledge of C++ signature arguments, and is easy to get wrong. Also, from a python perspective, the syntax is needlessly verbose, and rather "unpythonic". Because of this, PySide/PyQt have added some syntactic "sugar" which provides an alternative, more pythonic, syntax for signals and slots. This is used by the first method in your examples.
The specific reason why QString has to be used in the second method, is that Qt signals are defined statically as part of a C++ class. So the argument to SIGNAL has to quite precisely match the C++ definition in order for the connection to be successful. But note that the argument to SIGNAL doesn't require the QString class to be available - it just requires the use of the string "QString" in the signature.
The "old", C++ way of connecting signals will probably remain available for quite some time (for backward compatibillity if nothing else). But it's generally better to use the "new", pythonic way whenever possible. It's just much clearer, and more readable.

In short: efficiency.
A QString is made up of QChar(s). These provide cross platform compatibility between the C++ and Python bindings (as well as for easier language translation); a string in Python versus a string in C++ are usually different. Qt provides their own.
textChanged(QString) uses QString because ...
1) it can provide a more agnostic type between the language bindings,
2) it avoids the type conversion that happens in the first example and is more efficient.
Here is the detailed description of QString. Note the link on implicit sharing.
Here are examples of other possibilities that are more idiomatic for PySide.

Related

How to apply Closed-Open and Inversion of Control principles in Python?

Building out a new application now and struggling a lot with the implementation part of "Closed-Open" and "Inversion of Control" principles I following after reading Clean Architecture book by Uncle Bob.
How can I implement them in Python?
Usually, these two principles coming hand in hand and depicted in the UML as an Interface reversing control from module/package A to B.
I'm confused because:
Python does not possess Interfaces as Java and C++ do. Yes, there are ABC and #abstractmethod, but it is not a Pythonic style and redundant from my point of view if you are not developing a framework
Passing a class to the method of another one (I understood that it is a way to implement open-closed principle) is a little bit dangerous in Python, since it does not have a compiler which is catching issues may (and will) happen if one of two loosely coupled objects change
After neglecting interfaces and passing a top-level class to lower-level ones... I still need to import everything somewhere at the top module. And by that, the whole thing is violated.
So, as you can see I'm super confused and having a hard time programming according to my design. I came up with. Can you help me, please?
You just pass an object that implements the methods you need it to implement.
True, there is no "Interface" to define what those methods have to be, but that's just the way it is in python.
You pass around arguments all the time that have to be lists, maps, tuples, or whatever, and none of these are type-checked. You can write code that calls whatever you want on these things and python will not notice any kind of problem until that code is actually executed.
It's exactly the same when you need those arguments to implement whatever IoC interface you're using. Make sure you detail the requirements in comments.
Yes, this is all pretty dangerous. That's why we prefer statically typed languages for large systems that have complex interfaces.

How to enforce method interface with Python?

I want to create a class that requires a specific method, with specifically typed arguments and return values.
I can inherit from an abstract class that requires the method to be implemented - but I do not have the ability to force specific argument values and return values ala a static language like Java (I could throw an error at runtime if I wanted to). What is the best way of approaching this with Python? Have looked into type hinting a bit but I don't think it solves this problem.
This seems fundamentally un-pythonic. There's no typing of function parameters in python, so there's no way to restrict the argument types to a function.
Type hinting is useful for documentation or code linters, but python doesn't use that information to enforce anything at runtime.
If you really want to ensure the validity of an interface (even beyond just argument types), the way to do that would be with functional unittests.
Unittesting and Test-Driven Development are so prevalent in the python community that type-hinting doesn't really add much when it comes to testing and finding bugs. And while it's a debatable point, there are many who believe that any benefit from type-hinting is immediately destroyed by making python code harder to read. There are some promising possibilities with type-hinting of being able to compile python out to C or Java, but they don't exist, yet.

Using gpointer with Python and GObject introspection

I am learning about Python and Gtk 3, using GObject introspection. I have done some samples, and I am begining to understant how it works. But there is one thing I can't understand, How can I pass a gpointer param?
I trying to use a function who receive a buffer (with gpointer), and I always end with this message:
could not convert value for property `pixels' from LP_c_ubyte to gpointer
(LP_c_ubyte was my last try, but I have prove a lot of types)
You can't pass a pointer in GObject introspection. If the introspected function is one you wrote yourself, then you should annotate your parameter documentation with, for example, (array length=buflen), where buflen is the name for the parameter that gives the length of the buffer. See the linked page for more information.
If the function is in a library that you didn't write yourself, either look around in the API for a more introspection-friendly function, or file a bug with the library. APIs using bare gpointers shouldn't even be exposed to Python.

PyQt4 #pyqtSlot: what is the result kwarg for?

By reading this, two questions came up:
1.
It says
it is sometimes necessary to explicitly mark a Python method as being
a Qt slot
While I always use the #pyqtSlot decorator because it says:
Connecting a signal to a decorated Python method also has the
advantage of reducing the amount of memory used and is slightly faster
I ask myself: in which specific cases is it necessary?
and: Are there any advantages of not using the #pyqtSlot decorator?
2.
The result keyword argument, what is its purpose?
#pyqtSlot(int, result=int)
def foo(self, arg1):
""" C++: int foo(int) """
It looks like the return value's type, but AFAIK you cannot retrieve return values when emitting signals.
Any ideas about that?
It is faster because of PyQt architecture. PyQt converts the python slots to C++ slots, in order to communicate with the Qt framework. When you explicitly mark a Python method as a Qt slot and provide a C++ signature for it, the PyQt code doesn't have to guess the C++ signature itself, as it is already specified. This may enhance performance on heavy projects.
The return value is only needed when you want to call the slot as a normal function.
Edit: It seems that the QMetaObject.invokeMethod method executes a slot and uses it's return value.

Statically Typed Metaprogramming?

I've been thinking about what I would miss in porting some Python code to a statically typed language such as F# or Scala; the libraries can be substituted, the conciseness is comparable, but I have lots of python code which is as follows:
#specialclass
class Thing(object):
#specialFunc
def method1(arg1, arg2):
...
#specialFunc
def method2(arg3, arg4, arg5):
...
Where the decorators do a huge amount: replacing the methods with callable objects with state, augmenting the class with additional data and properties, etc.. Although Python allows dynamic monkey-patch metaprogramming anywhere, anytime, by anyone, I find that essentially all my metaprogramming is done in a separate "phase" of the program. i.e.:
load/compile .py files
transform using decorators
// maybe transform a few more times using decorators
execute code // no more transformations!
These phases are basically completely distinct; I do not run any application level code in the decorators, nor do I perform any ninja replace-class-with-other-class or replace-function-with-other-function in the main application code. Although the "dynamic"ness of the language says I can do so anywhere I want, I never go around replacing functions or redefining classes in the main application code because it gets crazy very quickly.
I am, essentially, performing a single re-compile on the code before i start running it.
The only similar metapogramming i know of in statically typed languages is reflection: i.e. getting functions/classes from strings, invoking methods using argument arrays, etc. However, this basically converts the statically typed language into a dynamically typed language, losing all type safety (correct me if i'm wrong?). Ideally, I think, I would have something like the following:
load/parse application files
load/compile transformer
transform application files using transformer
compile
execute code
Essentially, you would be augmenting the compilation process with arbitrary code, compiled using the normal compiler, that will perform transformations on the main application code. The point is that it essentially emulates the "load, transform(s), execute" workflow while strictly maintaining type safety.
If the application code are borked the compiler will complain, if the transformer code is borked the compiler will complain, if the transformer code compiles but doesn't do the right thing, either it will crash or the compilation step after will complain that the final types don't add up. In any case, you will never get the runtime type-errors possible by using reflection to do dynamic dispatch: it would all be statically checked at every step.
So my question is, is this possible? Has it already been done in some language or framework which I do not know about? Is it theoretically impossible? I'm not very familiar with compiler or formal language theory, I know it would make the compilation step turing complete and with no guarantee of termination, but it seems to me that this is what I would need to match the sort of convenient code-transformation i get in a dynamic language while maintaining static type checking.
EDIT: One example use case would be a completely generic caching decorator. In python it would be:
cacheDict = {}
def cache(func):
#functools.wraps(func)
def wrapped(*args, **kwargs):
cachekey = hash((args, kwargs))
if cachekey not in cacheDict.keys():
cacheDict[cachekey] = func(*args, **kwargs)
return cacheDict[cachekey]
return wrapped
#cache
def expensivepurefunction(arg1, arg2):
# do stuff
return result
While higher order functions can do some of this or objects-with-functions-inside can do some of this, AFAIK they cannot be generalized to work with any function taking an arbitrary set of parameters and returning an arbitrary type while maintaining type safety. I could do stuff like:
public Thingy wrap(Object O){ //this probably won't compile, but you get the idea
return (params Object[] args) => {
//check cache
return InvokeWithReflection(O, args)
}
}
But all the casting completely kills type safety.
EDIT: This is a simple example, where the function signature does not change. Ideally what I am looking for could modify the function signature, changing the input parameters or output type (a.l.a. function composition) while still maintaining type checking.
Very interesting question.
Some points regarding metaprogramming in Scala:
In scala 2.10 there will be developments in scala reflection
There is work in source to source transformation (macros) which is something you are looking for: scalamacros.org
Java has introspection (through the reflection api) but does not allow self modification. However you can use tools to support this (such as javassist). In theory you could use these tools in Scala to achieve more than introspection.
From what I could understand of your development process, you separate your domain code from your decorators (or a cross cutting concern if you will) which allow to achieve modularity and code simplicity. This can be a good use for aspect oriented programming, which allows to just that. For Java theres is a library (aspectJ), however I'm dubious it will run with Scala.
So my question is, is this possible?
There are many ways to achieve the same effect in statically-typed programming languages.
You have essentially described the process of doing some term rewriting on a program before executing it. This functionality is perhaps best known in the form of the Lisp macro but some statically typed languages also have macro systems, most notably OCaml's camlp4 macro system which can be used to extend the language.
More generally, you are describing one form of language extensibility. There are many alternatives and different languages provide different techniques. See my blog post Extensibility in Functional Programming for more information. Note that many of these languages are research projects so the motivation is to add novel features and not necessarily good features, so they rarely retrofit good features that were invented elsewhere.
The ML (meta language) family of languages including Standard ML, OCaml and F# were specifically designed for metaprogramming. Consequently, they tend to have awesome support for lexing, parsing, rewriting, interpreting and compiling. However, F# is the most far removed member of this family and lacks the mature tools that languages like OCaml benefit from (e.g. camlp4, ocamllex, dypgen, menhir etc.). F# does have a partial implementation of fslex, fsyacc and a Haskell-inspired parser combinator library called FParsec.
You may well find that the problem you are facing (which you have not described) is better solved using more traditional forms of metaprogramming, most notably a DSL or EDSL.
Without knowing why you're doing this, it's difficult to know whether this kind of approach is the right one in Scala or F#. But ignoring that for now, it's certainly possible to achieve in Scala, at least, although not at the language level.
A compiler plugin gives you access to the tree and allows you to perform all kinds of manipulation of that tree, all fully typechecked.
There are some issues with generating synthetic methods in Scala compiler plugins - it's difficult for me to know whether that will be a problem for you.
It is possible to work around this by creating a compiler plugin that generates source code which is then compiled in a separate pass. This is how ScalaMock works, for instance.
You might be interested in source-to-source program transformation systems (PTS).
Such tools parse the source code, producing an AST, and then allow one to define arbitrary analyses and/or transformations on the code, finally regenerating source code from the modified AST.
Some tools provide parsing, tree building and AST navigation by a procedural interface, such as ANTLR. Many of the more modern dynamic languages (Python, Scala, etc.) have had some self-hosting parser libraries built, and even Java (compiler plug-ins) and C# (open compiler) are catching on to this idea.
But mostly these tools only provide procedural access to the AST. A system with surface-syntax rewriting allows you to express "if you see this change it to that" using patterns with the syntax of the language(s) being manipulated. These include Stratego/XT and TXL.
It is our experience that manipulating complex languages requires complex compiler support and reasoning; this is the canonical lesson from 70 years of people building compilers. All of the above tools suffer from not having access to symbol tables and various kinds of flow analysis; after all, how one part of the program operates, depends on action taken in remote parts, so information flow is fundamental. [As noted in comments on another answer, you can implement symbol tables/flow analysis with those tools; my point is they give you no special support for doing so, and these are difficult tasks, even worse on modern languages with complex type systems and control flows].
Our DMS Software Reengineering Toolkit is a PTS that provides all of the above facilities (Life After Parsing), at some cost in configuring it to your particular language or DSL, which we try to ameliorate by providing these off-the-shelf for mainstream languages. [DMS provides explicit infrastructure for building/managing symbol tables, control and data flow; this has been used to implement these mechanisms for Java 1.8 and full C++14].
DMS has also been used to define meta-AOP, tools that enable one to build AOP systems for arbitrary languages and apply AOP like operations.
In any case, to the extent that you simply modify the AST, directly or indirectly, you have no guarantee of "type safety". You can only get that by writing transformation rules that don't break it. For that, you'd need a theorem prover to check that each modification (or composition of such) didn't break type safety, and that's pretty much beyond the state of the art. However, you can be careful how you write your rules, and get pretty useful systems.
You can see an example of specification of a DSL and manipulation with surface-syntax source-to-source rewriting rules, that preserves semantics, in this example that defines and manipulates algebra and calculus using DMS. I note this example is simple to make it understandable; in particular, its does not exhibit any of the flow analysis machinery DMS offers.
Ideally what I am looking for could modify the function signature, changing the input parameters or output type (a.l.a. function composition) while still maintaining type checking.
I have same need for making R APIs available in the type safe world. This way we would bring the wealth of scientific code from R into the (type) safe world of Scala.
Rationale
Make possible documenting the business domain aspects of the APIs through Specs2 (see https://etorreborre.github.io/specs2/guide/SPECS2-3.0/org.specs2.guide.UserGuide.html; is generated from Scala code). Think Domain Driven Design applied backwards.
Take a language oriented approach to the challenges faced by SparkR which tries to combine Spark with R.
See https://spark-summit.org/east-2015/functionality-and-performance-improvement-of-sparkr-and-its-application/ for attempts to improve how it is currently done in SparkR. See also https://github.com/onetapbeyond/renjin-spark-executor for a simplistic way to integrate.
In terms of solutioning this we could use Renjin (Java based interpreter) as runtime engine but use StrategoXT Metaborg to parse R and generate strongly typed Scala APIs (like you describe).
StrategoTX (http://www.metaborg.org/en/latest/) is the most powerful DSL development platform I know. Allows combining/embedding languages using a parsing technology that allows composing languages (longer story).

Categories