Stian Soiland wrote:
På 14. jan 2005 kl. 22:58 skrev Steven Bethard:
(Any mac users? How do I fix this to appear in Norwegian? =)
Note that if you're not comfortable with short-circuiting behavior,
you can also code this using lazy evaluation:
(lambda: 1/x, lambda: 1.0e99)[x==0]()
.
Craig Howard wrote:
I am working on a python project where an object will have a script that
can be edited by the end user: object.script
If the script is a simple one with no functions, I can easily execute it
using:
exec object.script
But if the object script is a bit more complicated, su
Xah Lee wrote:
© Note: this post is from the Perl-Python
© a-day mailing list at
© http://groups.yahoo.com/group/perl-python/
Is there any chance you could post these all as part of the same thread?
That would be really nice for those of us who aren't interested --
then we could just ignore the
I completely agree. I'm also waiting for an advanced Python/project
management book that helps folks out with large-scale projects.
And, for the 2nd edition, may I suggest:
- coverage of OptionParser module, which is more advanced than the
getopt module that you discuss on page 141.
- better Mac O
Paul Simmonds wrote:
I would assume that they're refering to the fact that even the basic
data types such as int are derived from object, and hence have methods:
int.__class__.__base__
Java, for example, has both an Integer object and a basic int data
type. One word. Yuck.
Heh heh. Yeah, I can re
Antoon Pardon wrote:
In this case for example there are a number of people who flat out
assert that muatble dict keys in pyhthon is impossible.
If you run into any of these folks, please point them to:
http://www.python.org/moin/DictionaryKeys
It's a pretty good summary of one of the more recent th
Bengt Richter wrote:
Which make me wonder what plans there are for providing a better
mechanism than default arguments as a way of initializing local function
variables. Nested def's to create a closure with initialized values is
pretty crufty for that, IMO.
What about using a class? Associating f
Bengt Richter wrote:
On Tue, 18 Jan 2005 17:38:20 -0700, Steven Bethard <[EMAIL PROTECTED]> wrote:
Bengt Richter wrote:
Which make me wonder what plans there are for providing a better
mechanism than default arguments as a way of initializing local function
variables. Nested def's
Stephen Thorne wrote:
On Tue, 18 Jan 2005 23:09:57 -0700, Steven Bethard
<[EMAIL PROTECTED]> wrote:
@with_consts(i=1, deftime=time.ctime())
def foo(x, y=123, *args, **kw):
return x*y, kw.get('which_time')=='now' and time.ctime() or deftime
Then you don't have to
David Eppstein wrote:
In article <[EMAIL PROTECTED]>,
Nick Coghlan <[EMAIL PROTECTED]> wrote:
For a 'mutable key' to make sense, the following:
lst = []
dct = {l: "Hi!"}
print dct[[]]
print dct[lst]
lst.append(1)
print dct[[1]]
print dct[lst]
Should print:
Hi
Hi
Hi
Hi
Yes, and what should the fo
Nick Coghlan wrote:
For a 'mutable key' to make sense, the following:
lst = []
dct = {l: "Hi!"}
print dct[[]]
print dct[lst]
lst.append(1)
print dct[[1]]
print dct[lst]
Should print:
Hi
Hi
Hi
Hi
And here's an implementation that does so:
py> class sillydict(dict):
... def __getitem__(self, key)
Bill Mill wrote:
2 solutions:
In [98]: bars = ["str", "foobaz", "barbaz", "foobar"]
In [99]: for bar in bars:
: if 'bar' in bar and 'baz' in bar:
: print bar
: print bars.index(bar)
:
barbaz
2
In [100]: for i in range(len(bars)):
.: if 'bar
On Thu, 20 Jan 2005 18:21:17 -0500, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
>
> Instead of a __getattr__ solution, I recommend subclassing from a mixin:
>
> class RichMap(SomePartialMapping, UserDict.DictMixin): pass
>
> class RichFile(SomePartialFileClass, Mixins.FileMixin): pass
Yun Mao wrote:
Hi python gurus,
I have some questions when I'm using python numeric:
1. When I do v = u[:, :], it seems u and v still point to the same
memory. e.g. When I do v[1,1]=0, u[1,1] will be zero out as well.
What's the right way to duplicate an array? Now I have to do v =
dot(u, identi
Stephen Thorne wrote:
On Fri, 21 Jan 2005 01:54:34 GMT, Kartic
<[EMAIL PROTECTED]> wrote:
Aha..I guess I posted too soon.
You might want to take a look at this cookbook entry:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300
Defines lambdas to convert integer to binary. The one you pr
Johnny Lin wrote:
my understanding about locals() from the nutshell book was that i
should treat that dictionary as read-only. is it safe to use it to
delete entries?
No it's not:
py> def f():
... x = 1
... del locals()['x']
... print x
...
py> f()
1
py> def f():
... x = 1
...
py> import numarray as na
py> a = na.array([[1,2,3],[4,5,6]])
Yun Mao wrote:
Thanks for the help. numarray doesn't provide what I look for either. e.g.
a = array( [[1,2,3],[4,5,6]] )
I sometimes what this: a[ [1,0], :],
py> a[[1,0]]
array([[4, 5, 6],
[1, 2, 3]])
or even a[ [1,0], [0,1] ]
Paul McGuire wrote:
expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen]
Or if you're afraid of lambda like me:
def expand(lst,default,minlen):return (lst + [default]*minlen)[0:minlen]
or perhaps more readably:
def expand(lst, default, minlen):
return (lst + [default]*minlen)
Alex Martelli wrote:
Nevertheless, any modifications to locals() are utterly
futile (within a function).
Evil hack that makes modifications to locals() not quite as futile:
py> import sys
py> import ctypes
py> def f():
... x = 1
... locals()['x'] = 2
... ctypes.pythonapi.PyFrame_LocalsT
André wrote:
Given the statement
a = public_class()
I would like to generate
my_dict['a'] = private_class()
so that one could write
a.apparently_simple_method()
and that, behind the scene, I could translate that as
my_dict['a'].not_so_simple_method()
as well as do things like
for name in my_dict:
I wrote:
> If you really want locals that don't contribute to arguments, I'd be
> much happier with something like a decorator, e.g.[1]:
>
> @with_consts(i=1, deftime=time.ctime())
> def foo(x, y=123, *args, **kw):
>return x*y, kw.get('which_time')=='now' and time.ctime() or deftime
>
> Then yo
André wrote:
Using the method suggested by Steven Bethard, I *almost* got it working
the way I would like.
Here's my program:
===
.class PrivateClass(object):
.dict = {}
.def not_so_simple_method(self):
.for name in PrivateClass.dict.keys():
.if PrivateClass.dict
Andrà Roberge wrote:
Behind the scene, I have something like:
robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') }
and have mapped move() to correspond to
robot_dict['robot'].move()
(which does lots of stuff behind the scene.)
I have tested robot_dict[] with more than one robot (each with
i
André wrote:
Steven Bethard wrote:
André wrote:
Using the method suggested by Steven Bethard, I *almost* got it
working
the way I would like.
[snip]
It looks like you want PrivateClass.dict updated every time that
globals() is updated.
yes, that is what I would like to do.
You can just use
Andrà Roberge wrote:
Behind the scene, I have something like:
robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') }
and have mapped move() to correspond to
robot_dict['robot'].move()
(which does lots of stuff behind the scene.)
I have tested robot_dict[] with more than one robot (each with
i
Nick Coghlan wrote:
Steven Bethard wrote:
I wrote:
> If you really want locals that don't contribute to arguments, I'd be
> much happier with something like a decorator, e.g.[1]:
>
> @with_consts(i=1, deftime=time.ctime())
> def foo(x, y=123, *args, **kw):
>re
Bengt Richter wrote:
On Sat, 22 Jan 2005 16:22:33 +1000, Nick Coghlan <[EMAIL PROTECTED]> wrote:
Steven Bethard wrote:
I wrote:
> If you really want locals that don't contribute to arguments, I'd be
> much happier with something like a decorator, e.g.[1]:
>
> @with_co
Michael Tobis wrote:
I have a similar problem. Here's what I do:
.def new_robot_named(name,indict=globals()):
. execstr = name + " = robot('" + name + "')"
. exec(execstr,indict)
.class robot(object):
. def __init__(self,name):
. self.name = name
. def sayhi(self):
. print "Hi! I
Nick Coghlan wrote:
It also directly addresses the question of aliasing. Think about how
Steven's modified dictionary would react to this code:
pete = CreateRobot(2, 3)
dad = pete
dad.move()
pete.move()
If you'd like to handle these cases, but you don't want to have to
explain aliasing right off
Frans Englich wrote:
The reason I thinks about this is I need to implement a debug print for my
program; very simple, a function/print statement that conditionally prints
its message whether a bool is true. Not overly complex.
Sounds like you want to override sys.stdout:
py> class ConditionalWrit
Bengt Richter wrote:
So, e.g., for
>>> presets = dict(a=1, b=2, deftime=__import__('time').ctime())
in the decorator args, the next version will act as if the decorated
function had the source code
>>> print '%s = __frompresets__' % ', '.join(sorted(presets))
a, b, deftime = __frompresets__
for
Alex Martelli wrote:
class ReWithMemory(object):
def search(self, are, aline):
self.mo = re.search(are, aline)
return self.mo
def group(self, n):
return self.mo.group(n)
m = ReWithMemory()
if m.search(r'add (\d+) (\d+)', line):
do_add(m.group(1), m.group(2))
elif
Philippe C. Martin wrote:
> class Debug_Stderr:
> __m_text = ''
> __m_log_text = None
> __m_dbg = None
> __m_refresh_count = 0
I don't see the benefit in 99.9% of cases for making class variables
like this "private". If you don't want people to use them, simply use
the standard conventi
Fredrik Lundh wrote:
George Sakkis wrote:
Why does slicing a tuple returns a new tuple instead of a view of the existing
one, given that
tuples are immutable ?
really?
a = 1, 2, 3
b = a[:]
a is b
True
My impression was that full tuple copies didn't actually copy, but that
slicing a subset of a t
Fredrik Lundh wrote:
Steven Bethard wrote:
My impression was that full tuple copies didn't actually copy, but that slicing a subset of a
tuple might. Not exactly sure how to test this, but:
py> a = 1, 2, 3
py> a[:2] is a[:2]
False
yup. and to figure out why things are done this wa
given me a PEP number for it yet, but a patch is available[1] and I've
included the current draft of the PEP below.
[1]http://sourceforge.net/tracker/?func=detail&atid=305470&aid=1094542&group_id=5470
Steve
------
PEP: XXX
Title: G
Philippe C. Martin wrote:
I used double underscore because I thought it was the correct way to name
private variables/methods - I will have to change those to single
underscore since that it the current methodology.
A private variable to me:
1) is internal to the processing of a class and needs not
Nick Craig-Wood wrote:
Thinking about this some more leads me to believe a general purpose
imerge taking any number of arguments will look neater, eg
def imerge(*generators):
values = [ g.next() for g in generators ]
while True:
x = min(values)
yield x
for i in range
Nick Craig-Wood wrote:
Steven Bethard <[EMAIL PROTECTED]> wrote:
Nick Craig-Wood wrote:
Thinking about this some more leads me to believe a general purpose
imerge taking any number of arguments will look neater, eg
def imerge(*generators):
values = [ g.next() for g in generators ]
whil
Bengt Richter wrote:
On Mon, 24 Jan 2005 20:35:09 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote:
from presets import presets, curry
@presets(verbose=True, a=1, b=2, deftime=__import__('time').ctime())
... def foo():
...print (a, b)
...print deftime
...
presets: -- "name(?)" means name may be
Toby Dickenson wrote:
I have a counterexample. Consider refactoring a class from
class B(A):
etc
into
class C(A):
etc
class B(C):
etc
Usage of some double-undescore attributes moved from B to the new intermediate
base class C. Unit tests on B still passed, so that change is
Fuzzyman wrote:
> Cameron Laird wrote:
> [snip..]
>
>>This is a serious issue.
>>
>>It's also one that brings Tcl, mentioned several
>>times in this thread, back into focus. Tcl presents
>>the notion of "safe interpreter", that is, a sub-
>>ordinate virtual machine which can interpret only
>>speci
Swaroop C H wrote:
On Tue, 25 Jan 2005 12:38:13 -0700, Brent W. Hughes
<[EMAIL PROTECTED]> wrote:
I'd like to get a character from stdin, perform some action, get another
character, etc. If I just use stdin.read(1), it waits until I finish typing
a whole line before I can get the first character.
Michael Spencer wrote:
Safe eval recipe posted to cookbook:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469
This recipe only evaluates constant expressions:
"Description:
Evaluate constant expressions, including list, dict and tuple using the
abstract syntax tree created by compiler
Michael Spencer wrote:
Steven Bethard wrote:
Michael Spencer wrote:
Safe eval recipe posted to cookbook:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469
This recipe only evaluates constant expressions
[snip
Indeed. But it's easy to extend this to arbitrary constructs. You
Davor wrote:
Is it possible to write purely procedural code in Python, or the OO
constructs in both language and supporting libraries have got so
embedded that it's impossible to avoid them?
Hmmm... sorta depends on how you define write procedural code... If
you mean, can you write Python code w
Mike Moum wrote:
s.atoi('4',3)
Traceback (most recent call last):
File "", line 1, in -toplevel-
s.atoi('4',3)
File "/usr/lib/python2.3/string.py", line 220, in atoi
return _int(s, base)
ValueError: invalid literal for int(): 4
What did you expect the value of '4' in base 3 to be? Ther
Jose Rivera wrote:
I installed the new release and I have not been able to make work metakit.
Please give me some help to enjoy metakit and python 24.
Repeating your request every 10 minutes is not likely to get you help
quicker. On the contrary, it's more likely to make people ignore your
threa
Thomas Guettler wrote:
Am Wed, 26 Jan 2005 15:55:28 + schrieb Judi Keplar:
I am currently taking a course to learn Python and was looking for
some help. I need to write a Python statement to print a comma-
separated repetition of the word, "Spam", written 511 times ("Spam,
Spam, ï Spam").
Jack Diederich wrote:
Yes, this comes up every couple months and there is only one answer:
This is the job of the OS.
Java largely succeeds at doing sandboxy things because it was written that
way from the ground up (to behave both like a program interpreter and an OS).
Python the language was not
Christian Dieterich wrote:
Hi,
I need to create many instances of a class D that inherits from a class
B. Since the constructor of B is expensive I'd like to execute it only
if it's really unavoidable. Below is an example and two workarounds, but
I feel they are not really good solutions. Does s
Christian Dieterich wrote:
The size attribute only needs to be computed once and stays constant
after that. The lazy property recipe of Scott David Daniels looks
promising. I'll try that, when I've installed Python 2.4. However, I
need my package to work on machines where there is Python 2.2 and
Jack Diederich wrote:
On Wed, Jan 26, 2005 at 10:23:03AM -0700, Steven Bethard wrote:
Jack Diederich wrote:
Yes, this comes up every couple months and there is only one answer:
This is the job of the OS.
Java largely succeeds at doing sandboxy things because it was written that
way from the
[EMAIL PROTECTED] wrote:
Hello, if we want to access the private member of object we use the
classname, it doesn't make sense. For example:
I have class A:
class A:
def __init__(self, i):
self.__i = i;
pass
__i = 0
a = A(22);
b = A(33);
How can I get field i in object a and how can I get field i i
[EMAIL PROTECTED] wrote:
I try to use __methods__ in python 2.4 and 2.2 it always fail.
Can some one tell me if I want to itterate the methods in a class and
print it in a string format ( it is possible using __methods__ ).
Is there any replacement?
py> class C(object):
... a = 1
... b = 2
Nick Vargish wrote:
Here's my Monty Pythonic answer:
## cut here
class Viking():
def __init__():
pass
def order():
return 'Spam'
# this is one viking making one order repeated 511 times. if you want
# 511 vikings making seperate orders, you'll have to write a loop.
v = Vikin
Christian Dieterich wrote:
On Dé Céadaoin, Ean 26, 2005, at 13:45 America/Chicago, Steven Bethard
wrote:
Note that:
@deco
def func(...):
...
is basically just syntactic sugar for:
def func(...):
...
func = deco(func)
Oh, I learned something new today :-) Nice
Francis Girard wrote:
For the imerge function, what we really need to make the formulation clear is
a way to look at the next element of an iteratable without consuming it. Or
else, a way to put back "consumed" elements in the front an iteration flow,
much like the list constructors in FP langua
Stephen Thorne wrote:
f = file('input', 'r')
labels = f.readline() # consume the first line of the file.
Easy Option:
for line in f.readlines():
x, y = line.split()
x = float(x)
y = float(y)
Or, more concisely:
for line in f.readlines():
x, y = map(float, line.split())
Somewhat more memory
Stephen Thorne wrote:
I did all I did in the name of clarity, considering the OP was on his
first day with python. How I would actually write it would be:
inputfile = file('input','r')
inputfile.readline()
data = [map(float, line.split()) for line in inputfile]
Notice how you don't have to call ite
Nick Craig-Wood wrote:
Steven Bethard <[EMAIL PROTECTED]> wrote:
py> orders = [Viking().order()] * 7
py> ', '.join(orders)
'Spam, Spam, Spam, Spam, Spam, Spam, Spam'
Thats still one Viking making 7 orders surely?
So you want this...
orders = [ Viking().order()
Alex Martelli wrote:
Steven Bethard <[EMAIL PROTECTED]> wrote:
...
Beware of mixing iterator methods and readline:
[snip]
I hope this concisely indicates that the problem (in today's current
implementations) is only with switching FROM iteration TO other
approaches to reading, and (
flamesrock wrote:
The statement (1 > None) is false (or any other value above 0). Why is
this?
What code are you executing? I don't get this behavior at all:
py> 100 > None
True
py> 1 > None
True
py> 0 > None
True
py> -1 > None
True
py> -100 > None
True
(The reason I ask is sortof unrelated. I wan
Francis Girard wrote:
Le jeudi 27 Janvier 2005 20:16, Steven Bethard a écrit :
flamesrock wrote:
The statement (1 > None) is false (or any other value above 0). Why is
this?
What code are you executing? I don't get this behavior at all:
py> 100 > None
True
py> 1 > None
True
Francis Girard wrote:
Le jeudi 27 Janvier 2005 21:29, Steven Bethard a écrit :
So None being smaller than anything (except itself) is hard-coded into
Python's compare routine. My suspicion is that even if/when objects of
different types are no longer comparable by default (as has been
sugg
Francis Girard wrote:
I see. There is some rule stating that all the strings are greater than ints
and smaller than lists, etc.
Yes, that rule being to compare objects of different types by their type
names (falling back to the address of the type object if the type names
are the same, I believe
Francis Girard wrote:
a = "10"
b = 10
a > b
True
b > a
False
id(a)
1077467584
id(b)
134536516
Just to thoroughly explain this example, the current CPython
implementation says that numbers are smaller than everything but None.
The reason you get such a small id for 'b' is that there is only one 10
enigma wrote:
Do you really need to use the iter function here? As far as I can
tell, a file object is already an iterator. The file object
documentation says that, "[a] file object is its own iterator, for
example iter(f) returns f (unless f is closed)." It doesn't look like
it makes a differen
John Machin wrote:
To grab the text after the 2nd colon (if indeed there are two or more),
it's much simpler to do this:
import re
q = re.compile(r'.*?:.*?:(.*)').search
def grab(s):
...m = q(s)
...if m:
... print m.group(1)
...else:
... print 'not found!'
...
grab('')
not f
Alex Martelli wrote:
Steven Bethard <[EMAIL PROTECTED]> wrote:
...
If I could see how to go from 'object' (or 'int', 'str', 'file', etc.)
to 'eval' or '__import__', that would help out a lot...
object.__subclasses__()
[, , ,
Michael Tobis wrote:
Anyway, I'd like to dynamically add a method to an instance at
instantiation time. Something like
Nearly identical question from yesterday and a series of answers:
http://mail.python.org/pipermail/python-list/2005-January/263024.html
Steve
--
http://mail.python.org/mailman/list
Pedro Werneck wrote:
If you need direct access to some atribute, use object.__getattribute__.
class DefaultAttr(object):
... def __init__(self, default):
... self.default = default
... def __getattribute__(self, name):
... try:
... value = object.__getattribute_
Kartic wrote:
[EMAIL PROTECTED] said the following on 1/30/2005 7:43 PM:
Hello,
I want to do the following:
def do_load(self, arg):
sitefile = file('sitelist', 'r+', 1)
while True:
siteline = sitefile.readline()
site_rawlist = siteline.split()
sitelist[site_rawlist[0]] = site_rawlist[1:]
if len(sit
Baoqiu Cui wrote:
Today I was playing with a small Python program using Python 2.4
on Cygwin (up-to-date version, on Windows XP), but ran into a
strange error on the following small program (named bug.py):
---
#!/usr/bin/python
class Person:
population = 0
def __del__(se
Fredrik Lundh wrote:
Baoqiu Cui wrote:
The error returned is this:
$ python bug.py
Exception exceptions.AttributeError: "'NoneType' object has no
attribute 'population'" in > ignored
However, if I rename variable name 'peter' to something like 'peter1'
or 'david', the error is gone. Looks to me th
Alex Martelli wrote:
def f(x):
... class C:
... x = x
... return C
...
[snip]
def f(x):
... def g():
... x = x
... return x
... return g
...
[snip]
See the difference? In a function, the 'x = x' compiles into LOAD_FAST,
STORE_FAST, which only looks at locals and nowhere el
Laszlo Zsolt Nagy wrote:
I would like to match strings not beginning with '/webalizer'. How can I
do this?
Are you sure you need a regular expression? The str.startswith method
is what I would normally use to solve this kind of problem:
py> lst = ['aax', 'abx', 'acx', 'aay', 'aby', 'acy']
py> [
[EMAIL PROTECTED] wrote:
I'd like to be able to look up a method name by passing a string with
the method name.
Use getattr:
py> class A(object):
... def f(self):
... pass
... def g(self):
... pass
...
py> class B(A):
... def h(self):
... pass
...
py> getattr(B()
Frans Englich wrote:
But in Python, when one wants to be able to pass different data types into a
single "entry point" for functionality, how is that best done? To in a
function do an if statement with the type() function?
It often depends a lot on the specific use case... Do you have a
partic
Philippe Fremy wrote:
I would like to develop a tool that goes one step further than pychecker
to ensure python program validity. The idea would be to get close to
what people get on ocaml: a static verification of all types of the
program, without any kind of variable declaration. This would de
Nick Coghlan wrote:
I'd definitely recommend hiding this trick inside a function. Perhaps
something like (using Michael's function name):
from itertools import izip, repeat, chain
def partition(seq, part_len):
return izip(*((iter(seq),) * part_len))
def padded_partition(seq, part_len, pad_val=N
kpp9c wrote:
Greetings,
I am working on a program to produce patterns. What would like is for
it to exhaustively produce all possible permutations of a sequence of
items but for each permutation produce variations, and also a sort of
stutter based on probability / weighted randomess.
Let us say we
Terry Reedy wrote:
> Nothing about bytecode is part of the language spec. And CPython
> bytecode is version specific. If the CPython implementation changed
> from a virtual stack machine to a virtual register machine, as was
> once discussed, the stack-oriented byte code would be replaced by a
>
Jay donnell wrote:
in the code below 'print locals()' shows mc2. What is the equivalent
way to see the namespace that mc resides in?
class myClass:
--def func1(self):
self.mc = 1
mc2 = 3
print 'in myClass.func1'
print 'printing locals'
print locals()
print
I think you're loo
Mick Krippendorf wrote:
In Python there seems to be no guarantee that different objects also
have different hash values.
Well, it's true that you can override the __hash__ method to do whatever
you want, but I believe the default for class __hash__ methods is to
return the class id, which should
[EMAIL PROTECTED] wrote:
In a file there can be several dictionaries like this
{Key11: Value11
Key12: Value12
Key13: Value13,
...
...
Key1n:Value1n}
{Key21: Value21
Key22: Value22
Key23: Value23,
...
...
Key2n:Value2n}
{Key31: Value31
Key32: Value32
Key33: Value33,
...
...
Key3n:Value3n}
Caleb Hattingh wrote:
===file: a.py===
# module a.py
test = 'first'
class aclass:
def __init__(self, mod, value):
mod.test = value# Is there another way to refer
to the module this class sits in?
===end: a.py===
You can usually import the current module with:
__import_
M.E.Farmer wrote:
alex wrote:
is it possible to create 'global' variables that can be seen in all
other classes?
What about using a class?
Py> class globalVar:
...pass
Py> globals = globalVar()
Probably naming it something other than 'globals' would be a good idea
-- otherwise you'll hide the
Erik Johnson wrote:
"Erick" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
Ah, you're running into the "old-style classes vs. new style classes".
Try subclassing from "object".
For example:
class A(object):
That works! :) I guess I am fortunate to be running 2.2 - looks kinda ugly
prio
Erick wrote:
Hello,
I've been looking for a while for an answer, but so far I haven't been
able to turn anything up yet. Basically, what I'd like to do is to use
re.finditer to search a large file (or a file stream), but I haven't
figured out how to get finditer to work without loading the entire f
fortepianissimo wrote:
We all know that using __getattr__() we can compute an instance
variable on demand, for example:
class Foo:
def __getattr__ (self, name):
if name == 'bar':
self.bar = 'apple'
return self.bar
else:
raise AttributeError()
Then we can
f = Foo()
s1 = f.bar
s2 = f.bar # this use
Gurpreet Sachdeva wrote:
The purpose is, I pass a list to a class in a module but I want to use
that list out of the scope of that class and that too not in any other
class or a function but in the main program...
The problem is that when I import that, the statements in the module
which are not in
Steve Holden wrote:
M.E.Farmer wrote:
Ok it has been a long day,
In my reply to Steven Bethard , Steve should read Steven ;)
M.E.Farmer
Well, since he signs himself "Steve" too I guess we'll just have to put
up with the ambiguities. Or perhaps, given my (lack of) typing skill,
Just wrote:
In article <[EMAIL PROTECTED]>,
Steven Bethard <[EMAIL PROTECTED]> wrote:
py> class A:
... pass
...
py> class B:
... pass
...
py> a = A()
py> a.__class__ == A
True
py> a.__class__ == B
False
Uh, isinstance(a, A) works for both new-style and old-style
fortepianissimo wrote:
This seems to be what I need. My use case is to do lengthy
intialization as late as possible. In this case this is to initialize
class variables. Does this make sense?
Yup. If they definitely have to be class variables, then yeah, you
probably need to use a metaclass. If y
I wrote:
Alex Martelli wrote:
See the difference? In a function, the 'x = x' compiles into LOAD_FAST,
STORE_FAST, which only looks at locals and nowhere else. In a
classbody, it compiles to LOAD_NAME, STORE_NAME, which looks at locals
AND globals -- but still not at closure cells...
Is there a re
I'm sorry, I assume this has been discussed somewhere already, but I
found only a few hits in Google Groups... If you know where there's a
good summary, please feel free to direct me there.
I have a list[1] of objects from which I need to remove duplicates. I
have to maintain the list order t
Caleb Hattingh wrote:
Peter
Yes, you can even write
f = open("data.txt")
for line in f:
# do stuff with line
f.close()
This has the additional benefit of not slurping in the entire file at
once.
Is there disk access on every iteration? I'm guessing yes? It
shouldn't be an issue in the va
Carl Banks wrote:
from itertools import *
[ x for (x,s) in izip(iterable,repeat(set()))
if (x not in s,s.add(x))[0] ]
Wow, that's evil! Pretty cool, but for the sake of readers of my code,
I think I'll have to opt against it. ;)
STeVe
--
http://mail.python.org/mailman/listinfo/python-list
Marc Huffnagle wrote:
I have a number of variables that I want to modify (a bunch of strings
that I need to convert into ints). Is there an easy way to do that
other than saying:
> a = int(a)
> b = int(b)
> c = int(c)
I tried
> [i = int(i) for i in [a, b, c]]
but that didn't work because it
4301 - 4400 of 15563 matches
Mail list logo