« first day (3342 days earlier)      last day (1598 days later) » 
00:00 - 20:0020:00 - 00:00

wim
12:54 AM
@Dodge thanks! Nothing magical here, it's actually just a plain old stdlib logging call... and the only one in the computer gist.github.com/wimglenn/…
@Dodge No (good) reason for the nested class. Just did it so you get a reference to IntComputer.Halt without needing to import another name separately. I suppose it makes the IntComputer kind of self-contained?
 
What format is better when using if - else statements?
if not something():
   logger.warn("something was false")
else:
    # continue processing....
or:
if something():
    # processing, potentially many lines
else:
    logger.warn("something was false")
?
 
user10984358
1:25 AM
I’d go with having the main event under the if true condition.
 
user10984358
If it’s a empty check for a list then I guess the first one makes sense.
 
@TheNamesAlc bingo
ok thanks
 
wim
note that logger.warn is deprecated
 
@wim ah yes, thanks
 
wim
using it will, ironically, raise warnings
 
1:32 AM
the circle of life is complete
 
 
1 hour later…
3:02 AM
Hello Everyone, i have a running python script which is basically working with multiple excel files and also provides output as dashboards in multiple excel files. Is there any way i can use create a web page to run this script in the backend so that user does not have direct access to the script? The script has multiple options for user input and dialog boxes. Please advise.
 
@RahulMoharir You can try using Flask. But that's getting into web development.
Consider something like Google Forms?
 
@jigglypuff Yes, i tried reading about flask and django, but not sure how helpful it will be in my case. Does Google forms run scripts? i didnt find any relevant references
 
I doubt it can.
What about Jenkins?
 
This Wooey seems helpful. Also found some blogs regarding jenkins. Thanks a lot @jigglypuff. you have been very helpful.
 
@RahulMoharir No worries, any time.
there's also github.com/chriskiehl/Gooey for turning an app to a GUI, which would be much easier than using Wooey
 
3:23 AM
ohhok, will check it out. thanks
 
 
2 hours later…
5:35 AM
cbg guys o/
 
6:05 AM
hi people
 
@GiorgiBeria cbg o/
 
what is cbg?
 
cbg is "salad talk: for "hullo"
 
so i am a Green Bean
?
:d
 
6:09 AM
you are a green bean if you are novice to python as a whole
[I am not a salad person at all btw]
 
i wonder where can i ask some algorithm question not just about python general
 
just ask the python algorithm question if you cant search it up
 
6:27 AM
@RahulMoharir Interested in knowing more. Come back and tell us if you used Wooey/Gooey, and what your experience was.
@cs95 Err well it wasn't, even though it was 7 years old and heavily-trafficked. I changed it so the first line states an actual question, and as concisely as possible: "Is there a pandas built-in way to apply two different aggregating functions f1, f2 to the same column df["returns"], without having to call agg() multiple times?" Rather than the usual antipattern of starting with "My data looks like..." than gradually sprinkling in small bits of question... :)
...should also improve its indexability by search engines.
 
7:08 AM
@smci sure, will do
 
7:51 AM
@wim no, just another solution I hadn't considered
@Aran-Fey that's one of those things that I've read somewhere already for sure, but couldn't connect to something tangible as of yet. thanks for the info!
 
cbg
oh, the riddle page is not editable.
could someone with write access be so kind and post this there? gist.github.com/a-recknagel/2a01466199470ba61874f76e0fa4ea8b
 
just realized I don't have editing permissions on this account :/
 
welcome to plebeianship
 
user10984358
if I am inheriting a method foo from ClassA is there a need to document foo in ClassB? I was told to create a method in classB and do super().foo() just so I can document it there
 
8:07 AM
No, just document it in ClassA
if child classes had to duplicate all inherited methods, what even would the point of inheritance be?
 
user10984358
that is what I did, but they said you know its inherited, the guy who comes after you will not get it
 
99% of the time, nobody should care if it's inherited or defined directly in that class. That only starts mattering if you get into multiple inheritance
And even if it matters, you should find a tool that auto-generates that kind of documentation for you instead of doing it manually
 
user10984358
@Aran-Fey I will use this as my counter point, also I will be using sphinx
 
I'm not sure if sphinx documents that kind of thing per default, but I'm sure there's a monkeypatch (in lieu of a config setting) that makes it do it...
 
user10984358
will look into that, thanks!
 
8:12 AM
it doesn't by default
which is good, because it would be superfluous in most cases
documentation should be kept minimal, if it becomes too much trouble to maintain it (and duplication would be troublesome for sure) then it will get out of date. and bad documentation is worse than no documentation
and here is a post outlining what Aran described.
 
not getattr(member, '__doc__'), getattr(bases[-1], name).__doc__, i.imgflip.com/1jmzdm.jpg
that's a weird way of writing member.__doc__... and they're only searching the last base class for a matching function, really?
 
user10984358
never used metaclasses before, but if it does what I want, or at least what I am asked to, then yay for me
 
8:28 AM
all it does is copy docstrings from the parent class if you override a method in a subclass and don't document it
so there's a decent chance you'll end up with a method that has an incorrect docstring, because if the subclass method did the same thing as the parent method then you probably wouldn't have overridden it
well, maybe not so much incorrect as incomplete
 
@Aran-Fey seems I linked a bad answer
hmm, I'll try to improve it if I get the time today
 
@Aran-Fey base[-1] will already have received the docstrings from its own base[-1] and so on
 
but what about multiple inheritance
 
@Aran-Fey erm, if you follow LSP then an overriden method should appear to do the same thing as the original
@Aran-Fey hm, true. Also any subclass that does not override a method breaks the chain to its own subclasses.
 
@MisterMiyagi yeah, true. But even if you follow LSP you should probably explicitly document your methods instead of blindly copying the parent's docs. It has its uses, but it's not something that should blindly be used 100% of the time, is what I'm trying to say
I can't be arsed to properly test this, but something along these lines should work better than the code in that answer:
class SuperclassMeta(type):
    def __init__(cls, *args, **kwargs):
        for name, member in vars(cls).items():
            if not hasattr(member, '__doc__') or member.__doc__:
                continue

            for base_cls in cls.mro():
                if name not in vars(base_cls):
                    continue

                doc = vars(base_cls)[name].__doc__
                if not doc:
                    continue

                member.__doc__ = doc
                break  # forgot this, oops
People never seem to implement __init__ in their metaclasses for some reason
 
8:41 AM
yeah, because overriding __init__ breaks the "ignore __init__" magic :P
this looks like a good job for __init_subclass__ and class decorators as well, by the way
 
true, a decorator would be a better solution for that. Avoids the risk of possible metaclass conflicts with abc.ABCMeta or whatever
 
what would be the text form here? class PropagateDoc(type) and "a class with this class as its metaclass will copy-paste parent docstrings into inherited (including overriden) methods"
 
though you only need to set the metaclass once, whereas a decorator has to be applied to every single subclass as well
 
true, it's why I like metaclasses. It fits the idea of self-contained entities better. Decorators are much easier for maintenance, sadly. :/
 
it's a shame metaclasses can't choose to be automatically merged with other metaclasses (instead of throwing a metaclass conflict error)
@Arne text form? Not sure what you mean
 
8:49 AM
a natural language description, as opposed to self-documenting code
 
Still not entirely sure I understand the question, but I'm fairly confident I don't know the answer :D
 
as for something concrete that I don't understand, what does the initial not hasattr(member, '__doc__') condition achieve?
 
...nothing, actually. I thought it was necessary to not crash with an AttributeError when a class has a non-function attribute like foo = 5, but in that case foo.__doc__ just gives you the int docstring
 
I'm decently sure it should be negated, i.e. if hasattr(member, '__doc__', None):
 
@MisterMiyagi __doc__ is automagically set to None anyway, so that's just a verbose way of writing if member.__doc__:
 
8:59 AM
is there a way to ask an object if it's a method?
 
Depends on what exactly you mean by "method" ;)
A bound method, or a function, or a function defined in a class, or something else?
 
bound methods, yes
unbound, no
@Aran-Fey the more I look at it, the more I realise what a brainfart I wrote there ^^
dons the hat of shame
 
ha, I didn't even notice you wrote hasattr
monkey see \w{3}attr(<argument>{3}), monkey think getattr
Ha, what nobody realized is that the metaclass crashes if the class has no docstring
class Superclass(object, metaclass=SuperclassMeta):
    pass
# AttributeError: 'NoneType' object attribute '__doc__' is read-only
(because it tries to set Superclass.__doc__.__doc__ = None)
So... what's the correct way to figure out if an object has a (writable) __doc__? isinstance(obj, (types.FunctionType, type))?
 
try: except AttributeError: ;)
 
...I guess
 
9:14 AM
@Aran-Fey did you include type to inherit the class docstring?
 
tbh I'm not very comfortable with relying on some_instance.__doc__ falling through to the class's doc, so if possible I would prefer an explicit "does this thing have a docstring" check rather than a try
 
the try is for writing the docstring, not for fetching it
 
@Arne It's to support arbitrary (non-function) callables. Say my_method = functools.partial(print, 3) or whatever
@MisterMiyagi Right, but I don't want to rely on some_instance.__doc__ not throwing an AttributeError.
 
>>> isinstance(dict, type)
True
>>> dict.__doc__ = 'foobar'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'dict'
 
...I guess I could wrap that in a try as well
 
9:19 AM
as for reading, if getattr(thing, '__doc__', None) should do the trick
 
Also, I just realized that the code doesn't handle methods hidden behind descriptors (classmethod, staticmethod).
 
tips his hat of shame
hm, you might just want to use functools.wraps or its underlying helpers
 
How did I get tricked into cleaning up SO again, anyway?
I should be eating breakfast
 
@Aran-Fey thanks for the help, enjoy your breakfast =) .. it was probably because I mentioned your name while pasting the link
 
I probably haven't worked on my own projects enough lately... so all that unused programming energy went into this instead (:
 
10:27 AM
just in case you're still interested, I tried turning your metaclass draft into a decorator and tested it a little gist.github.com/a-recknagel/de864922bd4183cf523a2463a2da5f3d
 
Hmm, comparing code objects of functions and the whole overload thing in general seem a bit weird. Why would anyone override a method with the exact same implementation? And then, why wouldn't they want to docstring to be copied, since it does exactly the same thing anyway?
 
recbg
 
10:55 AM
Hi, ai m trying to read numbers from file, looking like this:

```
_ _ _ _ _ _
|_ | || | ||_| _| ||_ |_
|_||_||_| | | _| | _| _|

_ _ _ _ _ _
|_ |_ | ||_|| ||_||_||_ |_|
|_| _||_| ||_||_| | _| |

_ _ _ _ _ _ _ _
_||_| || ||_ || | _| |
_||_| ||_| _| ||_||_ |

```
How I can identify those in Python?
 
11:30 AM
@Aran-Fey I probably just have the wrong idea about how inheritance works. Going back to the drawing board.
 
It's not like it's a problem, it's just... not really a useful feature either
In what situation would @inherit_docstrings(overload=False) do something useful?
 
@arshpreet I can't even read them manually. Did you forget code formatting?
 
11:57 AM
@MisterMiyagi My question is like this(stackoverflow.com/questions/43054107/…) but in Python only, is there any other smart way to do that in Python?
 
looks like you just need to slice the lines to 3x3 blocks. [line[c:c+3] for line in text[n:n+3]] gives you the number at number-line n, position c.
if you define a dict of 3x3 literals to their number, e.g. {('_ _', '|_ ', '|_|'): 6}, you can directly look up each digit
 
12:22 PM
@Aran-Fey sorry for the spotty connection, work is keeping me busy today. the use case was that if the parent class includes implementation details in the docstring that should not be communicated to children. now that I think about it, yeah, if you'd overload such a method you should absolutely just document it yourself, in which case you wouldn't need the option.
and even if there was some need for such a parameter, it should be configurable per-method, and not for the whole class. In which case, again, you might as well just write your own docstring. Oh well, another learning experience.
 
Yeah, that ^ is what I was thinking, too. If you want to turn it off for the whole class, you just... don't decorate the class in the first place
 
1:02 PM
Cbg
 
1:22 PM
cbg
 
Math Q: Are 0 and 1 coprime?
 
yes
link The numbers 1 and −1 are the only integers coprime to every integer, and they are the only integers that are coprime with 0.
 
1:37 PM
Ok, thanks
 
@arshpreet I agree with Mister Miyagi's suggestion. FWIW, here's a 7 segment clock: chat.stackoverflow.com/transcript/6?m=44155599#44155599
@Kevin What Paritosh said. n & n+1 are always coprime. More generally, any common divisor of n & n+k must divide k.
@AndrasDeak Gone
 
1:52 PM
i did it. i have officially downloaded keypass now!
let me just store the keypass master password as the database file name, and we're good to go. right? giggles to self like a happy schoolkid
 
@PM2Ring You are great Old Friend!!
 
@arshpreet Thanks. :)
 
2:20 PM
Boy I sure hope math.atan2(x, 0) == math.pi/2 for all positive integer values of x
 
at least up to 20000000 - 1
 
I should think the positive real values of x should also give this
 
I think therefore I am.
 
Although I get math.tau/4
 
Oh there actually is a math.tau
IIRC Euler introduced both pi and tau.
What a legend.
 
2:34 PM
I'm trying to find any text hold the word of "area". but I'm not big fan of regex .
soup.findAll(text=re.compile('*area'))
 
@Dair everyone can make mistakes
 
@AndrasDeak I was thinking about that Daniel vs the Cooler Daniel meme, but it's just euler.
 
@αԋɱҽԃαмєяιcαη The regular expression pattern that matches the exact text "area" is: "area"
 
the text can be

right area
left area
 
>>> import re
>>> pattern = re.compile("area")
>>> pattern.search("right area")
<re.Match object; span=(6, 10), match='area'>
>>> pattern.search("left area")
<re.Match object; span=(5, 9), match='area'>
>>> pattern.search("foobar")
>>>
works on my machine
 
2:40 PM
@αԋɱҽԃαмєяιcαη *area is not valid regex, it's a wildcard. Regex for "anything or nothing" is roughly .*
 
@AndrasDeak There's a whole thread dedicated to mistakes Euler made lol.
 
thanks @Kevin @AndrasDeak
 
@Kevin Might want to use "\barea\b" to avoid false hits of 'area' nested within a larger word.
 
"area$" got the correct result for me.
 
You just got lucky that none of your text values ended with "marea" or "o'harea"
 
2:53 PM
cbg
 
In fact, using findall and search, you wouldn't necessarily know that you matched "area" at the end of a larger word, since the re.span and .match will just show the matching "area" characters.
 
@PaulMcG yes all text ending with "area"
got it.
thanks for clarification
 
I'm looking for a way to reference the local mixin class name when mixed in to a composed class. self.__class__.__name__ gives the name of the composed class, not the local mixin class.
Currently doing this, but PyCharm inspection complains about the reference to the undefined attribute.
for cls in MixinsBaseClass.__subclasses__():
    # access within Mixin class body using "self.__localname"
    setattr(cls, "_{}__localname".format(cls.__name__), cls.__name__)
(Still haven't switched over to these newfangled f-strings. They just feel so Javascripty. Or Tclish even.)
 
3:10 PM
cbg
 
@PaulMcG Kinda hard to follow what's being mixed in and what's being composed and whatnot. Could we see an example?
 
@PaulMcG heaven forbid even PHP'ish :)
 
class Base: pass

class Mixin0(Base):
    # __localname = "Mixin0"
    def method0(self):
        return type(self).__localname

class MixinA(Base):
    # __localname = "MixinA"
    def method1(self):
        return self.__localname
 
@αԋɱҽԃαмєяιcαη If you don't care about whether "area" is embedded within a longer word, then you don't necessarily even need regex: soup.find_all(text = lambda x: x.endswith("area"))
 
In my case, I use self.__localname for class-specific logging. If I had a MixinB that also implemented method1, then I could have symmetric logging logic that just references self.__localname
Just trying to keep this short for chat
Oops, left out the actual class creation
def make_class(*classes):
    class_name = '_'.join(cls.__name__ for cls in classes)
    return type(class_name, classes, {})
DynamicClass = make_class(Mixin0, MixinA, Base)
Or AnotherDynamicClass = make_class(Mixin0, MixinB, Base)
 
3:17 PM
@Kevin or possibly .findall(text=re.compile(r'.*\barea$')
(the .* might not be necessary - can't remember if it calls .match or .search on the regex object)
 
@PaulMcG Hmm, I'm still not entirely sure what exactly you're trying to do, but it seems like a loop similar to the one you already have is unavoidable. Maybe you could silence PyCharm by turning the logic around: Loop over type(self).mro() and skip classes that don't inherit from MixinsBaseClass
 
@Kevin ta :)
 
Using the setattr code, I can avoid the commented-out __localname statements (which also offend my DRY sensibilities)
 
Alternative solution: I don't know about this specific case, but I've found that fairly often the best solution is actually to ignore/disable the pesky inspection
 
3:25 PM
@Aran-Fey Yes, I'm already doing this a lot. Invoke the I'm-the-human-I-know-what-I'm-doing inspection hammer.
 
@PaulMcG have you tried type-hinting the classes to PyCharm? Often enough, it's type inference that fails, not attribute discovery.
typing.Protocol also has been surprisingly pleasant, considering how unpleasant typing generally is with meta-programming.
 
I will look more at the typing module, thanks
 
fyi, Protocol is 3.8, and needs the backport in typing-extensions for lower versions
 
3:42 PM
oh, true. I keep forgetting some of the merely-semi-ugly nuisances of typing every time mypy throws an error worthy of C++.
speaking of which... does someone know if defaults can be used for inferring TypeVars?
def foo(value: T, default: T = 42) -> T:
    return value if value else default
 
oh gawd... it seems I might have to boot into windows... heaven help me!
 
given such a function, I'd assume T to be int(or compatible) when no default is given.
but Mypy assumes that default always is int and complains T cannot match that.
 
how would you write a def__init__() function for a class with no member variables
?
def __init__(self,):
then nothing?
 
3:57 PM
@Permian why not stick to the default __init__, which already does what you describe? No need to replace it.
 
so just nothing?
 
@MisterMiyagi I know nothing about typing, but does it make a difference to Mypy if you change it to return value or default ?
 
just go straight to member variables
 
class Foo:
     def not_init(self): return 2
 
classes dont need to return?
 
3:59 PM
I agree that defining __init__ is unnecessary in the first place if you don't want it to do anything. But if you're dead-set on defining it anyway, the conventional approach for defining a function that does nothing is to use the statement pass
class Fred:
    def __init__(self):
        pass
 
@Permian judging by the wording you use, you may be trying to do something you should not be doing. Can you clarify your use-case?
 
#Likewise, if you want a class that has no methods or attributes, you can pass in the class body:
class Barney:
    pass
 
just i was told wrap my function in a class
if you need to write other functions
 
note that classes never return, and a class without member variables cannot go straight to member variables, because it doesn't have any.
 
but i have no member variables
 
4:00 PM
sounds like you are looking for a module, not a class
 
Making all of your functions into static methods of a class is a valid design, but I don't consider it necessary in all (or even most) cases.
 
@PM2Ring sadly not, Mypy is very good at getting far enough to foil my schemes.
 
@MisterMiyagi Oh well. It was worth trying, I guess. ;)
@Permian What does your function do, and what was the reason they gave for wrapping it in a class?
 
to make it production ready
if more similar functions were needed
 
I invoke the principle of YAGNI. If you need more similar functions later, then"later" is the time to refactor things and make a class.
 
4:08 PM
I'm still not clear what the requirement has to do with wrapping functions in a class. If you need more functions, you define new functions. Wrapping a class around them does not change anything.
especially if there is no state involved, classes are generally bad for packaging functions. A class implies the capability for instantiation, state and identity, which is misleading when not applicable. There are also some nuances to functions inside classes, such as the difference between cls.func and cls().func.
 
windows = [5,6,7,8,9]
className.function1(windows)
why cant this find windows?
it claims its missing the windows argument
 
how is function1 defined? does it have a self parameter?
 
yes
function1 is in the class
 
Could someone help me with the multiprocessing lib? PROBLEM: I have a I/O process going on and a GUI. I need them to both be responsive and execute . Right now my GUI thread is stil blocking my I/O operation
 
"A class implies the capability for instantiation" -- in an ideal world, yeah. Unfortunately, our world is imperfect, because namespaces are one honking great idea, but there's no way to create namespaces in Python except by using the class syntax.
 
4:15 PM
@Permian define function1 without a self parameter. You are not using it as a method, so it doesn't need one.
BTW this is exactly the kind of class confusion I was talking about.
 
what do you mean?
im so confused
 
I continue to pine for syntax in the style of namespace Whatever:
 
@MisterMiyagi Should also be decorated with @staticmethod
This is a very Javaesque coding style - "everything must be in a class"
 
@Kevin well, there's SimpleNamespace
and modules.
 
fixed: i had to create the object first
then pass the function to that
 
4:19 PM
I would just like to point out, one last time, that you (@Permian) would have none of these issues if you would not wrap the function in a class.
 
ok
 
Would you agree if I said that defensive programming essentially was about checking parameter values?

I am not so fond of wiki's definition of it, so I am trying to come up with my own.
 
totally unrelated: Dupe votes getting converted to "Does this answer your question?" comments is really confusing. Just had another OP thinking its a regular comment and replying...
 
@SebastianNielsen I suspect you are focusing on only one aspect of program defense (like the blind men and the elephant). Program state is another aspect. Network connectivity failure another. Database access is another. Existence and access to data files is another. All of these are beyond just parameter value checking.
 
Yeah, Im mainly thinking in terms of client-server interactions.
 
4:26 PM
okay... booting into windows was "interesting"... for some reason it decided it was a fresh install - so I killed that, then couldn't mount an NTFS partition because it was an "unclean shutdown"... what fun.
 
Wikipedia's "Defensive programming is a form of defensive design intended to ensure the continuing function of a piece of software under unforeseen circumstances" seems like a decent definition to me
 
Kevin, not really. Imagine a scenario in which a method is called with an unexpected parameter (a logic error made by the programmer). Now, we don't intend the method, or program, to keep executing, we intend on it to terminate with a runTimeException!

In some cases we might want to "ensure the continuing function of a piece of software", but not always. That's why I think wiki's definition is flawed.
 
"Offensive programming is a category of defensive programming" Eh?
 
@MisterMiyagi Well, the comment does invite the OP to respond... But see meta.stackexchange.com/q/339563/334566 and meta.stackexchange.com/a/339838/334566
 
Perhaps you could extend Wikipedia's definition by giving an objective definition of "unforseen circumstances" that includes things like network connectivity failure, and excludes things like calling methods with the wrong parameter
 
4:37 PM
Morning cabbage
 
Something along the lines of "failures originating from resources and interfaces not directly controlled by the developer". Calling a method with the wrong parameter doesn't qualify, since the developer controls the parameters.
 
So I have a working solution for Day 5, Part 2, but I get the wrong answer. Any tips on how to figure out what I did wrong? I don't see anything obvious that I did wrong and as far as I can tell I implemented the new instructions correctly. Source code is here
 
hey im new to unittesting
how do you test functions in a class?
 
@PM2Ring TY, I've lost track of Meta discussions on these topics.
 
@MisterMiyagi What's wrong with the OP replying?
 
4:42 PM
@Kevin not if the method belongs to a library/API. The article seems rather blurry on the details as well.
 
@Permian similar to how you test global functions. The main difference is you have to create an instance of the class, just like you do in "regular" code.
 
@Code-Apprentice That I didn't ask them a question. SO did, claiming it was me. There isn't much point going further with the conversation, but the OP doesn't know that.
 
so
test_o = class()
self.assertEqual(test_o.function1(),800)
 
I think necessarily the definition will be blurry at the edges, since "defensive programming" is not something that you can derive from first principles. It's not a property of the universe, it's a category that humans invented.
 
surely the function should be a parameter of the test?
 
4:45 PM
@Permian no, unittest doesn't allow any parameters to test functions other than self.
@Permian yes, if the function always returns 800, then that would be a perfect test.
 
@MisterMiyagi The main Meta question about the new post notices is getting rather large. But the dev Yaakov seems like a nice guy & is pretty quick to respond to bug reports. OTOH, he can't just change stuff like the new dupe auto-comments, but he is listening to feedback about it, so there's a possibility that it will get changed.
 
@MisterMiyagi I guess it depends on how the OP responds. If they say "no, that doesn't answer my question because..." and then gives clear reasons, you then have the choice whether to continue to engage or not. Someone else might pick up the conversation from there.
 
@Code-Apprentice As far as I can tell, it's just junk cluttering up my inbox so far. Which means less time to sift through the new junk that people still need help with.
 
@Code-Apprentice Your "equals" implementation doesn't look right to me
 
@SebastianNielsen Well, why are you terminating with an exception? Is it to preserve data, stop anything from happening to data/programs on the computer, prevent unexpected behaviour, or what? I'd argue that if you broaden your definition of 'software' and 'continuing function' to include the other software and data on the computer, and the potential to restart after preventing damage by shutting down early (particularly relevant eg in a machinery context), then it still makes perfect sense.
 
5:03 PM
what is the rule for writing tests?
everything in a class?
every method in a class?
 
en.wikipedia.org/wiki/Code_coverage discusses a number of ways to measure the completeness of your testing suite. "write a test for every function/method" is one possible standard, sure.
 
ok
 
I don't think you need to test "everything in a class" in the sense of testing, like, constants. If you have class Fred: CATCHPHRASE = "Yabba Dabba Doo!", you don't really need to write a test_freds_catchphrase test.
 
i want to test for the existence of a created file
 
That sounds like a good thing to test 👍
 
5:08 PM
i cant find an example online in unittest yet
 
Not all code can be found online, sometimes you have to write it yourself ;-)
8
 
ahhhhh!!!
ive done it now
 
(On the other hand, lots of people make a decent career out of pasting together snippets they find online. If capitalism says that's a useful skill, who am I to argue?)
 
pathlib.Path("some_file.txt").exists() would be a good stdlib way to see if a file exists. Now just wrap it in a unittest
 
how do you do (global) variables to be accessed by two functions in a unittesting class
i try to initaite the object but it claims it cant be done
test_o = classX(file)
it cant find classX or file (in the unittest class)
 
5:24 PM
That is not really any different from regular Python, whether you are using unittest or not. A name has to be defined or imported in order to be used.
 
im rusty guys
ive forgotten how you do this
if i put the line in a function it works weirdly
but i need to do it so it class scope for both the functions
 
If you're going to the effort of putting all your functions into classes, then you definitely should have gotten rid of all your global variables before that
 
no no
 
Or are you saying "I want to create a file object as part of the setup for a collection of tests. Then every test needs to be able to access that file object, without having to create it from scratch again"?
Presumably in the setup method you would assign the file object to an attribute of self, e.g. self.file = open("whatever")
 
i am revisiting compiler construction notes to try and understand python better
 
5:37 PM
whatever that is, sounds painful.
 
guys i dont understand what im doing wrong
why cant i instantiate a class within another class(my unittest one)
 
Provide an MCVE and I will happily investigate
 
Kevin you cruel mister
 
I have already given my best guess based on limited information, and that guess was "try overriding setup()". My full powers can only be unlocked with complete verifiable code
 
is there a way to send a link
to code? i swear there is a website for this which hosts it for a day
 
5:45 PM
A paste site, such as pastebin or dpaste, is the usual approach
 
The name test_o, created in the body of OutliersTest, is not accessible to methods defined inside OutliersTest. This is not specific to unit tests. All classes have the same scoping restrictions.
>>> class Fred:
...     x = 23
...     def f(self):
...             print(x)
...
>>> Fred().f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in f
NameError: name 'x' is not defined
 
weirdly it works when after def test_for_trivial_outliers(self):
 
The quick solution is to prefix the name with the name of the class, e.g.
>>> class Fred:
...     x = 23
...     def f(self):
...             print(Fred.x)
...
>>> Fred().f()
23
But I think the correct solution here is to not create any attributes at the class level. Instead, create a method setup() and create all of your objects inside that, as attributes of the self object, as I have described above.
 
my brain is bursting haha
 
5:51 PM
cbg all
 
cbg?
 
Cabbage.
 
Another reason you might want to do this is so that object creation is deferred until after the test class instance is instantiated. As-is, all of your code in the class body, ending with test_o.clean_outliers, executes at the very beginning of the file. Since the class Outliers hasn't been defined at that point, you won't be able to access it.
Compare to creating your objects in setup(), which only executes when the tests actually run. By that time, Outliers exists, so it should be accessible.
Long story short, try overriding setup().
pat on the back to 20 minutes ago me
 
i dont want to do anything unusual
 
Understandable. The usual way to do this sort of thing is with setup(), so I recommend it heartily.
 
5:58 PM
sorry which bit is the setup() bit needed?
 
@Kevin Which opcode are you referring to?
 
So, basically,
class OutliersTest(unittest.TestCase):
    def setup(self):
        self.tmp = pd.DataFrame(0, index=np.arange(0, 1000), columns=np.arange(1))
        self.tmp[0][800] = 100
        self.test_o = Outliers(file)
        self.windows = [3,10,20,40,80]
        self.test_o.clean_outliers(self.test_o.outliers_IQRm(self.tmp[0],self.windows),place_to_write_to = 'Outliers_removed.csv')

    def test_for_trivial_outliers(self):

        self.assertEqual(self.test_o.outliers_IQRm(self.tmp[0], self.windows),[800])
No guarantees that this will work exactly as written, since I still don't have an MCVE
@Code-Apprentice Opcode 8, line 72.
 
im trying work out the purpose of setup() in general
what problem does it overcomee exactly?
 
If setUp did not exist, it would be hard to create objects that are needed for multiple tests. As you yourself have seen.
 
thats the result
but not the cause
per se
 
6:10 PM
Hmm. I misread unittest's documentation. setUp gets called once for each test, so it's not all that useful for creating objects that need to be instantiated once for the entire suite of tests. I guess the primary motivation of setUp, in that case, is that exceptions that occur during setup are not considered a test failure.
This makes sense. If you're testing a database's "insert" functionality, and you need to create the database before you test it, then a DataBaseCouldNotBeCreatedException shouldn't be considered a failure of the database's insert functionality.
I suspect setUpClass can be used for creating objects once.
 
omg
lol
 
6:34 PM
my code is a complete mess now
 
@Kevin huh...somehow I thought opcode 8 was "greater than"
thanks for taking a look. I'll fix that when I get home tonight.
 
wim
@MisterMiyagi __qualname__.
^ Well, it can lie, but in Python what can't?
does setup get called when it was misspelled (i.e. not setUp?). I haven't used unittest.TestCase in ages.
 
6:54 PM
should i overwrite init for the test class?
ide is happy but the console hates it
 
Going by the comments at stackoverflow.com/questions/17353213/init-for-unittest-testcase, you may overwrite __init__, but it's usually preferred to just override setUp instead.
If you do override __init__, remember to call super() so the base class constructor can do its thing
 
so def super().__init__():
?
 
@Permian syntax error
 
i have no idea
i am so bad at python now haha
:((
thanks ive fixed it now
@Kevin thanks mate
 
@wim I was going to reply "builtins", then I remembered that I've overriden all of __class__, __instancecheck__, __subclasscheck__ and __mro__ to fake builtins.
dons hat of shame^2
@Permian I might have mentioned this before, but have you considered not using classes?
 
7:54 PM
@MisterMiyagi has to be used
criticise my code please!!
can anyone think of way to have a variable number of windows?
 
00:00 - 20:0020:00 - 00:00

« first day (3342 days earlier)      last day (1598 days later) »