Python: run a class method that takes an argument in a new thread - python-multithreading

I am trying to do the same thing as in this question: Run Class methods in threads (python), but the class method I want to invoke in a separate thread takes an extra argument, apart from self. A.Rodas's solution does not work: if I try Thread(target=self.class_method, args=(self, arg2)).start(), it says I have 3 arguments instead of 2, while if try args=(arg2), it is breaking my arg2 string into constituent elements and saying 334234 arguments! Any ideas? Thanks

You should do it like this:
threading.Thread(target=self.class_method, args=(arg2,)).start()

It is hard to tell from the format of your question, but I think the issue is that you shouldn't be including self in the args tuple.
i.e.
threading.Thread(target=self.class_method, args=(arg2)).start()

Related

How to make a class that inherits the same methods as IO::Path?

I want to build a class in Raku. Here's what I have so far:
unit class Vimwiki::File;
has Str:D $.path is required where *.IO.e;
method size {
return $.file.IO.s;
}
I'd like to get rid of the size method by simply making my class inherit the methods from IO::Path but I'm at a bit of a loss for how to accomplish this. Trying is IO::Path throws errors when I try to create a new object:
$vwf = Vimwiki::File.new(path => 't/test_file.md');
Must specify a non-empty string as a path
in block <unit> at t/01-basic.rakutest line 24
Must specify a non-empty string as a path
I always try a person's code when looking at someone's SO. Yours didn't work. (No declaration of $vwf.) That instantly alerts me that someone hasn't applied Minimal Reproducible Example principles.
So I did and less than 60 seconds later:
IO::Path.new
Yields the same error.
Why?
The doc for IO::Path.new shows its signature:
multi method new(Str:D $path, ...
So, IO::Path's new method expects a positional argument that's a Str. You (and my MRE) haven't passed a positional argument that's a Str. Thus the error message.
Of course, you've declared your own attribute $path, and have passed a named argument to set it, and that's unfortunately confused you because of the coincidence with the name path, but that's the fun of programming.
What next, take #1
Having a path attribute that duplicates IO::Path's strikes me as likely to lead to unnecessary complexity and/or bugs. So I think I'd nix that.
If all you're trying to do is wrap an additional check around the filename, then you could just write:
unit class Vimwiki::File is IO::Path;
method new ($path, |) { $path.IO.e ?? (callsame) !! die 'nope' }
callsame redispatches the ongoing routine call (the new method call), with the exact same arguments, to the next best fitting candidate(s) that would have been chosen if your new one containing the callsame hadn't been called. In this case, the next candidate(s) will be the existing new method(s) of IO::Path.
That seems fine to get started. Then you can add other attributes and methods as you see fit...
What next, take #2
...except for the IO::Path bug you filed, which means you can't initialize attributes in the normal way because IO::Path breaks the standard object construction protocol! :(
Liz shows one way to workaround this bug.
In an earlier version of this answer, I had not only showed but recommended another approach, namely delegation via handles instead of ordinary inheritance. I have since concluded that that was over-complicating things, and so removed it from this answer. And then I read your issue!
So I guess the delegation approach might still be appropriate as a workaround for a bug. So if later readers want to see it in action, follow #sdondley's link to their code. But I'm leaving it out of this (hopefully final! famous last words...) version of this answer in the hope that by the time you (later reader) read this, you just need to do something really simple like take #1.

SyntaxError: unexpected EOF while parsing on MRJob

I am working with MRJob through python and when I try to create a class, I get a synthax error. It's highlighting the colon. What am I missing? Here is my code:
class Bacon_count(MRJob):
You are defining an empty class, but in an unproper way. In Python an empty class should contain a pass statement, in your case:
class Bacon_count(MRJob):
pass
Also, take into account how to define single class methods in multiple cells, if that's what you are trying to do, as it is discussed here.

How can one invoke the non-extension `run` function (the one without scope / "object reference") in environments where there is an object scope?

Example:
data class T(val flag: Boolean) {
constructor(n: Int) : this(run {
// Some computation here...
<Boolean result>
})
}
In this example, the custom constructor needs to run some computation in order to determine which value to pass to the primary constructor, but the compiler does not accept the run, citing Cannot access 'run' before superclass constructor has been called, which, if I understand correctly, means instead of interpreting it as the non-extension run (the variant with no object reference in https://kotlinlang.org/docs/reference/scope-functions.html#function-selection), it construes it as a call to this.run (the variant with an object reference in the above table) - which is invalid as the object has not completely instantiated yet.
What can I do in order to let the compiler know I mean the run function which is not an extension method and doesn't take a scope?
Clarification: I am interested in an answer to the question as asked, not in a workaround.
I can think of several workarounds - ways to rewrite this code in a way that works as intended without calling run: extracting the code to a function; rewriting it as a (possibly highly nested) let expression; removing the run and invoking the lambda (with () after it) instead (funnily enough, IntelliJ IDEA tags that as Redundant lambda creation and suggests to Inline the body, which reinstates the non-compiling run). But the question is not how to rewrite this without using run - it's how to make run work in this context.
A good answer should do one of the following things:
Explain how to instruct the compiler to call a function rather than an extension method when a name is overloaded, in general; or
Explain how to do that specifically for run; or
Explain that (and ideally also why) it is not possible to do (ideally with supporting references); or
Explain what I got wrong, in case I got something wrong and the whole question is irrelevant (e.g. if my analysis is incorrect, and the problem is something other than the compiler construing the call to run as this.run).
If someone has a neat workaround not mentioned above they're welcome to post it in a comment - not as an answer.
In case it matters: I'm using multi-platform Kotlin 1.4.20.
Kotlin favors the receiver overload if it is in scope. The solution is to use the fully qualified name of the non-receiver function:
kotlin.run { //...
The specification is explained here.
Another option when the overloads are not in the same package is to use import renaming, but that won't work in this case since both run functions are in the same package.

How to properly declarate a suspend inline function with reified parameters?

I haven't found any simular questions and answers, but I don't understand what I should do in a situation like this: there is a function with long declaration and not so long name.
Is there any convention rule saying about breaking a line there? or the only way is to shorten method name?
The only improvement I see here is that you add the generic type constraints using where at the end (on a new line).
Check out the docs: https://kotlinlang.org/docs/reference/generics.html#generic-constraints

Test method existence on Objects

I have a cell array of Matlab objects, something like:
objs = {Object1(), Object2(), Object3()};
These objects are all of different types. Some of them will have a method, let's call it myMethod(). I want to do something like:
for o = objs
if hasMethod(o, 'myMethod()')
o.myMethod();
end
end
and my difficulty is that I don't know how to do hasMethod - exist doesn't seem helpful here.
I could use a try - catch, but I'd rather do something neater. Is there a way to do this? Should I just change my design instead?
Another option is to use the meta class.
obmeta = metaclass(ob);
methodNames = cellfun(#(x){x.Name},obmeta.Methods);
You can also get additional information from obmeta.Methods like
Amount of input/output parameters.
Access type
In which class the method is defined.
Also, metaclass can be constructed from the name of the class, without an instance, which can be an advantage in some situations.
Ah, found it. Not very exciting - you can get a list of methods with the methods command. So to check if an object has a method,
if any(strcmp(methods(o), 'myMethod'))
o.myMethod();
end
Very close! If you had written the function name a bit differently you would've stumbled upon the following built-in:
if ismethod(o, 'myMethod')
o.myMethod();
end
Documentation: ismethod.
Why would you want to do that? You'd better have a good reason :p
Better make them inherit a general function from a superclass. Then you can just call that function for all of them, instead of looking up which class it is/checking if a function exists and then calling a function depending on the result (which is imo not very OO)
One simple option is to use the function EXIST (along with the function CLASS) to check if the method exists for the given class:
if exist(['#' class(o) '/myMethod'])
o.myMethod();
end
Another option is to use the function WHICH to perform the check like this:
if ~isempty(which([class(o) '/myMethod']))
o.myMethod();
end