Using suppressMessages in rpy2 still prints messages - rpy2

I'd like to suppress messages from R in rpy2 and thought the following would be enough:
>>> from rpy2.robjects.packages import importr
>>> import rpy2.robjects as robjs
>>> suppmsg = robjs.r["suppressMessages"]
but then I get:
>>> suppmsg(robjs.r.message("hello"))
R[write to console]: hello
I don't mind the messages during interactive work, but I want them off in a library. How can they be turned off?

Your code might not do what you expect to because in R the evaluation of expressions is lazy and in Python it is not.
For example, when doing in R
suppressMessages(library("foo"))
what happens is that the function suppressMessages() is called with the unevaluated expression library("foo") as an argument. In the body of the function suppressMessages() code that turns off the display of messages globally is first run, and then the expression is evaluated, and finally code that restores the display of messages is run.
In Python, doing
suppmsg(robjs.r.message("hello"))
will first evaluate robjs.r.message("hello") (which calls the R function function message() through rpy2) and the result of this evaluation (what is returned by the function) is passed as an argument to suppmsg().
If you only want to silence import of a library, the function rpy2.robjects.packages.quiet_require() can do that for you.

Related

How to fix this IndetationError in python?

from timeit import Timer
timer_obj1 = Timer('list_sum()'),
'from_main_import list_sum'
timer_obj2 = Timer('numpy_arr_sum()'),
'from_main_import numpy_arr_sum'
print('Pure python version:',timer_obj1.timeit(1000))
print('Numpy version:',timer_obj2.timeit(1000))
this is the code I key in
after run it, shows unexpected indent in line 3
Anyone can help me out, please?
You closed the parentheses of Timer class's constructor (basically a function), but attempted to insert another argument to it with a different indent. You can't do that.
Do it like that:
from timeit import Timer
timer_obj1 = Timer('list_sum()',
'from_main_import list_sum')
timer_obj2 = Timer('numpy_arr_sum()',
'from_main_import numpy_arr_sum')
...

What's the difference between the method .get() and the method .get in python? Both are appliable to dictionaries

Imagine I have a dict.
d = ['a': 1 , 'b':3]
I'm having a hard time to understand the difference between d.get and d.get().
I know that d.get() get the value from the key, like this:
print(d.get('a') )
output: 1
But when I write d.get, it shows this:
print(d.get)
output: <built-in method get of dict object at .........>
What is 'd.get' doing in my code?
I'm using python 3X
A method is literally just an attribute of an object that happens to be of type <class function>. The output you see is essentially what happens when you try to call print() on any function object, and is essentially a concise string representation that python creates for the function.
Actually calling a function is done with parentheses: d.get('a'), which means to execute the behavior the function refers to. It doesn't especially matter where the function is, though: I could do the following, and it would still work:
d = {'a': 1 , 'b':3}
freefunc = d.get
freefunc('a')
This is what the term "first class functions" refers to, when people compare python to something like Java. An entire function can be encapsulated in a variable and treated no differently than any other variable or attribute.
The short answer? There is no difference between the two methods. They are the same exact method.
The difference in your code is at when you write .get() you call the method, but when you write .get you just get a pointer (or location in the memory, to be exact) for that method, to call it later on if needed.
In the first scenario, you are calling print on the result of executing get('a'), which in this case is 1.
In your second scenario, you are calling print on the get function itself, instead of on an execution of it, which evaluates to its documentation, i.e. <built-in method get of dict object at... etc.

Python: signature with Numba

I have a function that is doing some computation and at a certain point is calling another one. For example, the main function is something like:
import numba
#numba.njit(some signature here)
def my_funct():
...
value = cosd(angle)
Since the function cosd is inside another function decorated with numba.njit, it has to be decorated as well, and in my case it is:
from numba import float64
#numba.njit(float64(float64))
def cosd(angle):
return np.cos(np.radians(angle))
My problem now is that in another function, the input value angle is an array and the related output is an array as well. I know that I could decorate my function as #numba.njit(float64[:](float64[:])) but doing so the function would not accept scalars anymore. How can I can tell numba that input is something like Union[float64, float64[:]]? Of course this applies to the output as well. Thanks a lot!
I finally found an answer myself.
The solution is to create a list of signatures so, for my example, it would be:
from numba import float64
#njit([float64(float64), float64[:](float64[:])])
def cosd(angle):
return np.cos(np.radians(angle))
I hope this will be helpful to others.

Call a function dynamically from a variable - Python

Ok so I have two files, filename1.py and filename2.py and they both have a function with same name funB. The third file process.py has function that calls function from either files. I seem to be struggling in calling the correct function.
In process.py:
from directoryA.filename1 import funB
from directoryA.filename2 import funB
def funA:
#do stuff to determine which filename and save it in variable named 'd'
d = 'filename2'
# here i want to call funB with *args based on what 'd' is
So i have tried eval() like so:
call_right_funB = eval(d.funB(*args))
but it seems not to work.
Any help is appreciated.
The problem is, you can't use eval() with a combination of a string and a method like that. What you have written is:
call_right_funB = eval('filename'.funB(*args))
What you can do is:
call_right_funB = eval(d + '.funB(*args)')
But this is not very pythonic approach.
I would recommend creating a dictionary switch. Even though you have to import entire module:
import directoryA.filename1
import directoryA.filename2
dic_switch = {1: directoryA.filename1, 2: directoryA.filename2}
switch_variable = 1
call_right_funB = dic_switch[switch_variable].funB(*args)
Hope it helps.

python import as a variable name

I wanted to use import with a variable name. For example I wanted to do something like this
from var import my_class
I went through pythons documentation, but seems thats a little confusing. Also I seen some other posting on stack overflow that give the example of something like this
import importlib
my_module = importlib.import_module("var, my_class)
This second example does work to a certain extent. The only issue I see here var is imported but I don't see the attributes of my_class in python's namespace. How would I equate this to my original example of
from var import my_class
Here's how to use importlib (there is no need for the second parameter):
var = importlib.import_module("var")
# Now, you can use the content of the module:
var.my_class()
There is no direct programmable equivalent for from var import my_class.
Note: As #DYZ points out in the comments, this way of solving this is not recommended in favor of importlib. Leaving it here for the sake of another working solution, but the Python docs advise "Direct use of import() is also discouraged in favor of importlib.import_module()."
Do you mean that you want to import a module whose name is defined by a variable? If so, you can use the __import__ method. For example:
>>> import os
>>> os.getcwd()
'/Users/christophershroba'
>>>
>>> name_to_import = "os"
>>> variable_module = __import__(name_to_import)
>>> variable_module.getcwd()
'/Users/christophershroba'
If you also want to call a variable method of that variable module you could use the __getattribute__ method on the module to get the function, and then call it with () as normal. The line below marked "See note" is not necessary, I just include it to show that the __getattribute__ method is returning a function.
>>> name_to_import = "os"
>>> method_to_call = "getcwd"
>>> variable_module = __import__(name_to_import)
>>> variable_module.__getattribute__(method_to_call) # See note
<built-in function getcwd>
>>> variable_module.__getattribute__(method_to_call)()
'/Users/christophershroba'
More documentation available for Python 3 here or Python2 here.

Resources