I've got a python script using PySide and it works fine.
But then I thought to check if it gonna work with PyQt4.
And after changing the import strings to PyQt4, things went wrong.
The error points to the subject, as follows:
File "./my_file.py", line 93, in showit
curr_query = '.'.join(curr_query)
TypeError: sequence item 0: expected string, QString found
From the docs I can see that PySide subject method returns 'unicode' string,
but the PyQt4 one returns QString object.
Playing with the str(), str() etc did not seem to do the job.
Here's the function code:
def showit(self, idx):
curr_query = []
for i in xrange(idx+1):
>> x = self.combo[i].currentText()
>> if x:
curr_query.append(x)
else:
break
curr_query = '.'.join(curr_query)
This reads text of a set of QCombobox'es to build up a dot-sepated string presentation that I use later.
The marked '>>' lines is where the issue occurs - the 'x' object is never an empty string, suddenly, as it was while using PySide library. But it is expected to be empty, if there's an empty self.combo[i] .
I've searched the SO archive and found this answer but not able to use it.
Please advice how to fix this.
You need to convert your x values to a string of sorts. Something like
curr_query.append(str(x))
should do the trick.
Related
I am trying to execute the command abs.__ doc__ inside the exec() function but for some reason it does not work.
function = input("Please enter the name of a function: ")
proper_string = str(function) + "." + "__doc__"
exec(proper_string)
Essentially, I am going through a series of exercises and one of them asks to provide a short description of the entered function using the __ doc__ attribute. I am trying with abs.__ doc__ but my command line comes empty. When I run python in the command line and type in abs.__ doc__ without anything else it works, but for some reason when I try to input it as a string into the exec() command I can't get any output. Any help would be greatly appreciated. (I have deliberately added spaces in this description concerning the attribute I am trying to use because I get bold type without any of the underscores showing.)
As a note, I do not think I have imported any libraries that could interfere, but these are the libraries that I have imported so far:
import sys
import datetime
from math import pi
My Python version is Python 3.10.4. My operating system is Windows 10.
abs.__doc__ is a string. You should use eval instead of exec to get the string.
Example:
function = input("Please enter the name of a function: ")
proper_string = str(function) + "." + "__doc__"
doc = eval(proper_string)
You can access it using globals():
def func():
"""Func"""
pass
mine = input("Please enter the name of a function: ")
print(globals()[mine].__doc__)
globals() return a dictionary that keeps track of all the module-level definitions. globals()[mine] is just trying to lookup for the name stored in mine; which is a function object if you assign mine to "func".
As for abs and int -- since these are builtins -- you can look it up directly using getattr(abs, "__doc__") or a more explicit: getattr(__builtins__, "abs").__doc__.
There are different ways to lookup for a python object corresponding to a given string; it's better not to use exec and eval unless really needed.
I want to make a sort of help() function for my module. My idea is to have something like module.help() that just prints out the __doc__ of my functions. My first approach was just to hardcode them and then iterate over them, but I feel there has to be a better way to do so. I looked through the docs for a reference as to where they are stored but couldn't find any. What I want is the python equivalent to this but for function names. I would appreciate if anyone could help me out. Thanks!
Edit: Ok so as of now the functions I have are:
BoyleGraph
Boyle_Resolve
Boyle_k
Boyle_k_solve
GayLussacGraph
GayLussac_Resolve
`
and what I have tried so far is:
funcs = list()
for f in dir():
funcs.append(f)
def helper():
for f in funcs[:-13]:
print(help(f))
and this returns something like (redacted):
No Python documentation found for 'GayLussac_Resolve'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.
Now using:
def helper():
for f in funcs[:-13]:
print(f)
will give me:
BoyleGraph
Boyle_Resolve
Boyle_k
Boyle_k_solve
GayLussacGraph
GayLussac_Resolve
but doing:
def helper():
for f in funcs[:-13]:
print(f, '\n', '#' * 50)
print(f.__doc__)
gives me (redacted):
GayLussac_Resolve
##################################################
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
which is the __doc__ of str() which is not even in the funcs list. I feel I'm so close yet so far.
PS: I know the funcs definition looks sloppy but when I try to assign directly or use list comprehensions I only get the first element of dir()'s output
dir() gets you a list of names, not objects. You could use the values of globals() instead, but you would need to filter out special names like __builtins__ and imports. Instead, just use help(module). It does everything you want, automatically.
So I have the following function in my Flask app.
def markup_abbreviations(txt, match_map, match_regex):
html = Markup.escape(txt)
sub_template = Markup('<abbr title="%s">%s</abbr>')
def replace_callback(m):
return sub_template % (match_map[m.group(0)], m.group(0))
return match_regex.sub(replace_callback, html)
Example arguments:
txt = 'blah blah blah etc., blah blah'
match_map = {
'etc.': 'et cetera',
'usu.': 'usually',
}
match_regex = re.compile(
'|'.join(r'\b' + re.escape(k) for k in match_map)
)
This was working very well and turning "etc." into "<abbr title=\"et cetera\">etc.</abbr>" and so on in my local Python 3.3 machine.
Then I figure I want to deploy to Heroku, and it says it only supports the latest python, which is Python 3.6.1. It's different from the one I got locally, but, eh, whatever. It works... mostly.
Except my function above gives me "<abbr title="et cetera">etc.</abbr>" now.
I assume between Python 3.3 and Python 3.6 the re.sub implementation must have changed somehow and now it no longer uses the passed string methods to create the output. So Markup's auto-escaping methods aren't used. Instead a new str is built from scratch. Which is why re.sub only returns str now, and not Markup anymore.
How can I use re.sub with jinja2.Markup in Python 3.6 and make my function work once again?
The Markup class just "mark" string as safe for html. It means that the string doesn't have to be escaped when it placed in to the template.
When the re.sub() return new str object what you have to do is mark the new object as safe (wrap it in the Markup).
def markup_abbreviations(txt, match_map, match_regex):
html = Markup.escape(txt)
sub_template = '<abbr title="%s">%s</abbr>'
def replace_callback(m):
return sub_template % (match_map[m.group(0)], m.group(0))
return Markup(match_regex.sub(replace_callback, html))
I check all "What's new" from Python 3.3 to 3.6 and there is nothing about changing behavior of re module (well there is something but it shouldn't be connected with your problem). Maybe someone else know what happend...
This question already has answers here:
What is the difference between __str__ and __repr__?
(28 answers)
Closed 6 years ago.
I've looked through many different forum posts and have tried a bunch of different techniques, but I have not figured out how to get my str function to return a string ' ' rather than having no quotations.
My Code:
class Comment:
def __init__(self,commenterName, content):
self.name = commenterName
self.content = content
def __str__(self):
return str('%s: %s' %(self.name, self.content))
From what I understand if I am accompanying my return value in my str function with str() it should return the string value.
Instead...:
>>>Comment("lol","lol")
<__main__.Comment object at 0x000000000354CF60>
I need to specifically return the value as a string rather than print it, that I know.
I am trying to get the output:
"lol": "lol"
but the best I have managed is a:
lol: lol
I have been working on this exact little problem for quite sometime and cannot figure out what I am doing wrong. Thank you for help in advance :D
P.S. I am trying to use
Comment(commenterName,content)
in the terminal so that it returns the value
'commenterName: content'
I'm trying to achieve this without using the print() command in the terminal as well as not using the str() command in the terminal. In my python file however, it is fine, I just need to return the value in some way. I hope this isn't too much of a repost, as I said I have tried to find the solutions, but I can't quite get them to work..
You need to call the __str__ function. Try
my_var = Comment('name', 'content')
print(str(my_var))
print('My message is: %s'.format(my_var)
I've just started learning Python recently and the first project I'm making is a text based adventure game however I've run into a problem. I need a function that makes more objects using the class Goblin that are named after a string.
def spawn(name):
title = name
exec("{0} = {1}".format('title', Goblin))
return title, 'spawn'
Essentially, another function calls this function to create another Goblin (a class) using the input name(a string) as the name of the new Goblin.
What I don't under stand though is that when I run the code(using "bill" as the argument), it gives me this error.
bill = <class '__main__.Goblin'>
^
SyntaxError: invalid syntax
Shouldn't my function be equivalent to:
bill = Goblin
When you do this:
exec("{0} = {1}".format('title', Goblin))
format method converts Goblin class by calling default __str__ method which yields <class '__main__.Goblin'>
Do this instead:
exec("{0} = {1}".format('title', 'Goblin'))
Wait! don't to this, just do:
title = Goblin
as it's strictly equivalent (without any security issues :)).
But that will just alias Goblin class to title. No real interest to all this after all (unless you want to create an instance?: title = Goblin())
With your comment: "I want a Goblin that is named after the string which title represents" I get it: you need
exec("{0} = {1}".format(title, 'Goblin()'))
(no quotes for the first arg so the name you're passing is used, and () on the second to create an instance)
Again: this is really a clumsy way of doing it. What if you want to iterate through all your goblins?
It would be much better to create a dictionary:
goblins_dict = dict()
goblins_dict["my_goblin"] = Goblin()
goblins_dict["my_goblin_2"] = Goblin()
and so on...