This is a follow-up question to this other one.
I am trying to extend gtk.Builder but I found out that once the builder is instantiated one can only call the connect_signals method once: if called more than once, any call after the second will return None (which would mean: all signals have been connected, which is a blatant lie!).
The problem is that in my design I would need to pass around the builder instance to various modules (each of them has some of the handlers for managing the GUI), but this way, I can't.
I tried to see if I could understand how/where gtk.Builder stores the handler names that assigned withing the Glade GUI, in order to write my own method to overcome this limitation, but after more than an hour of console experiments I still haven't understand where this information is stored.
Any help or pointer is highly appreciated! :)
That connect_signals only works once is an old but undocumented limitation of the GtkBuilder C code. Especially from Python there is no way to access its internals to remedy that.
Instead of the builder you could pass around a dictionary. After everyone added their handlers you call connect_signals with it.
i think if you want to call connect_signals multiple times you must disconnect inbetween, kindof like
x = self.menu.connect('activate', self.func1)
self.menu.disconnect(x)
x = self.menu.connect('activate', self.func2)
Related
Spent a little too much time trying to figure it out by myself...
I'm working with a FEA app called Simcenter Femap. In my program I need to create N new instances of it after I get some data from base instance for some asyncio fun. Can't even start on the asyncio part because I can't force early binding on new instances.
What is working for me at this point:
Created a makepy wrapper, called it PyFemap as Femap help is suggesting, made an import
Connected to a running instance
femap_object = pythoncom.connect('femap.model')
feAppBaseInstance = PyFemap.model(femap_object)
Every method of every Femap object works perfectly fine after this.
I am able to create instances using DispatchEx('femap.model') and invoke methods that don't require data conversion.
But for the rest of the methods to work I need to force early binding on these instances through already existing wrapper (as I see it).
"Python programming on win32" suggests that I use gencache.EnsureModule to create a wrapper and link it to created instance. But when I try to do it through type library's CLSID I get an error that it's not registered. Is there really no way to do it with a wrapper I already created?
Also tried to do all of this using comtypes. Some parts work better for me with it some are worse. But the end result is the same. If I may, I'd like to ask how to do it with comtypes too.
Sorry if I'm missing something really obvious.
I recommend using pythoncom.New(...) instead of .connect(...).
I'll post the solution since I solved the issue.
It is actually really obvious. I ended up using pythoncom.New(...) for multiple instances, but I think other methods would work just as well if you only need one. The issue was that I didn't attach the wrapper head class (model) to these new instances, which was pretty silly of me.
To create a new instance
femap_object = pythoncom.new('femap.model')
To assign a win32 wrapper (PyFemap) to it.
new_instance = PyFemap.model(femap_object)
I was wandering in the source code of the fabulous python-chess library when I saw the following code:
def _reset_board(self):
# code...
def reset_board(self):
self._reset_board()
The reset_board() function only does one thing, call its private counterpart. Is there a reason behind this? Wouldn't putting the code directly in the private function be faster due to python not have to resolve the name _reset_board()?
_reset_board exists so it can be called from both reset_board and __init__. __init__ can't call self.reset_board, because that method is overridden in subclasses, and __init__ wants to call the specific _reset_board implementation from its own class. (Subclass reset_board implementations may depend on initialization that hasn't happened yet, among other problems.)
I agree with you, here this _reset_board is not necessary. The author probably did some wrapping/cleaning in the reset_board method before, removed it, and didn't take the time to remove the _reset_board. Or maybe he plans to add some wrapping/cleaning in there in the future.
Some project also may generate Documentation automatically based on the code, and may skip functions/method that start with a _, and he may not want to publish any documentation for this function, but being open source, it's probably not the real reason.
I'm wondering how to go about implementing a macro recorder for a python gui (probably PyQt, but ideally agnostic). Something much like in Excel but instead of getting VB macros, it would create python code. Previously I made something for Tkinter where all callbacks pass through a single class that logged actions. Unfortunately my class doing the logging was a bit ugly and I'm looking for a nicer one. While this did make a nice separation of the gui from the rest of the code, it seems to be unusual in terms of the usual signals/slots wiring. Is there a better way?
The intention is that a user can work their way through a data analysis procedure in a graphical interface, seeing the effect of their decisions. Later the recorded procedure could be applied to other data with minor modification and without needing the start up the gui.
You could apply the command design pattern: when your user executes an action, generate a command that represents the changes required. You then implement some sort of command pipeline that executes the commands themselves, most likely just calling the methods you already have. Once the commands are executed, you can serialize them or take note of them the way you want and load the series of commands when you need to re-execute the procedure.
Thinking in high level, this is what I'd do:
Develop a decorator function, with which I'd decorate every event-handling functions.
This decorator functions would take note of thee function called, and its parameters (and possibly returning values) in a unified data-structure - taking care, on this data structure, to mark Widget and Control instances as a special type of object. That is because in other runs these widgets won't be the same instances - ah, you can't even serialize a toolkit widget instances, be it Qt or otherwise.
When the time comes to play a macro, you fill-in the gaps replacing the widget-representating object with the instances of the actually running objects, and simply call the original functions with the remaining parameters.
In toolkits that have an specialized "event" parameter that is passed down to event-handling functions, you will have to take care of serializing and de-serializing this event as well.
I hope this can help. I could come up with some proof of concept code for that (although I am in a mood to use tkinter today - would have to read a lot to come up with a Qt4 example).
An example of what you're looking for is in mayavi2. For your purposes, mayavi2's "script record" functionality will generate a Python script that can then be trivially modified for other cases. I hear that it works pretty well.
I'm programming a game in Python, where all IO activities are done by an IO object (in the hope that it will be easy to swap that object out for another which implements a different user interface). Nearly all the other objects in the game need to access the IO system at some point (e.g. printing a message, updating the position of the player, showing a special effect caused by an in-game action), so my question is this:
Does it make sense for a reference to the IO object to be available globally?
The alternative is passing a reference to the IO object into the __init__() of every object that needs to use it. I understand that this is good from a testing point of view, but is this worth the resulting "function signature pollution"?
Thanks.
Yes, this is a legitimate use of a global variable. If you'd rather not, passing around a context object that is equivalent to this global is another option, as you mentioned.
Since I assume you're using multiple files (modules), why not do something like:
import io
io.print('hello, world')
io.clear()
This is a common way programs that have more complex I/O needs than simple printing do things like logging.
Yes, I think so.
Another possibility would be to create a module loggerModule that has functions like print() and write(), but this would only marginally be better.
Nope.
Variables are too specific to be passed around in the global namespace. Hide them inside static functions/classes instead that can do magic things to them at run time (or call other ones entirely).
Consider what happens if the IO can periodically change state or if it needs to block for a while (like many sockets do).
Consider what happens if the same block of code is included multiple times. Does the variable instance get duplicated as well?
Consider what happens if you want to have a version 2 of the same variable. What if you want to change its interface? Do you have to modify all the code that references it?
Does it really make sense to infect all the code that uses the variable with knowledge of all the ways it can go bad?
Let's say that i have a Python module to control a videoconference system. In that module i have some global variables and functions to control the states of the videoconference, the calls, a phone book, etc.
To start the control system, the module self-executes a function to initialize the videoconference (ethernet connection, polling states and so)
Now, if i need to start controlling a second videoconference system, i'm not sure how to approach that problem: i thought about making the videoconference module a class and create two instances (one for each videoconference system) and then initialize both, but the problem is that i don't really need to have two instances of a videoconference class since i won't do anything with those objects because i only need to initialize the systems; after that i don't need to call or keep them for anything else.
example code:
Videoconference.py
class Videoconference:
def __init__(self):
self.state = 0
#Initialization code
Main.py
from Videoconference import Videoconference
vidC1 = Videoconference()
vidC2 = Videoconference()
#vidC1 and vidC2 will never be use again
So, the question is: should i convert the videoconference module to a class and create instances (like in the example), even if i'm not going to use them for anything else appart of the initialization process? Or is there another solution without creating a class?
Perhaps this is a matter of preference, but I think having a class in the above case would be the safer bet. Often I'll write a function and when it gets too complicated I'll think that I should have created a class (and often do so), but I've never created a class that was too simple and thought that this is too easy why didn't I just create a function.
Even if you have one object instead of two, it often helps readability to create a class. For example:
vid = VideoConference()
# vid.initialize_old_system() # Suppose you have an old system that you no longer use
# But want to keep its method for reference
vid.initialize_new_system()
vid.view_call_history(since=yesterday)
This sounds like the perfect use case for a VideoConferenceSystem object. You say you have globals (ew!) that govern state (yuck!) and calls functions for control.
Sounds to me like you've got the chance to convert that all to an object that has attributes that hold state and methods to mutate it. Sounds like you should be refactoring more than just the initialization code, so those vidC1 and vidC2 objects are useful.
I think you're approaching this problem the right way in your example. In this way, you can have multiple video conferences, each of which may have different attribute states (e.g. vidC1.conference_duration, etc.).