Yingjie Lan wrote:
> I am wondering when extending Python (CPython), what should be put into
> the C header file? Any guidelines?
You don't even need to write a header file at all. There are no Python-
specific requirements to put anything into a header file, though you might
want to do so for re
sl33k_ wrote:
> Isnt it like self must be the first parameter to the method/function?
"self" is just customary as first parameter to memberfunctions, the
language itself doesn't impose this convention, as e.g. C++ does with its
"this".
> Also, can the terms method and function be used intercha
Hmmm.
Is it just us that read this topic and think of an object with a psychic
disorder like multiple personalities?
:):
TGIF.
Uli
--
http://mail.python.org/mailman/listinfo/python-list
Nico Schlömer wrote:
> I ran into a bit of an unexpected issue here with itertools, and I
> need to say that I discovered itertools only recently, so maybe my way
> of approaching the problem is "not what I want to do".
>
> Anyway, the problem is the following:
> I have a list of dictionaries, som
Nico Schlömer wrote:
> So when I go like
>
> for item in list:
> item[1].sort()
>
> I actually modify *list*? I didn't realize that; I thought it'd just
> be a copy of it.
No, I misunderstood your code there. Modifying the objects inside the list
is fine, but I don't thing you do that, provi
Hi!
I have a list [1,2,3,4,5,6] which I'd like to iterate as (1,2), (3,4),
(5,6). I can of course roll my own, but I was wondering if there was
already some existing library function that already does this.
def as_pairs(seq):
i = iter(seq)
yield (i.next(), i.next())
Question to this cod
Ulrich Eckhardt wrote:
> I have a list [1,2,3,4,5,6] which I'd like to iterate as (1,2), (3,4),
> (5,6). I can of course roll my own, but I was wondering if there was
> already some existing library function that already does this.
>
>
> def as_pairs(seq):
> i = ite
Richard Lamboj wrote:
> i want to inherit from a data type. How can i do this? Can anyone explain
> more abou this?
Other than in e.g. C++ where int and float are special types, you can
inherit from them in Python like from any other type. The only speciality
of int, float and string is that they
Richard Lamboj wrote:
> "How knows python that it is a float, or a string?" Sorry this was bad
> expressed. I want to create a new data type, which inherits from float. I
> just know the "dir" function and the "help" function to get more
> infromations about the class, but i need to get more inform
Hi!
I wrote a simple loop like this:
d = {}
...
for k in d:
if some_condition(d[k]):
d.pop(k)
If I run this, Python complains that the dictionary size changed during
iteration. I understand that the iterator relies on the internal structure
not changing, but how would I str
Vincent Davis wrote:
> I am looking for the most efficient (speed) way to produce an an
> iterator to of permutations.
> One of the problem I am having it that neither combinations nor
> permutations does not exactly what I want directly.
> For example If I want all possible ordered lists of 0,1 of
Hi!
When I use help() on a function, it displays the arguments of the function,
along with the docstring. However, when wrapping the function using
functools.wraps it only displays the arguments that the (internal) wrapper
function takes, which is typically "*args, **kwargs", which isn't very
usef
Hi!
I have a class that maintains a network connection, which can be used to
query and trigger Things(tm). Apart from "normal" errors, a broken network
connection and a protocol violation from the peer are something we can't
recover from without creating a new connection, so those errors
should "s
Alfred Bovin wrote:
> I'm working on something where I need to read a (binary) file bit by bit
> and do something depending on whether the bit is 0 or 1.
Well, smallest unit you can read is an octet/byte. You then check the
individual digits of the byte using binary masks.
f = open(...)
da
Ulrich Eckhardt wrote:
>data = f.read()
>for byte in data:
>for i in range(8):
>bit = 2**i & byte
>...
Correction: Of course you have to use ord() to get from the single-element
string ("byte" above) to its integral value firs
Nobody wrote:
> On Mon, 07 Jun 2010 02:31:08 -0700, Richard Thomas wrote:
>
>> You're reading those bits backwards. You want to read the most
>> significant bit of each byte first...
>
> Says who?
Says Python:
>>> bin(192)
'0x1100'
That said, I totally agree that there is no inherently rig
Peter Otten wrote:
> Ulrich Eckhardt wrote:
>> Says Python:
>>
>>>>> bin(192)
>> '0x1100'
>
> Hmm, if that's what /your/ Python says, here's mine to counter:
>
>>>> bin(192)
> '0_totally_faked_binary_0
superpollo wrote:
> mine goes like this:
>
> >>> bin(192)
> Traceback (most recent call last):
>File "", line 1, in
> NameError: name 'bin' is not defined
Yep, one of mine, too. The "bin" function was new in 2.6, as were binary
number literals ("0b1100").
Uli
--
Sator Laser GmbH
Geschäft
superpollo wrote:
> ... s += i**2
> ... if not (i+1)%5:
> ... s -= 2*i**2
> ... if not i%5:
> ... s -= 2*i**2
if not (i % 5) in [1, 2]:
s += i**2
else:
s -= i**2
Untested code.
Uli
--
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR
aimeixu wrote:
> I really need help to figure out a way to get someone's calendar from
> mail exchange server with python.
You can implement any network protocol with Python, see e.g. the struct
library. However, it would be easier to use an existing protocol
implementation. When you say "mail exc
Daniel Fetchinson wrote:
> After getting the technicalities out of the way, maybe I should have
> asked:
>
> Is it only me or others would find a platform independent python API
> to clear the terminal useful?
There are two kinds of programs:
1. Those that process input to output. If one of those
wheres pythonmonks wrote:
> Thanks ... I thought int was a type-cast (like in C++) so I assumed I
> couldn't reference it.
Hopefully somebody correct me if I explain this badly, but I'll take a
shot...
Firstly, "int" is a class. Python doesn't make a distinction between builtin
types and class t
Steven D'Aprano wrote:
> Perhaps I have been misinformed, but my understanding of C type-casts is
> that (where possible), a cast like `int(var)` merely tells the compiler
> to temporarily disregard the type of var and treat it as if it were an
> int. In other words, it's a compiler instruction rat
Neil Cerutti wrote:
> Perhaps emailing the tests to yourself would be a good solution.
> Every tme the tests ran, you'd get a new email containing the
> results.
Nice idea, only that it's even less portable and requires manual setup...
;^)
Uli
--
Sator Laser GmbH
Geschäftsführer: Thorsten Föc
Joe Goldthwaite wrote:
> import unicodedata
>
> input = file('ascii.csv', 'rb')
> output = file('unicode.csv','wb')
>
> for line in input.xreadlines():
> unicodestring = unicode(line, 'latin1')
> output.write(unicodestring.encode('utf-8')) # This second encode
>
Brandon McCombs wrote:
> I'm building an elevator simulator for a class assignment. I recently
> ran into a roadblock and don't know how to fix it. For some reason, in
> my checkQueue function below, the call to self.goUp() is never executed.
[...]
> sorry about the formatting
While I can certainl
aimeixu wrote:
> a = "{'a':'1','b':'2'}"
> how to change a into a dictionary ,says, a = {'a':'1','b':'2'}
You could evaluate it as regular Python code, using "exec":
res = {}
exec("a={'a':'1'}", res)
print res['a']
However, if this is input from a file or the user, be aware that this opens
blur959 wrote:
> Hi, all, I am working on a simple program that renames files based on
> the directory the user gives, the names the user searched and the
> names the user want to replace. However, I encounter some problems.
> When I try running the script, when it gets to the os.rename part,
> the
targetsmart wrote:
> Right now if I want to dump the contents of a generator object I use ,
> a snip from a bigger block of code..
>
> try:
> while gen: print gen.next()
> except StopIteration:
> print "Done"
> else:
> raise
>
> is there a much simpler way ?
Why not something like this:
f
candide wrote:
> Python is an object oriented langage (OOL). The Python main
> implementation is written in pure and "old" C90. Is it for historical
> reasons?
The fact that Python is OOP doesn't mean that the implementation of it has
to be written using an OOP language.
Other than that, I'm actu
Carl Banks wrote:
> I highly doubt the Python source would build with a C++ compiler.
As Christian showed, it doesn't. However, look around the sources a bit.
There are lots of places where e.g. the returnvalue of malloc() (or,
rather, the macro that resolves to something like it) is explicitly
ty
Hi!
I have an extension module (a plugin written with Boost.Python) and around
that a wrapper class that adapts a few things. Since the module is a
plugin, there are multiple implementations of this. What I'm currently
doing is this:
plugin = __import__(plugin_name)
class PluginWrapper(plugin.
Peter Otten wrote:
> Use getattr()
>
class W(object):
> ... def __init__(self, wrapped): self._wrapped = wrapped
> ... def __getattr__(self, name):
> ... return getattr(self._wrapped, name)
> ...
I thought there was something like this, thanks! :)
When I read this, I tho
Peter Otten wrote:
> Ulrich Eckhardt wrote:
>> So, short follow-up question: Why does this work?
>
> __getattr__() is a fallback that is only tried when the normal lookup
> fails. If you need to intercept every attribute lookup use
> __getattribute__() instead:
Thank yo
Martin v. Loewis wrote:
> Am 10.08.2010 09:06, schrieb Ulrich Eckhardt:
>> When asked on the developers' list, it was said that this was
>> intended for compatibility with C++, e.g. in cases where people
>> want to embed Python into their C++ projects. Of course, this
sturlamolden wrote:
> On 11 Aug, 08:40, Ulrich Eckhardt wrote:
> Header (definition) and source (implementation) is not the same.
I'm aware of this and that's not the thing I was talking about.
Uli
--
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Ha
Jean-Michel Pichavant wrote:
> My problem is however simplier : how do I add such character [a BOM]
> at the begining of the file ?
> I tried
>
> f = open('paf', w)
> f.write(u'\ufeff')
>
> UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in
> position 0: ordinal not in range(12
Hi!
I need to pack a floating point value into a vector of 32-bit unsigned
values in IEEE format. Further, I maintain a CRC32 checksum for integrity
checking. For the latter, I actually need the float as integral value.
What I currently do is this:
tmp = struct.pack("=f", f)
(i,) = struct.un
casebash wrote:
> I know the bin function converts an int into a binary string.
Binary string sounds ambiguous. Firstly, everything is binary. Secondly,
strings are byte strings or Unicode strings. In any case, I'm not 100% sure
what you mean - giving an example of input and output would help!
>
Cassian Braconnier wrote:
> [...] completely broke Synaptic, and made it impossible to install any
> (other, non python) package with apt-get or dpkg commands.
This is not a Python error and it doesn't actually belong here.
> So far I could not get any useful advice on the french ubuntu users
> f
jeni wrote:
[ ..large backtrace.. ]
For your own sake and that of your readers, try next time to reduce the code
that causes the problems to a minimal example. This prevents people from
guessing or simply ignoring your problems.
> /home/Activities/Kremala.activity/Kremala.py in insert_text_file
>
Dave Angel wrote:
> Ulrich Eckhardt wrote:
>> open() doesn't take a string as second parameter, see 'help(open)'.
>> Instead, it takes one of the integers which are defined as symbols in the
>> os module, see 'dir(os)'.
>
> [...]The second
Ben Finney wrote:
> Paul Watson writes:
>> On Mon, 2009-04-13 at 17:03 +0200, WP wrote:
>> > dict = {1:'astring', 2:'anotherstring'}
>> > for key in dict.keys():
>> > print 'Press %i for %s' % (key, dict[key])
>>
>> In addition to the comments already made, this code will be quite
>> broken
krishna wrote:
> I need to convert 1010100110 boolean value to some think like 2345, if
> its possible then post me your comment on this
Yes, sure. You can simply sum up the digit values and then format them as
decimal number. You can also just look up the number:
def decode_binary(input):
Robert Kern wrote:
> I wish people would stop representing decimal floating point arithmetic as
> "more accurate" than binary floating point arithmetic.
Those that failed, learned. You only see those that haven't learnt yet.
Dialog between two teachers:
T1: Oh those pupils, I told them hundred ti
Hi!
I'm currently converting my bioware to handle Python code and I have
stumbled across a problem...
Simple scenario: I have a handle to a resource. This handle allows me to
manipulate the resource in various ways and it also represents ownership.
Now, when I put this into a class, instances to
Bearophile wrote:
> Ulrich Eckhardt:
>> a way to automatically release the resource, something
>> which I would do in the destructor in C++.
>
> Is this helpful?
> http://effbot.org/pyref/with.htm
Yes, it aims in the same direction. However, I'm not sure this app
Thanks to all that answered, in particular I wasn't aware of the existence
of the __del__ function.
For completeness' sake, I think I have found another way to not really solve
but at least circumvent the problem: weak references. If I understand
correctly, those would allow me to pass out handles
Bearophile wrote:
> For example a novice wants to see 124 / 38 to return the 62/19
> fraction and not 3 or 3.263157894736842 :-)
Python has adopted the latter of the three for operator / and the the second
one for operator //. I wonder if it was considered to just return a
fraction from that opera
gganesh wrote:
> I have a dict object like
> emails={'mycontacts': [ 'x...@gmail.com, 'y...@gmail.com',
> 'z...@gmail.com'], 'myname':['gganesh']}
> I need to get the lenght of the list mycontacts ,like
> mycontacts_numbers=3
mycontacts = emails['mycontacts']
mycontacts_number = len(mycontacts)
A
per wrote:
> i am using the standard unittest module to unit test my code. my code
> contains several print statements which i noticed are repressed when i
> call my unit tests using:
>
> if __name__ == '__main__':
> suite = unittest.TestLoader().loadTestsFromTestCase(TestMyCode)
> unittes
Hi!
When would I use PyObject_SetAttrString/tp_dictoffset instead of tp_members?
I have a predefined set of members, some of which are optional. The problem
I had with an embedded dictionary was that I can't see its elements using
"dir()". Now I just converted to using tp_members, and it still
superpollo wrote:
> i can insert a hex value for a character literal in a string:
>
> >>> stuff = "\x45"
> >>> print stuff
> E
> >>>
>
> can i do something like the above, but using a *binary* number? (e.g.
> 00101101 instead of 45) ?
There are binary number literals since 2.6 and there is th
"Martin v. Löwis" wrote:
>> I have a predefined set of members, some of which are optional.
>
> Having optional fields is also a good reason.
What is the use of T_OBJECT_EX vs T_OBJECT in PyMemberDef then? I would
have though that the former describes an optional field, because the
behaviour of
Tom wrote:
> s = sauce.replace("\n", "")
>
> Sauce is a string, read from a file, that I need to remove newlines
> from. This code works fine in Linux, but not in Windows. rstrip("\n")
> won't work for me, so anybody know how to get this working on Windows?
I'm pretty sure this works regardless o
"Martin v. Löwis" wrote:
I have a predefined set of members, some of which are optional.
>>> Having optional fields is also a good reason.
>>
>> What is the use of T_OBJECT_EX vs T_OBJECT in PyMemberDef then?
>
> Right - this works for optional objects. However, it can't possibly
> work for
joy99 wrote:
> [...] it is giving me output like:
> '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95'
These three bytes encode the byte-order marker (BOM, Unicode uFEFF) as
UTF-8, followed by codepoint u09a8 (look it up on unicode.org what that
is).
In any case, if th
...that is the question!
I have a module which exports a type. It also exports a function that
returns instances of that type. Now, the reason for my question is that
while users will directly use instances of the type, they will not create
instances of the type themselves.
So, the type is a part
Jean-Michel Pichavant wrote:
> class Color:
> def __init__(self, r, g,b):
> pass
> BLACK = Color(0,0,0)
>
> It make sens from a design point of view to put BLACK in the Color
> namespace. But I don't think it's possible with python.
class Color:
...
setattrib(Color, "BLACK"
Ulrich Eckhardt wrote:
> Jean-Michel Pichavant wrote:
>> class Color:
>> def __init__(self, r, g,b):
>> pass
>> BLACK = Color(0,0,0)
>>
>> It make sens from a design point of view to put BLACK in the Color
>> namespace. But I don&
kj wrote:
> class Demo(object):
> def fact_iter(n):
> ret = 1
> for i in range(1, n + 1):
> ret *= i
> return ret
>
> def fact_rec(n):
> if n < 2:
> return 1
> else:
> return n * fact_rec(n - 1)
>
> classvar1
Nigel Rantor wrote:
> John Nagle wrote:
>> Immutability is interesting for threaded programs, because
>> immutable objects can be shared without risk. Consider a programming
>> model where objects shared between threads must be either immutable or
>> "synchronized" in the sense that Java uses
ganesh wrote:
>> Did you remeber to acquire the GIL? The GIL is global to the process
>
> No, I did not use GIL.
>
> -- Why do we need to use GIL even though python is private to each
> thread?
Quoting from above: "The GIL is global to the process". So no, it is NOT
private to each thread which
Kermit Mei wrote:
> #!/usr/bin/env
> python
>
> class Test:
> 'My Test class'
> def __init__(self):
> self.arg1 = 1
>
> def first(self):
> return self.arg1
>
> t1 = Test
't1' is now an alternative name for 'Test'. What you wanted instead was to
instantiate 'Test', wh
Hi!
"'abc'.split('')" gives me a "ValueError: empty separator".
However, "''.join(['a', 'b', 'c'])" gives me "'abc'".
Why this asymmetry? I was under the impression that the two would be
complementary.
Uli
--
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
-
Hi!
Take a look at:
http://vis.cs.ucdavis.edu/~ogawa/codeswarm/
code_swarm is a tool that generates a nice visual animation from a
repository history. It also features one with the Python history for
download, enhanced with a few comments.
I hope this isn't old news and you enjoy it!
Uli
--
daved170 wrote:
> I need help with exceptions raising.
> My goal is to print at the outer functions all the errors including
> the most inner one.
>
> For example:
>
> def foo1(self):
>try:
> foo2()
>except ? :
> print "outer Err at foo1" + ??
>
> def foo2(self):
>tr
Steven D'Aprano wrote:
[reading Bengali]
> In Python 2, you probably need to do this:
>
> f = open("filename")
> bytes = f.read()
> text = bytes.decode('which-encoding-you-use')
> f.close()
In Python 2, I'd rather take a look at the "codecs" module (see
http://docs.python.org), namely the "codecs
Tim Wintle wrote:
> [..] under the hood, cpython does something like this (in psudo-code)
>
> itterator = xrange(imax)
> while 1:
> next_attribute = itterator.next
> try:
> i = next_attribute()
> except:
> break
> a = a + 10
There is one thing that strikes me here: The code claims
Joakim Hove wrote:
> I have used ctypes to wrap a C-library
> [...]
> Observe that the c_container_get_node() function does _not_ allocate
> memory, it just returns a opaque handle to a node structure, still
> fully owned by the container structure.
[...]
>
> class Container:
> def __init__(
sajuptpm wrote:
> I need to change position of each values in the list and that dont
> affect fuctions which are using this list.
So you want to change the list's content but you don't want anyone to be
able to detect the difference? That doesn't make sense.
> I must have to use list of tuples.
>
Ian Hobson wrote:
> sys.stdout = sys.stderr = open("d:\logfile.txt", "a")
"\l" is probably not what you want. Consider using "\\l" or r"\l" instead.
Uli
--
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
--
http://mail.python.org/mailman/listinfo/python
sajuptpm wrote:
> I have a list of tuples l = [((cpu_util,mem_util),(disk_util)),
> ((cpu_util,mem_util),(disk_util))]
> ie, l = [((30,50),(70)), ((50,20),(20))]
>
> l.sort(key=lambda x:(-x[0][0], x[1][0]))
> # sorting cpu_util asc and disk_util desc
One thing here: Without knowing what special m
sajuptpm wrote:
> i want to find the loaded machine based on cpu and mem and desk
> utilization by changing this order.
>
> I created a UI using that i can change the order of item in the tuple.
> But the problem is asc and desc sorting
How about only changing the order in which the elements are
BartC wrote:
> So 'range' is just a class like any other. And that a class is something
> you can blithely copy from one variable to another. And whenever you see
> 'range' anywhere, you can't always be certain that someone hasn't done:
>
> range = 42
>
> at some point.
True. I read an explanati
Raymond Hettinger wrote:
> collections.deque('abcde').__getitem__[-2] # extension class, magic
> method
Small nit: You don't mean [square] brackets here, right?
Otherwise, good posting, thank you!
Uli
--
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
--
h
Stef Mientki wrote:
> When running this python application from the command line ( or launched
> from another Python program), the wrong character encoding (probably
> windows-1252) is used.
Rule #1: If you know the correct encoding, set it yourself. This
particularly applies to files you open you
Steven D'Aprano wrote:
> I want the mantissa and decimal exponent of a float, in base 10:
>
> mantissa and exponent of 1.2345e7
> => (1.2345, 7)
>
> (0.12345, 8) would also be acceptable.
[...]
> Have I missed a built-in or math function somewhere?
The integral, decimal exponent is just the floo
Hello!
I'm currently working on a testsuite using Python's unittest library. This
works all good and fine, but there's one thing where I haven't seen an
elegant solution to yet, and that is the ordering. Currently, it takes all
classes and orders them alphabetically and then takes all test functio
John Machin wrote:
> |>>> '\x80'.decode('cp936')
> Traceback (most recent call last):
> File "", line 1, in
> UnicodeDecodeError: 'gbk' codec can't decode byte 0x80
> in position 0: incomplete multibyte sequence
[...]
> So Microsoft appears to think that
> cp936 includes the euro,
> and the ICU
gb345 wrote:
> I have a handy Python script, which takes a few command-line
> arguments, and accepts a few options. [...]
> I want to adapt my script, with the minimum amount of
> work, so that it can have a double-clickable icon that brings up
> a small GUI to accept command-line options (includin
Geobird wrote:
> I am a beginner in Python and would ask for a help.
>
>
> I was searching for smaller version of code to calculate
> factorial . Found this one
> def fact(x):
> return x > 1 and x * fact(x - 1) or 1
I'd say this is about as small as it gets.
> But I don't really ge
Yingjie Lan wrote:
> I would like to have comments after the line continuation backslash.
>
if a > 0 \ #comments for this condition
> and b > 0:
> #do something here
Historically, and also in Python, the backslash escapes the immediately
following character. That means that _nothin
Roy Smith wrote:
> I'm writing a test suite for a web application. There is a subclass of
> TestCase for each basic page type.
[...]
> class CommonTestCase(unittest.TestCase):
>def test_copyright(self):
> self.assert_(find copyright notice in DOM tree)
>
> class HomepageTestCase(Common
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
On 21.01.10 12:18, anusha k wrote:
> Hi,
>
> Can anyone tell me how to convert number to words
> For example:
> If number = then it should give me *Nine thousand nine hundred
> ninetynine*
> Is there any build-in function or something that can do
unctions to different
instances of MyClass. It is in the context of a database app where I build
Getters for database data and pass one Getter per instance.
Thanks for hints
Ulrich
--
Ulrich Goebel
--
https://mail.python.org/mailman/listinfo/python-list
) doesn't allow to pip install required packages
system wide, so I have to use virtual environments even there. But is it right,
that I have to do that for every single user?
Can someone give me a hint to find an howto for that?
Best regards
Ulrich
--
Ulrich Goebel
--
https://mail.pytho
problem which I can't handle is to handle the Frame which
seems to be needed to place the Scrollbar somewhere.
Best regards
Ulrich
--
Ulrich Goebel
--
https://mail.python.org/mailman/listinfo/python-list
? I'm not a
friend of things so deep in the system...
Greetings
Ulrich
--
Ulrich Goebel
--
https://mail.python.org/mailman/listinfo/python-list
401 - 489 of 489 matches
Mail list logo