Tag Info

New answers tagged

4

Good for you for factoring out the platform specific bits from the bulk of the code. I bet this helps keep the overall project manageable. I think your organization based on platform is the way to go. Platform-specific files go in platform-specific directories, and the files themselves can have names that match what they do. This keeps things very clear, ...


0

I would use code generation from single source. E.g. define error codes in a text file and use T4 to generate C# enum and something similar to generate python code. Or write C# enums directly and use code generation to generate python only. You dont have to parse C# code necessarily, you can use some .net tool that dynamically loads your .net assembly and ...


0

Well, dependency injection comes to mind as a default sort of boxed approach to config testing. However, there are other ways, specifically designing your code to eliminate the dependency on config file all together. You can find more details in a canonical example of dependency elimination by Brian Geihsler that talks specifically about config files.


3

In Python's syntax, a hash indicates the start of a comment, and all subsequent characters on the line are ignored. To quote the language reference: A comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining ...


0

There are at least two questions being asked here (arguably a lot more, so I'll have to ignore many of the little ones), but the solution to both comes down to writing a class that effectively encapsulates retrieving (your) data from (your) files. Since you specifically asked whether it should be a class or something else, in this language classes are the ...


3

I'd not be concerned about performance here, but about usability. Modules are loaded just once in a Python program's lifetime. Referencing elements within modules and packages, including nested modules, is virtually free. Performance doesn't matter here. Use modules to group your project into logical units; it is more readable and maintainable if things ...


0

You should store the keys in two structures simultaneously -- a tree (or heap), and a doubly-linked list. Each node of the tree must include a pointer to the corresponding entry in the linked list. The values should be stored with the tree nodes; the list entries need only the keys. To look up a value, the linked list need not be consulted or altered. To ...


0

Use a queue to manage the keys by recency: from collections import deque class SizeLimitedDefaultDict(defaultdict): last_changed = deque() def __setitem__(self, key, val): if len(self) >= self.max_size: del self[last_changed.popleft()] super.__setitem__(self, key, val) last_changed.append(key) Roughly ...


2

I would highly recommend looking into Epydoc and also Sphinx-Doc. Epydoc especially does exactly what you are asking for as stated on their website and as per my experience working with it: Epydoc is a tool for generating API documentation for Python modules, based on their docstrings.


1

My guess is that you can pursue #3 by way of #2 and that it won't require anything close to a total refactor. Often in these situations, you just need to make a few adjustments at the entry points and (sometimes) exit points. If needed, wrap your current script in a main() function. def main(args, stdin = None): if stdin is None: stdin = ...


0

I agree with Doc Brown on the matter of Liskov Substitution, but if you don't inherit from dict, how will you know you're supporting the right abstract interface? May I suggest using MutableMapping from the collections module? The docstring for MutableMapping from the source looks like this: """A MutableMapping is a generic container for associating ...


3

If there is not a good reason to not do so, I would definitely advocate a spin on option 3. As @jonsharp mentions, breaking up your utility into clean units of functionality is a good way to ensure testability. Even the smallest scripts can eventually morph into a much larger program and making sure that you have an extensible API sooner rather than later ...


1

Calling a Python script A from another Python script B through subprocess looks weird to me. I'm not sure if performance impact will matter, but still, having a dependency on A in B and being able to call public methods directly seems more powerful and convenient, especially if both A and B use pip. I would probably use subprocess in one of those cases: ...


3

You are looking for something like a mixin. A mixing is like a subclass that you can apply to multiple superclasses, to create a new combined class. Since Python supports multiple inheritance, this is fairly easy to do: class A(object): def foo(self): print("A::foo") def bar(self): print("A::bar") # a variation of A class B(A): def foo(self): ...


4

In this specific case, you don't need to subclass defaultdict at all, because defaultdict is not much more than a dict subclass with an added __missing__ method. You can simply subclass LimitedDict and add that method to the subclass: class DefaultLimitedDict(LimitedDict): def __init__(self, factory, *args, **kw): self.default_factory = factory ...


30

Deriving a class "LimitedDict" from dict with the described behaviour will probably violate the Liskov substitution principle. Most code using dictionaries will expect that all data you put into a dict will stay in there and not vanish suddenly. So you cannot easily use a LimitedDict as a replacement for a dict in most places. That's why it is not a good ...


0

Depends on how you load data from your config file. Ideally, write your program to be easily testable and reduce unnecessary dependencies. So make sure that if you change the location or format of your config file, that this affects as little code as possible. Then make sure that code can also deal with the testing. If you have a single object or class or ...


3

You have to write a test that works independent of the config file, so you can test that depending on the "simulated configuration" the output of the function or behavior of that function is correct. You would need to inject the configuration file, or the value that you are trying to simulate on your function under test. This is the only way to guarantee ...


2

PEP 8 Allows you a bit of flexibility¸but requires consistency. I would use underscored caps, as per your initial suggestion for all constants, since what will make them instantly recognizable and distinct from Class names and other variables. So in short it is right. But when working on a project where a different patterns are follow the pattern used in ...


13

I agree with you, and e.g. pylint would complain about those names too (albeit purely on a length basis). for k, v in ... gives the reader no helpful information about what they should be expecting to get from the dictionary, which makes the subsequent code harder to follow. For example, it's only at if v['tree']... that you find out that the value is ...


3

The description of the range is poor. However, there is a clearly defined in the zoning codes. From section 11-122 of Zoning Resolution (Web Version) (the linked pdf) R1-1 Single-Family Detached Residence District R1-2 Single-Family Detached Residence District R1-2A Single-Family Detached Residence District R2 Single-Family Detached Residence ...


2

You are creating a user interface -- code is a user interface, where the "user" is another programmer, or another function. If you were the user of your code rather than the developer, what would make your code easier to use? So, look at this problem from the perspective of someone calling your function. What would be the most useful exception you could ...


1

Raising a generic xception and differentiating it just by its message would be wrong because then, if you have many of them and want to react appropriately, how would you distinguish them? Regarding the choice of the exception, taking your example, I would say that ArithmeticError is something pretty low-level and focused on the arithmetic aspects of the ...


3

Mathematical definition: Closure is defined for a particular operation over a particular set. Let's say we had a set S and we have 2 elements from S, call them a and b, and we have an operation, call it @ that combines 2 elements of S. Then @ is closed over S if a@b is always in S, no matter which particular elements we picked. So you have to specify ...


2

There's no just 'closure propery', there's a 'closure under operation X'. For instance, integers are closed both under addition and multiplication. Tuples are closed under many operations, one of them being 'element composition', that is, you can use a tuple as an element of another tuple. This particular property obviously, by construction, allows to ...


2

At the risk of repeating the previous solid, deleted answer... Like addition in case of real numbers, what is the operation on which tuple hold closure property? This is an odd question. There are infinitely many operations that work on tuple (or any type for that matter), which will return some type that the operation can be applied to again. It's ...


2

If you can think of a better name than call_method_a_and_b(), a name that is a single concept, then it isn't a violation of the 'one thing' principle. If you are calling a and b in that order for different reasons in foo than in bar, so one of the two call sites might need to change while the other stays the same, then you aren't violating DRY. (For ...


3

This is what setUp is for. It is executed automatically before running each test, and can be used to initialize class fields and properties or set up the environment (in a case of integration and system tests). As for the one thing principle, it is perfectly fine to have a method A which calls methods B and C if the method A is acting on a different level ...


2

This can be done with the following python one-liner: >>> f = 123.25 >>> sum(int(ch) for ch in str(f) if ch.isdigit()) 13 >>> To break down how this works: Convert to string as @whatsisname recommends to avoid floating point rounding issues str(f) Create a list containing each character ch for ch in str(f) Throw out ...


0

For accuracy better than the general tools use to gather the data is a Python module pyproj Feed your data into something like the odometer function extracted from waypoint.py from pyproj import Geod # sudo pip3 install pyproj geoid = Geod(ellps='WGS84') # See pyproj documentation for other fun options def odometer(start, end): """Calculate ...


0

Python syntax is sensitive to whitespace. In Python, a new code block must start with a deeper level of indentation. Your if statement should be written as below, with the print statement at one deeper level of indentation. if x: print(x)


4

You're right The argument for your side is already mentioned by Robert Harvey: don't add code you don't need right now, especially since it's easy to add it later. Your reviewer is right, too On the other hand, the reviewer's point is understandable as well: Returning a generic Exception() is not very helpful to the caller: while the exception ...


1

I once participated in a Python project in which we had to employ some pretty long and confusing data processing steps. In order to maintain the minimal modularity, we developed a system in which data would flow from one class to another through a very long chain. Each chain link would only need to know the calling interface of the the "next" step of the ...


0

Okay, when I understood you correctly your problem is that you don't know why params inside the function is associated with the dictionary myParams you put into the function, right? Okay, lets start at the beginning: When you have the following python code, how does Python know that you can call the upper() method (which makes it all caps) on the variable? ...


0

You’re noticing the difference between parameters and arguments, and also the notion of scope. A parameter is a name that refers to a value passed into a function. Consider a trivial function definition: def f(x): return x Here, x is a parameter of f. An argument is the value assigned to a parameter during a function call. print f(42) Here, 42 is ...


1

You're right to wonder why this symbol doesn't seem to mean anything to the rest of the file, but its spelling isn't its only attribute. Consider its positioning. The confusion lies in trying to equate the parameter name and the argument name. You are right, there is no connection between the names as such. But if you saw a Python error message due to a ...


2

In my opinion using regular import improves readability. When reviewing Python code I like seeing where the given function or class comes from right where it is used. It saves me from scrolling to the top of the module to get that info. As for the long module names I just use the as keyword and give them short aliases: import collections as col import ...


1

Generally, it's a good idea to split something into a function of it improves the readability of your code, Or, if the part being oft repeated is somehow core to the system. In the above example, If you needed to greet your users depending on the locale, then it would make sense to have a separate greeter function.


7

Yes, a function that just raises an exception is OK. You can easily have functions like ensureWellFormed(email_address) or http_request.ensureUserLoggedIn() that raise well-documented exceptions. This de-clutters code, and many high-profile projects, e.g. Django, do use this style here and there. If you use this approach, make sure your exception objects ...


1

Maybe It can work to externalize validation logic as long as it is not externally visible and is used to enforce preconditions. Say you have an object that operates on a database connection, and most of its functions require that the connection be set up and initialized. Rather than checking the connection and conditionally throwing an exception in each ...


1

No, it would be worse functions should tell what they do. With a good naming, your check_stuff function indicates what it does. It should therefore be named e.g. checkConditionsValid depending on what it actually does. I suppose your function func also returns something or has some side effect in case that the conditions are. If not, that would be a design ...



Top 50 recent answers are included