Skip to content
Advertisement

Using __str__ representation for printing objects in containers

I’ve noticed that when an instance with an overloaded __str__ method is passed to the print function as an argument, it prints as intended. However, when passing a container that contains one of those instances to print, it uses the __repr__ method instead. That is to say, print(x) displays the correct string representation of x, and print(x, y) works correctly,

SQLAlchemy: a better way for update with declarative?

Let’s say I have a user table in declarative mode: When I know user’s id without object loaded into session, I update such user like this: I dislike using User.__table__, should I stop worrying with that? Is there a better way to do this? Answer There’s also some update capability at the ORM level. It doesn’t handle any tricky cases

Extracting an attribute value with beautifulsoup

I am trying to extract the content of a single “value” attribute in a specific “input” tag on a webpage. I use the following code: I get TypeError: list indices must be integers, not str Even though, from the Beautifulsoup documentation, I understand that strings should not be a problem here… but I am no specialist, and I may have

Find full path of the Python interpreter?

How do I find the full path of the currently running Python interpreter from within the currently executing Python script? Answer sys.executable contains full path of the currently running Python interpreter. which is now documented here

How does Django save decimal values?

What am I doing wrong? I do something like that: count is the sum of all ratings of given MyModel and votes is an array of those ratings, their division gives an average rating for MyModel (sorry if I described it incorrectly due to my poor English). If i change previous to: Then ‘anything’ ends up in the database, but

Using Python How can I read the bits in a byte?

I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var = fread(file, 8, ‘ubit1’), and then retrieve each bit by var(1), var(2), etc. Is there any equivalent bit reader in python? Answer Read the bits from a file, low bits first.

Set the current directory when running a SimpleHTTPServer

Is there any way to set the directory where you want to start a SimpleHTTPServer or BaseHTTPServer? Answer If you’re using SimpleHTTPServer directly from command line, you can simply use shell features: In Python 3 you have to use: The SimpleHTTPServer module has been merged into http.server in Python 3.0

How to treat the last element in list differently in Python?

I need to do some special operation for the last element in a list. Is there any better way than this? array = [1,2,3,4,5] for i, val in enumerate(array): if (i+1) == len(array): // Process for the last element else: // Process for the other element Answer If you don’t want to make a copy of list, you can make

Advertisement