This question already has answers here:
How to access (get or set) object attribute given string corresponding to name of that attribute
(3 answers)
Closed 8 years ago.
This has to be asked somewhere already, but I don't know the right words to find or frame it. So please bear with me.
This code fragment:
code = 'VegCode'
d = {}
codes = foo_func
for item in codes:
print item.code
Results in:
RuntimeError: Row: Field code does not exist
if I change it like this, it will work, but I don't want to hard code the variable name:
for item in codes:
print item.VegCode
How do I pass the value of code to the item object instead of it's name? (and please tell me what key words would have led to an answer!)
Use getattr: getattr(item, code)
Keywords: how to access object's attribute by its name
Related
This question already has answers here:
Flag duplicate keys in dictionary using pylint
(2 answers)
Closed 14 days ago.
Python dictionaries cannot have duplicate keys, so something typed in like this:
chessSet = {'1b': 'wpawn', '1b': 'wking', '1c': 'wpawn'}
will be reduced to
chessSet = {'1b': 'wking', '1c': 'wpawn'}
How can I check and ensure the data entered into the dictionary does not have duplicate keys?
Overall, my goal would be an error message warning that this mistake was made.
Edit: more specifically, I am referring to trying to catch mistakes of typing this information into the source code. Is there a way to check if someone made a typo and created a second duplicate key which will overwrite the first one?
You need to if the key is already assigned and raise a warning.
chessSet = {'b1': 'wpawn', '1c':'wpawn'}
def move(piece, to):
if to in chessSet:
initial_piece = chessSet[to]
chessSet[to] = piece
print(f"{piece} has captured {initial_piece}")
else:
chessSet[to] = piece
Then you can try:
move('b1', 'wking')
And see what happens
Also:
move('b2', 'wking')
This question already has answers here:
Type hinting a collection of a specified type
(5 answers)
Closed 1 year ago.
There is the following function:
import pdfplumber
from pdfplumber.page import Page
def searchFromFile(path:str,keyword:str) -> list[Page]:
with pdfplumber.open(path) as pdf:
result = [Page]
for page in pdf.pages:
pageText = page.extract_text()
if pageText != None and keyword in pageText:
result.append(page)
return result
In order to be more accurate, I defined the returned list with a generic type like in Java, i.e.list[Page], but it didn't work and got error:
TypeError: 'type' object is not subscriptable
Question: Is is possible at all to define the returned list with generic type?
The built-in list wasn't made a generic type until Python 3.9. In earlier versions, you'll have to use List (from the typing module) instead.
from typing import List
def searchFromFile(path:str, keyword:str) -> List[Page]:
I am not well versed at python at all. I was asked to review someone else's python script that uses search ldap entries. Btw - I can't reach out to original developer for some reason and before it is deployed + tested visual code checking is required. With that constraints in mind, allow me to proceed.
import ldap3
from ldap3 import Server,Connection, ALL
conn = Connection(....)
conn.search(....)
for entry in conn.entries:
if (len(entry['cn']) > 0):
....
name = entry['name']
if name:
user_name = str(name)
else:
user_name = "Bob"
First question is len(entry['cn']) > 0 I like to interpret it as checking the length of characters of returned cn value from ldap e.g. cn=bob,ou=people,ou=foocomany. I am pretty sure entry['cn'] is NOT string type but I don't know what data type it represents. Can you tell me what type it is?
My 2nd + 3rd questions are not directly related to the original question, but plz bear with me asking for them with grace.
My 2nd question is, if that assumption is correct, entry['cn'] should be converted to string type like str(entry['cn']). Then check its length?
My 3rd question is on if stmt. I like to interpret it as if name is not null or if name is not None in pythonic way. Did I interpret it correctly? If so I should replace it as if not (name is None) would work? I googled on it to get that stmt.
Given the context and code provided, it looks like this snippet is using the ldap3 library.
From the relevant documentation, conn.entries should be a list of Entry objects.
This means that entry['cn'] should be returning an Attribute. Doing a bit of source diving, this appears to just be a fancy list with writable flags. len(entry['cn']) > 0 ends up calling this method, which just returns the number of values that attribute has. It being greater than 0 just ensuring that the cn is, in fact, set.
This question already has an answer here:
Access specific information within worklogs in jira-python
(1 answer)
Closed 5 years ago.
I'm trying to insert the following worklog JSON fields that are part of an array using Python however I don't seem to be able to loop over an array in Python.
See code snippet below:
try:
worklogs_to_insert = []
for i in issue.fields.worklog["worklogs"]:
worklogs_to_insert.append(i)
except AttributeError as e:
log.info("Something went wrong when processing worklogs. :(")
log.info(e)
I am getting the following error when script is run:
Something went wrong when processing worklogs. :(
type object 'PropertyHolder' has no attribute 'worklog'
try using
for i in issue.fields.worklog.raw["worklogs"]
This question already has answers here:
Is there a simple way to delete a list element by value?
(25 answers)
Closed 6 years ago.
I have the following structure on a JSON file:
{
"channels": [
"180873781382873088",
"181268808055521280",
"183484852287307777",
"174886257636147201",
"174521530573651968"
]
}
I want to know how I can loop through the file searching for a specific string, and delete it if it matches.
Thank you.
EDIT: A Google search pointed me to using a for loop and using the del command to remove the key, so here's what I tried:
channel = "180873781382873088"
for item in data['channels']:
del channel
But it only deletes the variable channel, not the key that matches it's value.
Try
data['channels'].remove(channel)
instead of the for loop.
This will automatically search the array and remove any key matching your variable. If you need help saving the results to a file I would open another question.