3 ms·
The most awesome way to bundle data and functions would be what I call "standalone modules". So in Python you could do: import greeter standalone greet1
by TekMol 4y ago
The most awesome way to bundle data and functions would be what I call "standalone modules".
So in Python you could do:
import greeter standalone greet1
import greeter standalone greet2
greet1.name = 'Joe'
greet2.name = 'Sue'
greet1.greet()
greet2.greet()
And greeter.py would look like this:
name = 'nobody'
def greet():
print ('Hello '+name)
Output:
Hello Joe
Hello Sue
So just like it is now, but with a "standalone" keyword that turns an imported module into an "instance".
- CGamesPlay 4y agoIs this a real thing? What if greet imports a module, is that one shared or instanced twice?
- TekMol 4y agoThat would be shared unless it imports it with the "standalone" keyword.
- messe 4y agoYou can sorta do this with Zig, but the file you're importing has to be written with that in mind. "Modules" in Zig are just structs, so you can create instances of them (I'm handwaving a little bit here, but that's the gist of it). // Greeter.zig const std = @import("std"); const Self = @This(); name: []const u8, pub fn greet(self: *Self) void { std.debug.print("hello {s}!\n", .{self.name}); } The above file is equivalent to the struct: pub const Greeter = struct { name: []const u8, pub fn greeter(self: *Greeter) void { std.debug.print("hello {s}!\n", .{self.name}); } }; --- // main.zig const Greeter = @import("Greeter.zig"); const greeter1 = Greeter{ .name = "Joe", }; const greeter2 = Greeter{ .name = "Sue", }; pub fn main() !void { greeter1.greet(); greeter2.greet(); } A lot of data structures in the stdlib are in written in this style. EDIT for comparison, a non-standalone version would be written like this: // greeter-nonstandalone.zig: const std = @import("std"); pub var name: []const u8 = "nobody"; pub fn greet() void { std.debug.print("hello {s}!\n", .{name}); } // main-nonstandalone.zig const greeter = @import("greeter-nonstandalone.zig"); pub fn main() !void { greeter.name = "Joe"; greeter.greet(); }